1# base/containers library 2 3[TOC] 4 5## What goes here 6 7This directory contains some STL-like containers. 8 9Things should be moved here that are generally applicable across the code base. 10Don't add things here just because you need them in one place and think others 11may someday want something similar. You can put specialized containers in 12your component's directory and we can promote them here later if we feel there 13is broad applicability. 14 15### Design and naming 16 17Fundamental [//base principles](../README.md#design-and-naming) apply, i.e.: 18 19Containers should adhere as closely to STL as possible. Functions and behaviors 20not present in STL should only be added when they are related to the specific 21data structure implemented by the container. 22 23For STL-like containers our policy is that they should use STL-like naming even 24when it may conflict with the style guide. So functions and class names should 25be lower case with underscores. Non-STL-like classes and functions should use 26Google naming. Be sure to use the base namespace. 27 28## Map and set selection 29 30### Usage advice 31 32* Do not use `base::flat_map` or `base::flat_set` if the number of items will 33 be large or unbounded and elements will be inserted/deleted outside of the 34 containers constructor/destructor - they have O(n) performance on inserts 35 and deletes of individual items. 36 37* Do not default to using `std::unordered_set` and `std::unordered_map`. In 38 the common case, query performance is unlikely to be sufficiently higher 39 than `std::map` to make a difference, insert performance is slightly worse, 40 and the memory overhead is high. This makes sense mostly for large tables 41 where you expect a lot of lookups. 42 43* Most maps and sets in Chrome are small and contain objects that can be moved 44 efficiently. In this case, consider `base::flat_map` and `base::flat_set`. 45 You need to be aware of the maximum expected size of the container since 46 individual inserts and deletes are O(n), giving O(n^2) construction time for 47 the entire map. But because it avoids mallocs in most cases, inserts are 48 better or comparable to other containers even for several dozen items, and 49 efficiently-moved types are unlikely to have performance problems for most 50 cases until you have hundreds of items. If your container can be constructed 51 in one shot, the constructor from vector gives O(n log n) construction times 52 and it should be strictly better than a `std::map`. 53 54 Conceptually inserting a range of n elements into a `base::flat_map` or 55 `base::flat_set` behaves as if insert() was called for each individually 56 element. Thus in case the input range contains repeated elements, only the 57 first one of these duplicates will be inserted into the container. This 58 behaviour applies to construction from a range as well. 59 60* `base::small_map` has better runtime memory usage without the poor mutation 61 performance of large containers that `base::flat_map` has. But this 62 advantage is partially offset by additional code size. Prefer in cases where 63 you make many objects so that the code/heap tradeoff is good. 64 65* Use `std::map` and `std::set` if you can't decide. Even if they're not 66 great, they're unlikely to be bad or surprising. 67 68### Map and set details 69 70Sizes are on 64-bit platforms. Stable iterators aren't invalidated when the 71container is mutated. 72 73| Container | Empty size | Per-item overhead | Stable iterators? | Insert/delete complexity | 74|:------------------------------------------ |:--------------------- |:----------------- |:----------------- |:-----------------------------| 75| `std::map`, `std::set` | 16 bytes | 32 bytes | Yes | O(log n) | 76| `std::unordered_map`, `std::unordered_set` | 128 bytes | 16 - 24 bytes | No | O(1) | 77| `base::flat_map`, `base::flat_set` | 24 bytes | 0 (see notes) | No | O(n) | 78| `base::small_map` | 24 bytes (see notes) | 32 bytes | No | depends on fallback map type | 79 80**Takeaways:** `std::unordered_map` and `std::unordered_set` have high 81overhead for small container sizes, so prefer these only for larger workloads. 82 83Code size comparisons for a block of code (see appendix) on Windows using 84strings as keys. 85 86| Container | Code size | 87|:-------------------- |:---------- | 88| `std::unordered_map` | 1646 bytes | 89| `std::map` | 1759 bytes | 90| `base::flat_map` | 1872 bytes | 91| `base::small_map` | 2410 bytes | 92 93**Takeaways:** `base::small_map` generates more code because of the inlining of 94both brute-force and red-black tree searching. This makes it less attractive 95for random one-off uses. But if your code is called frequently, the runtime 96memory benefits will be more important. The code sizes of the other maps are 97close enough it's not worth worrying about. 98 99### std::map and std::set 100 101A red-black tree. Each inserted item requires the memory allocation of a node 102on the heap. Each node contains a left pointer, a right pointer, a parent 103pointer, and a "color" for the red-black tree (32 bytes per item on 64-bit 104platforms). 105 106### std::unordered\_map and std::unordered\_set 107 108A hash table. Implemented on Windows as a `std::vector` + `std::list` and in libc++ 109as the equivalent of a `std::vector` + a `std::forward_list`. Both implementations 110allocate an 8-entry hash table (containing iterators into the list) on 111initialization, and grow to 64 entries once 8 items are inserted. Above 64 112items, the size doubles every time the load factor exceeds 1. 113 114The empty size is `sizeof(std::unordered_map)` = 64 + the initial hash table 115size which is 8 pointers. The per-item overhead in the table above counts the 116list node (2 pointers on Windows, 1 pointer in libc++), plus amortizes the hash 117table assuming a 0.5 load factor on average. 118 119In a microbenchmark on Windows, inserts of 1M integers into a 120`std::unordered_set` took 1.07x the time of `std::set`, and queries took 0.67x 121the time of `std::set`. For a typical 4-entry set (the statistical mode of map 122sizes in the browser), query performance is identical to `std::set` and 123`base::flat_set`. On ARM, `std::unordered_set` performance can be worse because 124integer division to compute the bucket is slow, and a few "less than" operations 125can be faster than computing a hash depending on the key type. The takeaway is 126that you should not default to using unordered maps because "they're faster." 127 128### base::flat\_map and base::flat\_set 129 130A sorted `std::vector`. Seached via binary search, inserts in the middle require 131moving elements to make room. Good cache locality. For large objects and large 132set sizes, `std::vector`'s doubling-when-full strategy can waste memory. 133 134Supports efficient construction from a vector of items which avoids the O(n^2) 135insertion time of each element separately. 136 137The per-item overhead will depend on the underlying `std::vector`'s reallocation 138strategy and the memory access pattern. Assuming items are being linearly added, 139one would expect it to be 3/4 full, so per-item overhead will be 0.25 * 140sizeof(T). 141 142`flat_set` and `flat_map` support a notion of transparent comparisons. 143Therefore you can, for example, lookup `std::string_view` in a set of 144`std::strings` without constructing a temporary `std::string`. This 145functionality is based on C++14 extensions to the `std::set`/`std::map` 146interface. 147 148You can find more information about transparent comparisons in [the `less<void>` 149documentation](https://en.cppreference.com/w/cpp/utility/functional/less_void). 150 151Example, smart pointer set: 152 153```cpp 154// Declare a type alias using base::UniquePtrComparator. 155template <typename T> 156using UniquePtrSet = base::flat_set<std::unique_ptr<T>, 157 base::UniquePtrComparator>; 158 159// ... 160// Collect data. 161std::vector<std::unique_ptr<int>> ptr_vec; 162ptr_vec.reserve(5); 163std::generate_n(std::back_inserter(ptr_vec), 5, []{ 164 return std::make_unique<int>(0); 165}); 166 167// Construct a set. 168UniquePtrSet<int> ptr_set(std::move(ptr_vec)); 169 170// Use raw pointers to lookup keys. 171int* ptr = ptr_set.begin()->get(); 172EXPECT_TRUE(ptr_set.find(ptr) == ptr_set.begin()); 173``` 174 175Example `flat_map<std::string, int>`: 176 177```cpp 178base::flat_map<std::string, int> str_to_int({{"a", 1}, {"c", 2},{"b", 2}}); 179 180// Does not construct temporary strings. 181str_to_int.find("c")->second = 3; 182str_to_int.erase("c"); 183EXPECT_EQ(str_to_int.end(), str_to_int.find("c")->second); 184 185// NOTE: This does construct a temporary string. This happens since if the 186// item is not in the container, then it needs to be constructed, which is 187// something that transparent comparators don't have to guarantee. 188str_to_int["c"] = 3; 189``` 190 191### base::fixed\_flat\_map and base::fixed\_flat\_set 192 193These are specializations of `base::flat_map` and `base::flat_set` that operate 194on a sorted `std::array` instead of a sorted `std::vector`. These containers 195have immutable keys, and don't support adding or removing elements once they are 196constructed. However, these containers are constructed on the stack and don't 197have any space overhead compared to a plain array. Furthermore, these containers 198are constexpr friendly (assuming the key and mapped types are), and thus can be 199used as compile time lookup tables. 200 201To aid their constructions type deduction helpers in the form of 202`base::MakeFixedFlatMap` and `base::MakeFixedFlatSet` are provided. While these 203helpers can deal with unordered data, they require that keys are not repeated. 204This precondition is CHECKed, failing compilation if this precondition is 205violated in a constexpr context. 206 207Example: 208 209```cpp 210constexpr auto kSet = base::MakeFixedFlatSet<int>({1, 2, 3}); 211 212constexpr auto kMap = base::MakeFixedFlatMap<std::string_view, int>( 213 {{"foo", 1}, {"bar", 2}, {"baz", 3}}); 214``` 215 216Both `MakeFixedFlatSet` and `MakeFixedFlatMap` require callers to explicitly 217specify the key (and mapped) type. 218 219### base::small\_map 220 221A small inline buffer that is brute-force searched that overflows into a full 222`std::map` or `std::unordered_map`. This gives the memory benefit of 223`base::flat_map` for small data sizes without the degenerate insertion 224performance for large container sizes. 225 226Since instantiations require both code for a `std::map` and a brute-force search 227of the inline container, plus a fancy iterator to cover both cases, code size 228is larger. 229 230The initial size in the above table is assuming a very small inline table. The 231actual size will be `sizeof(int) + min(sizeof(std::map), sizeof(T) * 232inline_size)`. 233 234## Deque 235 236### Usage advice 237 238Chromium code should always use `base::circular_deque` or `base::queue` in 239preference to `std::deque` or `std::queue` due to memory usage and platform 240variation. 241 242The `base::circular_deque` implementation (and the `base::queue` which uses it) 243provide performance consistent across platforms that better matches most 244programmer's expectations on performance (it doesn't waste as much space as 245libc++ and doesn't do as many heap allocations as MSVC). It also generates less 246code than `std::queue`: using it across the code base saves several hundred 247kilobytes. 248 249Since `base::deque` does not have stable iterators and it will move the objects 250it contains, it may not be appropriate for all uses. If you need these, 251consider using a `std::list` which will provide constant time insert and erase. 252 253### std::deque and std::queue 254 255The implementation of `std::deque` varies considerably which makes it hard to 256reason about. All implementations use a sequence of data blocks referenced by 257an array of pointers. The standard guarantees random access, amortized 258constant operations at the ends, and linear mutations in the middle. 259 260In Microsoft's implementation, each block is the smaller of 16 bytes or the 261size of the contained element. This means in practice that every expansion of 262the deque of non-trivial classes requires a heap allocation. libc++ (on Android 263and Mac) uses 4K blocks which eliminates the problem of many heap allocations, 264but generally wastes a large amount of space (an Android analysis revealed more 265than 2.5MB wasted space from deque alone, resulting in some optimizations). 266libstdc++ uses an intermediate-size 512-byte buffer. 267 268Microsoft's implementation never shrinks the deque capacity, so the capacity 269will always be the maximum number of elements ever contained. libstdc++ 270deallocates blocks as they are freed. libc++ keeps up to two empty blocks. 271 272### base::circular_deque and base::queue 273 274A deque implemented as a circular buffer in an array. The underlying array will 275grow like a `std::vector` while the beginning and end of the deque will move 276around. The items will wrap around the underlying buffer so the storage will 277not be contiguous, but fast random access iterators are still possible. 278 279When the underlying buffer is filled, it will be reallocated and the constents 280moved (like a `std::vector`). The underlying buffer will be shrunk if there is 281too much wasted space (_unlike_ a `std::vector`). As a result, iterators are 282not stable across mutations. 283 284## Stack 285 286`std::stack` is like `std::queue` in that it is a wrapper around an underlying 287container. The default container is `std::deque` so everything from the deque 288section applies. 289 290Chromium provides `base/containers/stack.h` which defines `base::stack` that 291should be used in preference to `std::stack`. This changes the underlying 292container to `base::circular_deque`. The result will be very similar to 293manually specifying a `std::vector` for the underlying implementation except 294that the storage will shrink when it gets too empty (vector will never 295reallocate to a smaller size). 296 297Watch out: with some stack usage patterns it's easy to depend on unstable 298behavior: 299 300```cpp 301base::stack<Foo> stack; 302for (...) { 303 Foo& current = stack.top(); 304 DoStuff(); // May call stack.push(), say if writing a parser. 305 current.done = true; // Current may reference deleted item! 306} 307``` 308 309## Safety 310 311Code throughout Chromium, running at any level of privilege, may directly or 312indirectly depend on these containers. Much calling code implicitly or 313explicitly assumes that these containers are safe, and won't corrupt memory. 314Unfortunately, [such assumptions have not always proven 315true](https://bugs.chromium.org/p/chromium/issues/detail?id=817982). 316 317Therefore, we are making an effort to ensure basic safety in these classes so 318that callers' assumptions are true. In particular, we are adding bounds checks, 319arithmetic overflow checks, and checks for internal invariants to the base 320containers where necessary. Here, safety means that the implementation will 321`CHECK`. 322 323As of 8 August 2018, we have added checks to the following classes: 324 325- `base::span` 326- `base::RingBuffer` 327- `base::small_map` 328 329Ultimately, all base containers will have these checks. 330 331### Safety, completeness, and efficiency 332 333Safety checks can affect performance at the micro-scale, although they do not 334always. On a larger scale, if we can have confidence that these fundamental 335classes and templates are minimally safe, we can sometimes avoid the security 336requirement to sandbox code that (for example) processes untrustworthy inputs. 337Sandboxing is a relatively heavyweight response to memory safety problems, and 338in our experience not all callers can afford to pay it. 339 340(However, where affordable, privilege separation and reduction remain Chrome 341Security Team's first approach to a variety of safety and security problems.) 342 343One can also imagine that the safety checks should be passed on to callers who 344require safety. There are several problems with that approach: 345 346- Not all authors of all call sites will always 347 - know when they need safety 348 - remember to write the checks 349 - write the checks correctly 350 - write the checks maximally efficiently, considering 351 - space 352 - time 353 - object code size 354- These classes typically do not document themselves as being unsafe 355- Some call sites have their requirements change over time 356 - Code that gets moved from a low-privilege process into a high-privilege 357 process 358 - Code that changes from accepting inputs from only trustworthy sources to 359 accepting inputs from all sources 360- Putting the checks in every call site results in strictly larger object code 361 than centralizing them in the callee 362 363Therefore, the minimal checks that we are adding to these base classes are the 364most efficient and effective way to achieve the beginning of the safety that we 365need. (Note that we cannot account for undefined behavior in callers.) 366 367## Appendix 368 369### Code for map code size comparison 370 371This just calls insert and query a number of times, with `printf`s that prevent 372things from being dead-code eliminated. 373 374```cpp 375TEST(Foo, Bar) { 376 base::small_map<std::map<std::string, Flubber>> foo; 377 foo.insert(std::make_pair("foo", Flubber(8, "bar"))); 378 foo.insert(std::make_pair("bar", Flubber(8, "bar"))); 379 foo.insert(std::make_pair("foo1", Flubber(8, "bar"))); 380 foo.insert(std::make_pair("bar1", Flubber(8, "bar"))); 381 foo.insert(std::make_pair("foo", Flubber(8, "bar"))); 382 foo.insert(std::make_pair("bar", Flubber(8, "bar"))); 383 auto found = foo.find("asdf"); 384 printf("Found is %d\n", (int)(found == foo.end())); 385 found = foo.find("foo"); 386 printf("Found is %d\n", (int)(found == foo.end())); 387 found = foo.find("bar"); 388 printf("Found is %d\n", (int)(found == foo.end())); 389 found = foo.find("asdfhf"); 390 printf("Found is %d\n", (int)(found == foo.end())); 391 found = foo.find("bar1"); 392 printf("Found is %d\n", (int)(found == foo.end())); 393} 394``` 395