1 /* 2 * Copyright (c) Facebook, Inc. and its affiliates. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <cstddef> 20 #include <type_traits> 21 22 namespace folly { 23 namespace detail { 24 25 // Shortcut, so we don't have to use enable_if everywhere 26 struct FormatTraitsBase { 27 typedef void enabled; 28 }; 29 30 // Traits that define enabled, value_type, and at() for anything 31 // indexable with integral keys: pointers, arrays, vectors, and maps 32 // with integral keys 33 template <class T, class Enable = void> 34 struct IndexableTraits; 35 36 // Base class for sequences (vectors, deques) 37 template <class C> 38 struct IndexableTraitsSeq : public FormatTraitsBase { 39 typedef C container_type; 40 typedef typename C::value_type value_type; 41 atIndexableTraitsSeq42 static const value_type& at(const C& c, int idx) { return c.at(idx); } 43 atIndexableTraitsSeq44 static const value_type& at(const C& c, int idx, const value_type& dflt) { 45 return (idx >= 0 && size_t(idx) < c.size()) ? c.at(idx) : dflt; 46 } 47 }; 48 49 // Base class for associative types (maps) 50 template <class C> 51 struct IndexableTraitsAssoc : public FormatTraitsBase { 52 typedef typename C::value_type::second_type value_type; 53 atIndexableTraitsAssoc54 static const value_type& at(const C& c, int idx) { 55 return c.at(static_cast<typename C::key_type>(idx)); 56 } 57 atIndexableTraitsAssoc58 static const value_type& at(const C& c, int idx, const value_type& dflt) { 59 auto pos = c.find(static_cast<typename C::key_type>(idx)); 60 return pos != c.end() ? pos->second : dflt; 61 } 62 }; 63 64 } // namespace detail 65 } // namespace folly 66