Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef DSTRINGS_H
- #define DSTRINGS_H
- #include <math.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <limits.h>
- #include <assert.h>
- #define DYNAMIC_STRING_GROW_FACTOR 1.5
- typedef struct DynamicString {
- char *s;
- size_t capacity;
- size_t length;
- } DynamicString;
- void createDynamicString(DynamicString *, size_t);
- void destroyDynamicString(DynamicString *);
- void increaseDynamicStringCapacity(DynamicString *);
- void appendCharToDynamicString(DynamicString *, char);
- /* The CREATEDYNAMICSTRING function
- *
- * The function initializes a DynamicString passing by the first argument.
- * The initial capacity of the string is passing by the second argument.
- * Capacity is the max length of the string. At the same time length is
- * current length of the string. Thus the function allocates capacity + 1
- * bytes for the string (considering the null-character).
- *
- * The input pointer to DynamicString struture should be a valid pointer and
- * capacity should be greater than 0.
- */
- void createDynamicString(DynamicString *ret, size_t capacity)
- {
- assert(ret);
- assert(capacity > 0);
- ret->s = malloc(capacity + 1);
- assert(ret->s);
- ret->length = 0;
- ret->capacity = capacity;
- }
- /* The APPENDCHARTODYNAMICSTRING function
- *
- * The function appends a character to the input DynamicString. If capacity of
- * the string is not enough the function increases it.
- *
- * The input pointer to a DynamicString should be a valid pointer as well as
- * its string buffer.
- */
- void appendCharToDynamicString(DynamicString *s, char c)
- {
- assert(s);
- assert(s->s);
- if (s->length == s->capacity)
- increaseDynamicStringCapacity(s);
- s->s[s->length++] = c;
- s->s[s->length] = '\0';
- }
- /* The INCREASEDYNAMICSTRINGCAPACITY function
- *
- * The function increases capacity of the input DynamicString. Grow factor
- * is sets by a macro constant DYNAMIC_STRING_GROW_FACTOR.
- *
- * The input pointer to a DynamicString struture should be a valid pointer
- * as well as its string buffer.
- */
- void increaseDynamicStringCapacity(DynamicString *s)
- {
- assert(s);
- assert(s->s);
- const size_t newCapacity = ceil(s->capacity * DYNAMIC_STRING_GROW_FACTOR);
- s->s = realloc(s->s, newCapacity + 1);
- assert(s->s);
- s->capacity = newCapacity;
- }
- /* The DESTROYDYNAMICSTRING function
- *
- * The function destroys the input DynamicString. It frees the string buffer
- * of the input DynamicString.
- *
- * The input pointer to a DynamicString should be a valid pointer as well as
- * its string buffer.
- */
- void destroyDynamicString(DynamicString *s)
- {
- assert(s);
- assert(s->s);
- free(s->s);
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement