|
|
1.1 paf 1: /*
2:
3: String Chunk0
4: ====== ========
1.2 ! paf 5: head--------->[ptr, size]
1.1 paf 6: append_here-------->[ptr, size]
1.2 ! paf 7: link_row ........
1.1 paf 8: . .
9: . [ptr, size]
10: ...........>[link to the next chunk]
11:
12: */
13:
14: #ifndef PA_POOL_H
15: #define PA_POOL_H
16:
17: #include <stddef.h>
18:
19: class Pool;
20:
21: class String {
1.2 ! paf 22: public:
! 23: enum {
! 24: CR_PREALLOCATED_COUNT=5,
! 25: CR_GROW_PERCENT=60
! 26: };
! 27:
! 28: private:
1.1 paf 29: friend Pool;
30:
31: // the pool I'm allocated on
32: Pool *pool;
33:
1.2 ! paf 34: // last chank allocated count cache
! 35: int curr_chunk_rows;
1.1 paf 36: struct Chunk {
1.2 ! paf 37: // the number of rows per chunk
! 38: int count;
1.1 paf 39: union Row {
40: // chunk item
41: struct {
42: char *ptr; // pointer to the start of string fragment
43: size_t size; // length of the fragment
44: } item;
45: Chunk *link; // link to the next chunk in chain
1.2 ! paf 46: } first[CR_PREALLOCATED_COUNT];
1.1 paf 47: // next rows are here
1.2 ! paf 48: Chunk *preallocated_link;
1.1 paf 49: }
1.2 ! paf 50: head; // the head chunk of the chunk chain
1.1 paf 51:
52: // next append would write to this record
53: Chunk::Row *append_here;
54:
55: // the address of place where lies address
56: // of the link to the next chunk to allocate
1.2 ! paf 57: Chunk::Row *link_row;
1.1 paf 58:
59: // new&constructors made private to enforce factory manufacturing at pool
60: void *operator new(size_t size, Pool *apool);
61:
1.2 ! paf 62: void construct(Pool *apool);
! 63: String(Pool *apool) {
! 64: construct(apool);
1.1 paf 65: }
66: String(Pool *apool, char *src) {
1.2 ! paf 67: construct(apool);
1.1 paf 68: *this+=src;
69: }
70:
71: bool chunk_is_full() {
1.2 ! paf 72: return append_here == link_row;
1.1 paf 73: }
74: void expand();
75:
76: public:
77:
78: size_t size();
79: char *c_str();
80: String& operator += (char *src);
81: };
82:
83: class Pool {
84: public:
85: Pool();
86: ~Pool();
87: void *alloc(size_t size);
88: void *calloc(size_t size);
89:
90: String *makeString() {
91: return new(this) String(this);
92: }
93: String *makeString(char *src) {
94: return new(this) String(this, src);
95: }
96: };
97:
98: #endif