commit 805a837

uint  ·  2026-08-06 21:43:50 +0000 UTC
parent a117951
Strings: basic strings (create, length, free)
2 files changed,  +53, -0
+18, -0
 1@@ -0,0 +1,18 @@
 2+#ifndef ULESTR_H
 3+#define ULESTR_H
 4+
 5+#include <stddef.h>
 6+
 7+typedef char* ustr;
 8+
 9+/* get length of a string */
10+size_t ustrlen(const ustr);
11+
12+/* allocate a new string */
13+ustr ustrnew(const char*);
14+
15+/* free a string */
16+void ustrfree(ustr);
17+
18+#endif /* ULESTR_H */
19+
+35, -0
 1@@ -0,0 +1,35 @@
 2+#include <stddef.h>
 3+#include <stdio.h>
 4+#include <stdlib.h>
 5+#include <string.h>
 6+
 7+#include "ulestr.h"
 8+
 9+size_t ustrlen(const ustr str)
10+{
11+	return *((const size_t*) str - 1);
12+}
13+
14+ustr ustrnew(const char* text)
15+{
16+	/* [len][text][\0] */
17+	size_t  len = strlen(text);
18+	void*   block = malloc(sizeof(size_t) + len + 1);
19+	size_t* lenptr = (size_t*)block;
20+	ustr    textptr = (ustr)((size_t*)block + 1);
21+
22+	if (block == NULL)
23+		return NULL;
24+
25+	*lenptr = len;
26+	memcpy(textptr, text, len + 1);
27+
28+	return textptr;
29+}
30+
31+void ustrfree(ustr str)
32+{
33+	if (str)
34+		free(str);
35+}
36+