9ff17bd63907bcdf92020de1e494a5601f2fab8f
[folly.git] / folly / FormatTraits.h
1 /*
2  * Copyright 2016 Facebook, Inc.
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 #ifndef FOLLY_FORMAT_TRAITS_H_
18 #define FOLLY_FORMAT_TRAITS_H_
19
20 #include <type_traits>
21
22 namespace folly { namespace detail {
23
24 // Shortcut, so we don't have to use enable_if everywhere
25 struct FormatTraitsBase {
26   typedef void enabled;
27 };
28
29 // Traits that define enabled, value_type, and at() for anything
30 // indexable with integral keys: pointers, arrays, vectors, and maps
31 // with integral keys
32 template <class T, class Enable = void> struct IndexableTraits;
33
34 // Base class for sequences (vectors, deques)
35 template <class C>
36 struct IndexableTraitsSeq : public FormatTraitsBase {
37   typedef C container_type;
38   typedef typename C::value_type value_type;
39
40   static const value_type& at(const C& c, int idx) {
41     return c.at(idx);
42   }
43
44   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
54   static const value_type& at(const C& c, int idx) {
55     return c.at(static_cast<typename C::key_type>(idx));
56   }
57
58   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 }}  // namespaces
65
66 #endif /* FOLLY_FORMAT_TRAITS_H_ */