Backport C++17 container access functions: size, empty, data
[folly.git] / folly / container / Access.h
1 /*
2  * Copyright 2017 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 <initializer_list>
20 #include <iterator>
21
22 /**
23  *  include or backport:
24  *  * std::size
25  *  * std::empty
26  *  * std::data
27  */
28
29 #if __cpp_lib_nonmember_container_access >= 201411 || _MSC_VER
30
31 namespace folly {
32
33 /* using override */ using std::size;
34 /* using override */ using std::empty;
35 /* using override */ using std::data;
36
37 }
38
39 #else
40
41 namespace folly {
42
43 //  mimic: std::size, C++17
44 template <typename C>
45 constexpr auto size(C const& c) -> decltype(c.size()) {
46   return c.size();
47 }
48 template <typename T, std::size_t N>
49 constexpr std::size_t size(T const (&)[N]) noexcept {
50   return N;
51 }
52
53 //  mimic: std::empty, C++17
54 template <typename C>
55 constexpr auto empty(C const& c) -> decltype(c.empty()) {
56   return c.empty();
57 }
58 template <typename T, std::size_t N>
59 constexpr bool empty(T const (&)[N]) noexcept {
60   //  while zero-length arrays are not allowed in the language, some compilers
61   //  may permit them in some cases
62   return N == 0;
63 }
64 template <typename E>
65 constexpr bool empty(std::initializer_list<E> il) noexcept {
66   return il.size() == 0;
67 }
68
69 //  mimic: std::data, C++17
70 template <typename C>
71 constexpr auto data(C& c) -> decltype(c.data()) {
72   return c.data();
73 }
74 template <typename C>
75 constexpr auto data(C const& c) -> decltype(c.data()) {
76   return c.data();
77 }
78 template <typename T, std::size_t N>
79 constexpr T* data(T (&a)[N]) noexcept {
80   return a;
81 }
82 template <typename E>
83 constexpr E const* data(std::initializer_list<E> il) noexcept {
84   return il.begin();
85 }
86
87 }
88
89 #endif