OLD | NEW |
| (Empty) |
1 // Copyright (c) 2010 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 // PagedArray implements an array stored using many fixed-size pages. | |
6 // | |
7 // PagedArray is a work-around to allow large arrays to be allocated when there | |
8 // is too much address space fragmentation for allocating the large arrays as | |
9 // contigous arrays. | |
10 | |
11 #ifndef COURGETTE_BSDIFF_PAGED_ARRAY_H_ | |
12 #define COURGETTE_BSDIFF_PAGED_ARRAY_H_ | |
13 | |
14 #include <stddef.h> | |
15 | |
16 #include "base/macros.h" | |
17 #include "base/process/memory.h" | |
18 | |
19 namespace courgette { | |
20 | |
21 // PagedArray implements an array stored using many fixed-size pages. | |
22 template<typename T> | |
23 class PagedArray { | |
24 enum { | |
25 // Page size in elements. Page size of 2^18 * sizeof(T) is 1MB for T = int. | |
26 kLogPageSize = 18, | |
27 kPageSize = 1 << kLogPageSize | |
28 }; | |
29 | |
30 public: | |
31 PagedArray() : pages_(NULL), page_count_(0) {} | |
32 | |
33 ~PagedArray() { clear(); } | |
34 | |
35 T& operator[](size_t i) { | |
36 size_t page = i >> kLogPageSize; | |
37 size_t offset = i & (kPageSize - 1); | |
38 // It is tempting to add a DCHECK(page < page_count_), but that makes | |
39 // bsdiff_create run 2x slower (even when compiled optimized.) | |
40 return pages_[page][offset]; | |
41 } | |
42 | |
43 // Allocates storage for |size| elements. Returns true on success and false if | |
44 // allocation fails. | |
45 bool Allocate(size_t size) { | |
46 clear(); | |
47 size_t pages_needed = (size + kPageSize - 1) >> kLogPageSize; | |
48 if (!base::UncheckedMalloc(sizeof(T*) * pages_needed, | |
49 reinterpret_cast<void**>(&pages_))) { | |
50 return false; | |
51 } | |
52 | |
53 for (page_count_ = 0; page_count_ < pages_needed; ++page_count_) { | |
54 T* block = nullptr; | |
55 if (!base::UncheckedMalloc(sizeof(T) * kPageSize, | |
56 reinterpret_cast<void**>(&block))) { | |
57 clear(); | |
58 return false; | |
59 } | |
60 pages_[page_count_] = block; | |
61 } | |
62 return true; | |
63 } | |
64 | |
65 // Releases all storage. May be called more than once. | |
66 void clear() { | |
67 if (pages_ != NULL) { | |
68 while (page_count_ != 0) { | |
69 --page_count_; | |
70 free(pages_[page_count_]); | |
71 } | |
72 free(pages_); | |
73 pages_ = NULL; | |
74 } | |
75 } | |
76 | |
77 private: | |
78 T** pages_; | |
79 size_t page_count_; | |
80 | |
81 DISALLOW_COPY_AND_ASSIGN(PagedArray); | |
82 }; | |
83 } // namespace | |
84 #endif // COURGETTE_BSDIFF_PAGED_ARRAY_H_ | |
OLD | NEW |