//: C04:CLib.cpp {O}
// Implementation of example C-like library
// Declare structure and functions:

#include "CLib.h"
#include <iostream>
using namespace std;
                                   

/* Quantity of elements to add when increasing storage: */

const int increment = 100;

/* Inizializza i campi della struct */

void initialize(CStash* s, int sz)
{

s->size = sz;
s->quantity = 0;
s->storage = 0;
s->next = 0;

}

/* Aggiunge un nuovo elemento in storage in coda all'ultimo inserito; se lo spazio allocato per storage non č sufficiente all'inserimento di un nuovo elemento viene chimata la funzione inflate. All'inserimento viene calcolata in byte la posizione in storage da cui scrivere byte per byte l'elemento passato */

int add(CStash* s, const void* element)
{

if(s->next >= s->quantity)

/* Enough space left? */

inflate(s, increment);

/* Copy element into storage, starting at next empty space: */

int startBytes = s->next * s->size;
unsigned char* e = (unsigned char*)element;
for(int i = 0; i < s->size; i++)
s->storage[startBytes + i] = e[i]; 
s->next++;
return(s->next - 1);

/* Index number */

}

/* Restituisce l'indirizzo del byte in storage dal quale inizia l'elemento cercato; se l'elemento cercato eccede alla dimensione di storage viene restituito l'indirizzo a null */

void* fetch(CStash* s, int index)
{

/* Check index boundaries: */

if(index >= s->next)
return 0;                          

/* To indicate the end
Produce pointer to desired element: */

return &(s->storage[index * s->size]);

}

/* Restituisce la posizione in byte in storage da cui si puņ scrivere */

int count(CStash* s)
{

return s->next;                   

/* Elements in CStash */

}

/* Viene calcolate la dimensione in byte del "vecchio" storage e quella del nuovo; viene poi compiato byte per byte nello spazio allocato per il nuovo storage il contenuto del vecchio. Viene, infine riassegnato il puntatore a storage alla nuova zona di memoria allocata a sua volta inizializzata */

 
void inflate(CStash* s, int increase)
{

int newQuantity = s->quantity + increase;
int newBytes = newQuantity * s->size;
int oldBytes = s->quantity * s->size;
unsigned char* b = new unsigned char[newBytes];
for(int i = 0; i < oldBytes; i++)
b[i] = s->storage[i];

/* Copy old to new */

delete [](s->storage);

/* Old storage */

s->storage = b;

/* Point to new memory */

s->quantity = newQuantity;

}

 

/* Libera la memoria allocata per memorizzare i dati */


void cleanup(CStash* s)
{

if(s->storage != 0)
{

cout << "freeing storage" << endl;
delete []s->storage;

}

} ///:~