/src/spotify-json/include/spotify/json/detail/stack.hpp
Line | Count | Source |
1 | | /* |
2 | | * Copyright (c) 2016-2017 Spotify AB |
3 | | * |
4 | | * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
5 | | * use this file except in compliance with the License. You may obtain a copy of |
6 | | * 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, WITHOUT |
12 | | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
13 | | * License for the specific language governing permissions and limitations under |
14 | | * the License. |
15 | | */ |
16 | | |
17 | | #pragma once |
18 | | |
19 | | #include <array> |
20 | | #include <cassert> |
21 | | #include <cstddef> |
22 | | #include <memory> |
23 | | #include <vector> |
24 | | #include <spotify/json/detail/macros.hpp> |
25 | | |
26 | | namespace spotify { |
27 | | namespace json { |
28 | | namespace detail { |
29 | | |
30 | | template <typename T, std::size_t inline_capacity> |
31 | | struct stack { |
32 | 1.12M | void push(T value) { |
33 | 1.12M | if (json_unlikely(_vector)) { |
34 | 1.06M | _vector->push_back(std::move(value)); |
35 | 1.06M | } else if (json_likely(_inline_size < inline_capacity)) { |
36 | 55.5k | _array[_inline_size++] = std::move(value); |
37 | 55.5k | } else { |
38 | 836 | _vector.reset(new std::vector<T>(_array.begin(), _array.end())); |
39 | 836 | _vector->push_back(std::move(value)); |
40 | 836 | } |
41 | 1.12M | } |
42 | | |
43 | 65.8k | T pop() { |
44 | 65.8k | if (json_unlikely(_vector)) { |
45 | 65.4k | auto top = _vector->back(); |
46 | 65.4k | _vector->pop_back(); |
47 | 65.4k | return top; |
48 | 65.4k | } else { |
49 | 484 | assert(_inline_size); |
50 | 484 | return _array[--_inline_size]; |
51 | 484 | } |
52 | 65.8k | } |
53 | | |
54 | | private: |
55 | | std::array<T, inline_capacity> _array; |
56 | | std::unique_ptr<std::vector<T>> _vector; |
57 | | std::size_t _inline_size = 0; |
58 | | }; |
59 | | |
60 | | } // namespace detail |
61 | | } // namespace json |
62 | | } // namespace spotify |