blob: e30097c8f56a2b4c0b849b98f086df280e82520d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
#ifndef LIBSTRING_H
#define LIBSTRING_H
#include <stdbool.h>
#include <string.h>
/**
* @brief Represents the default capacity of the string
*/
#define BASE_STRING_SIZE 8
#define STRINGS_ARE_EQUAL(A, B) (strcmp(A, B) == 0)
/**
* @brief Represents a dynamically allocated string.
*
* This struct manages a dynamically allocated null-terminated string
* along with its length and capacity.
*/
struct string
{
size_t length; /**< The current length of the string (excluding the null
terminator). */
size_t capacity; /**< The allocated capacity of the string (always a
multiple of `BASE_STRING_SIZE`). */
char *data; /**< A pointer to the null-terminated character data. */
};
/**
* @brief Creates a heap-allocated copy of the given string.
*
* The capacity is always a multiple of `BASE_STRING_SIZE`. If `s` is
* heap-allocated, the caller must free it later. The resulting string struct
* and data are freed when `string_free` is called.
*
* @param s A null-terminated string that can be null.
* @return A pointer to a newly heap-allocated `struct string`.
*/
struct string *string_create(char *s);
/**
* @brief Frees the `struct string` and its associated data.
*
* This function frees the struct `str` and its heap-allocated null-terminated
* character data.
*
* @param str A pointer to the `struct string` to be freed.
*/
void string_free(struct string *str);
/**
* @brief Pushes a single character into the string.
*
* Resizes the string's data and capacity if needed.
*
* @param str A pointer to the `struct string` where the character will be
* added.
* @param c The character to push into the string.
* @return `true` if the push succeeds, `false` otherwise.
*/
bool string_pushc(struct string *str, char c);
/**
* @brief Pushes a null-terminated string into the string.
*
* @param str A pointer to the `struct string` where the string will be added.
* @param s A null-terminated string to push into `str`.
* @return `true` if the operation succeeds, `false` otherwise.
*/
bool string_pushstr(struct string *str, char *s);
/**
* @brief Concatenates two `struct string` objects and frees the source string.
*
* The `src` struct and its data are freed after concatenation.
*
* @param dst A pointer to the destination `struct string` to which `src` will
* be concatenated.
* @param src A pointer to the source `struct string` that will be concatenated
* and freed.
* @return `true` if the concatenation succeeds, `false` otherwise.
*/
bool string_catenate(struct string *dst, struct string *src);
struct string *string_deepcopy(struct string *str);
#endif /* ! LIBSTRING_H */
|