Advertisement
Guest User

cppLib.cpp

a guest
Apr 15th, 2013
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include "CppLib.h"
  2. #include <iostream>
  3. #include <cassert>
  4. using namespace std;
  5. // Quantity of elements to add
  6. // when increasing storage:
  7. const int increment = 100;
  8.  
  9. void Stash::initialize(int sz) {
  10.   size = sz;
  11.   quantity = 0;
  12.   storage = 0;
  13.   next = 0;
  14. }
  15.  
  16. int Stash::add(const void* element) {
  17.   if(next >= quantity) // Enough space left?
  18.     inflate(increment);
  19.  
  20.   // Copy element into storage,
  21.   // starting at next empty space:
  22.   int startBytes = next * size;
  23.   unsigned char* e = (unsigned char*)element;
  24.   for(int i = 0; i < size; i++)
  25.     storage[startBytes + i] = e[i];
  26.  
  27.   next++;
  28.   return(next - 1); // Index number
  29. }
  30.  
  31. void* Stash::fetch(int index) {
  32.   // Check index boundaries:
  33.   assert(0 <= index);
  34.   if(index >= next)
  35.     return 0; // To indicate the end
  36.   // Produce pointer to desired element:
  37.   return &(storage[index * size]);
  38. }
  39.  
  40. int Stash::count() {
  41.   return next; // Number of elements in CStash
  42. }
  43.  
  44. void Stash::inflate(int increase) {
  45.   assert(increase > 0);
  46.  
  47.   int newQuantity = quantity + increase;
  48.   int newBytes = newQuantity * size;
  49.   int oldBytes = quantity * size;
  50.   unsigned char* b = new unsigned char[newBytes];
  51.  
  52.   for(int i = 0; i < oldBytes; i++)
  53.     b[i] = storage[i]; // Copy old to new
  54.  
  55.   delete []storage; // Old storage
  56.   storage = b; // Point to new memory
  57.   quantity = newQuantity;
  58. }
  59.  
  60. void Stash::cleanup() {
  61.   if(storage != 0) {
  62.     cout << "freeing storage" << endl;
  63.     delete []storage;
  64.   }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement