Skip to content

Commit feba674

Browse files
authored
C: Optimize hb_string() to compute length at compile time (#1318)
This pull request converts the `hb_string()` function to a macro and renames the existing `hb_string` function to `hb_string_from_c_string`. We do this in order to optimize `hb_string()` calls with static string literals so that they have no runtime-overhead for converting a C-String to a `hb_string_T`. This applies for calls like: ```c hb_string("<%") hb_string("%>") ``` For dynamic strings it will fallback to `hb_string_from_c_string()`: ```c hb_string(variable) hb_string(message) ```
1 parent 61fabe9 commit feba674

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/include/util/hb_string.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@ typedef struct HB_STRING_STRUCT {
1515
#define HB_STRING_EMPTY ((hb_string_T){ .data = "", .length = 0 })
1616
#define HB_STRING_NULL ((hb_string_T){ .data = NULL, .length = 0 })
1717

18-
hb_string_T hb_string(const char* null_terminated_c_string);
18+
hb_string_T hb_string_from_c_string(const char* null_terminated_c_string);
19+
20+
#define hb_string(string) \
21+
(__builtin_constant_p(string) \
22+
? ((hb_string_T){ .data = (char*)(string), .length = (uint32_t)__builtin_strlen(string) }) \
23+
: hb_string_from_c_string(string))
24+
1925
hb_string_T hb_string_slice(hb_string_T string, uint32_t offset);
2026

2127
bool hb_string_equals(hb_string_T a, hb_string_T b);

src/util/hb_string.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#include <string.h>
77
#include <strings.h>
88

9-
hb_string_T hb_string(const char* null_terminated_c_string) {
9+
hb_string_T hb_string_from_c_string(const char* null_terminated_c_string) {
1010
if (null_terminated_c_string == NULL) { return HB_STRING_NULL; }
1111

1212
hb_string_T string;

0 commit comments

Comments
 (0)