cbase coverage


File: src/type/private/str_type.c
Date: 2024-07-26 20:57:32
Lines:
15/15
100.0%
Functions:
3/3
100.0%
Branches:
2/2
100.0%

Line Branch Exec Source
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <stddef.h>
5
6 #include "type.h"
7
8 /**
9 * @brief Return a copy of this string
10 *
11 * @param s The string
12 * @return void* The copy of this string
13 */
14 2 void* str_copy(const void* s) {
15 2 char* copy = (char*)malloc(sizeof(*copy) * (strlen(s) + 1));
16 2 strcpy(copy, s);
17 2 return copy;
18 }
19
20 /**
21 * @brief Return a representation of this string in a rope_t
22 *
23 * @param s The string
24 * @return rope_t* The representation of this string
25 */
26 7 rope_t* str_repr(const void* s) {
27 7 char* temp = (char*)malloc(sizeof(*temp) * (strlen(s) + 3));
28 7 sprintf(temp, "\"%s\"", (const char*)s);
29 7 rope_t* r = rope_create_with(temp);
30 7 free(temp);
31 7 return r;
32 }
33
34 /**
35 * @brief Return a hash of this string using djb2
36 *
37 * @param s The string
38 * @return uint64_t The hash of this string
39 */
40 8 uint64_t str_hash(const void* s) {
41 8 uint64_t hash = 5381;
42 char c;
43
2/2
✓ Branch 0 taken 104 times.
✓ Branch 1 taken 8 times.
112 while ((c = *(const char*)s++))
44 104 hash = ((hash << 5) + hash) + c;
45
46 8 return hash;
47 }
48
49 /// @brief String type
50 const type_t* str_type = &(type_t){
51 .identifier = "str",
52 .destroy = free,
53 .copy = str_copy,
54 .repr = str_repr,
55 .hash = str_hash,
56 .cmp = (int (*const)(const void *, const void *))strcmp
57 };
58