2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <type_traits>
21 namespace folly { namespace detail {
23 // Shortcut, so we don't have to use enable_if everywhere
24 struct FormatTraitsBase {
28 // Traits that define enabled, value_type, and at() for anything
29 // indexable with integral keys: pointers, arrays, vectors, and maps
31 template <class T, class Enable = void> struct IndexableTraits;
33 // Base class for sequences (vectors, deques)
35 struct IndexableTraitsSeq : public FormatTraitsBase {
36 typedef C container_type;
37 typedef typename C::value_type value_type;
39 static const value_type& at(const C& c, int idx) {
43 static const value_type& at(const C& c, int idx, const value_type& dflt) {
44 return (idx >= 0 && size_t(idx) < c.size()) ? c.at(idx) : dflt;
48 // Base class for associative types (maps)
50 struct IndexableTraitsAssoc : public FormatTraitsBase {
51 typedef typename C::value_type::second_type value_type;
53 static const value_type& at(const C& c, int idx) {
54 return c.at(static_cast<typename C::key_type>(idx));
57 static const value_type& at(const C& c, int idx, const value_type& dflt) {
58 auto pos = c.find(static_cast<typename C::key_type>(idx));
59 return pos != c.end() ? pos->second : dflt;