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));
15 setErrno(E_BUFFER_ALLOCATION_FAILED);
19 buffer->data = (char *) calloc(1, DEFAULT_Buffer_CAPACITY);
22 if (NULL == buffer->data) {
24 setErrno(E_BUFFER_DATA_ALLOCATION_FAILED);
28 buffer->capacity = DEFAULT_Buffer_CAPACITY;
33 /* Clears the buffer (this function don't destroy it,
34 * see Buffer_free function.).
36 void Buffer_clear(Buffer_t buffer)
38 /* must be a valid buffer. */
39 ASSERT_VALID_Buffer(buffer);
42 buffer->data[0] = '\n';
43 buffer->data[1] = '\0';
46 /* Appends a string in the buffer. If successful,
47 * the function returns true. Otherwise the function
50 bool Buffer_append(Buffer_t buffer, char *str)
52 size_t len = strlen(str);
53 size_t capacity_needed = buffer->size + len + 1;
54 size_t capacity_available = buffer->capacity - buffer->size;
56 /* must be a valid buffer. */
57 ASSERT_VALID_Buffer(buffer);
58 /* must be a valid string. */
61 if (capacity_available < capacity_needed) {
62 buffer->data = (char *) realloc(buffer->data, capacity_needed);
64 if (NULL == buffer->data) {
65 setErrno(E_Buffer_DATA_REALLOCATION_FAILED);
69 buffer->capacity = capacity_needed;
72 strcpy(buffer->data + buffer->size, str);
73 buffer->size += len; /* + 1 */ ;
79 * Removes all the linefeed from the buffer.
81 void Buffer_chomp(Buffer_t buffer)
83 /* must be a valid buffer. */
84 ASSERT_VALID_Buffer(buffer);
86 while ((buffer->data[buffer->size - 1] == '\n')
87 || (buffer->data[buffer->size - 1] == '\r')) {
88 buffer->data[buffer->size - 1] = '\0';
98 void Buffer_free(Buffer_t buffer)
103 if (NULL != buffer->data)
111 * This function returns true is the buffer is empty.
112 * Otherwrise the function returns false.
114 bool Buffer_empty(Buffer_t buffer)
116 /* must be a valid buffer. */
117 ASSERT_VALID_Buffer(buffer);
118 return (buffer->size) == 0;