1/*
2 * Copyright 2015-present 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#pragma once
18
19#include <cstddef>
20#include <type_traits>
21
22namespace folly {
23namespace detail {
24
25// Shortcut, so we don't have to use enable_if everywhere
26struct 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
33template <class T, class Enable = void>
34struct IndexableTraits;
35
36// Base class for sequences (vectors, deques)
37template <class C>
38struct IndexableTraitsSeq : public FormatTraitsBase {
39 typedef C container_type;
40 typedef typename C::value_type value_type;
41
42 static const value_type& at(const C& c, int idx) {
43 return c.at(idx);
44 }
45
46 static const value_type& at(const C& c, int idx, const value_type& dflt) {
47 return (idx >= 0 && size_t(idx) < c.size()) ? c.at(idx) : dflt;
48 }
49};
50
51// Base class for associative types (maps)
52template <class C>
53struct IndexableTraitsAssoc : public FormatTraitsBase {
54 typedef typename C::value_type::second_type value_type;
55
56 static const value_type& at(const C& c, int idx) {
57 return c.at(static_cast<typename C::key_type>(idx));
58 }
59
60 static const value_type& at(const C& c, int idx, const value_type& dflt) {
61 auto pos = c.find(static_cast<typename C::key_type>(idx));
62 return pos != c.end() ? pos->second : dflt;
63 }
64};
65
66} // namespace detail
67} // namespace folly
68