Pyrogenesis  trunk
test_file_cache.h
Go to the documentation of this file.
1 /* Copyright (c) 2010 Wildfire Games
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining
4  * a copy of this software and associated documentation files (the
5  * "Software"), to deal in the Software without restriction, including
6  * without limitation the rights to use, copy, modify, merge, publish,
7  * distribute, sublicense, and/or sell copies of the Software, and to
8  * permit persons to whom the Software is furnished to do so, subject to
9  * the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 #include "lib/self_test.h"
24 
25 #include "lib/res/file/file_cache.h"
26 #include "lib/rand.h"
27 
28 class TestFileCache : public CxxTest::TestSuite
29 {
30  enum { TEST_ALLOC_TOTAL = 100*1000*1000 };
31 public:
33  {
34  // allocated address -> its size
35  typedef std::map<void*, size_t> AllocMap;
36  AllocMap allocations;
37 
38  // put allocator through its paces by allocating several times
39  // its capacity (this ensures memory is reused)
40  srand(1);
41  size_t total_size_used = 0;
42  while(total_size_used < TEST_ALLOC_TOTAL)
43  {
44  size_t size = rand(1, TEST_ALLOC_TOTAL/16);
45  total_size_used += size;
46  void* p;
47  // until successful alloc:
48  for(;;)
49  {
50  p = file_cache_allocator_alloc(size);
51  if(p)
52  break;
53  // out of room - remove a previous allocation
54  // .. choose one at random
55  size_t chosen_idx = (size_t)rand(0, (size_t)allocations.size());
56  AllocMap::iterator it = allocations.begin();
57  for(; chosen_idx != 0; chosen_idx--)
58  ++it;
59  file_cache_allocator_free(it->first, it->second);
60  allocations.erase(it);
61  }
62 
63  // must not already have been allocated
64  TS_ASSERT_EQUALS(allocations.find(p), allocations.end());
65  allocations[p] = size;
66  }
67 
68  // reset to virginal state
69  // note: even though everything has now been freed, this is
70  // necessary since the freelists may be a bit scattered already.
71  file_cache_allocator_reset();
72  }
73 };
void test_cache_allocator()
Definition: test_file_cache.h:32
Definition: test_file_cache.h:30
Definition: test_file_cache.h:28
size_t rand(size_t min_inclusive, size_t max_exclusive)
return random integer in [min, max).
Definition: rand.cpp:53