3 /* struct s_Buffer connected functions. */
5 /* Constructs an new buffer.
6 * If successful, the function returns a pointer to
7 * the new buffer. Otherwise, the function returns
10 Buffer_t Buffer_new(void)
12 Buffer_t buffer = (Buffer_t)calloc(1,sizeof(s_Buffer_t));
16 setErrno(E_BUFFER_ALLOCATION_FAILED);
20 buffer->data = (char*)calloc(1,DEFAULT_Buffer_CAPACITY);
23 if(NULL == buffer->data)
26 setErrno(E_BUFFER_DATA_ALLOCATION_FAILED);
30 buffer->capacity = DEFAULT_Buffer_CAPACITY;
35 /* Clears the buffer (this function don't destroy it,
36 * see Buffer_free function.).
38 void Buffer_clear(Buffer_t buffer)
40 /* must be a valid buffer. */
41 ASSERT_VALID_Buffer(buffer);
48 /* Appends a string in the buffer. If successful,
49 * the function returns true. Otherwise the function
52 bool Buffer_append(Buffer_t buffer,char* str)
54 size_t len= strlen(str);
55 size_t capacity_needed = buffer->size + len + 1;
56 size_t capacity_available = buffer->capacity - buffer->size;
58 /* must be a valid buffer. */
59 ASSERT_VALID_Buffer(buffer);
60 /* must be a valid string. */
63 if(capacity_available < capacity_needed)
65 buffer->data = (char*)realloc(buffer->data, capacity_needed);
67 if(NULL == buffer->data)
69 setErrno(E_Buffer_DATA_REALLOCATION_FAILED);
73 buffer->capacity = capacity_needed;
76 strcpy(buffer->data + buffer->size,str);
77 buffer->size += len;/* + 1*/ ;
83 * Removes all the linefeed from the buffer.
85 void Buffer_chomp(Buffer_t buffer)
87 /* must be a valid buffer. */
88 ASSERT_VALID_Buffer(buffer);
90 while ((buffer->data[buffer->size-1] == '\n') || (buffer->data[buffer->size-1] == '\r'))
92 buffer->data[buffer->size-1] = '\0';
100 * Destroy the buffer.
102 void Buffer_free(Buffer_t buffer)
107 if(NULL != buffer->data)
115 * This function returns true is the buffer is empty.
116 * Otherwrise the function returns false.
118 bool Buffer_empty(Buffer_t buffer)
120 /* must be a valid buffer. */
121 ASSERT_VALID_Buffer(buffer);
122 return (buffer->size) == 0;