Created
August 15, 2021 05:30
-
-
Save josephok/cbac235b6f87c5cc463bbef6fdece5c5 to your computer and use it in GitHub Desktop.
c string implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
const size_t INITIAL_SIZE = 16; | |
typedef struct String | |
{ | |
size_t len; | |
size_t cap; | |
char *chars; | |
size_t (*length)(struct String *this); | |
void (*append)(struct String *this, char *s); | |
} String; | |
size_t length(String *this) | |
{ | |
return this->len; | |
} | |
void append(String *this, char *s) | |
{ | |
size_t s_len = strlen(s); | |
if (this->len + s_len >= this->cap) | |
{ | |
size_t new_cap = this->cap << 1; | |
// 防止溢出 | |
assert(new_cap != 0); | |
this->chars = realloc(this->chars, new_cap); | |
this->cap = new_cap; | |
} | |
for (size_t i = 0; i < s_len; i++) | |
{ | |
this->chars[this->len + i] = s[i]; | |
} | |
this->chars[this->len + s_len] = '\0'; | |
this->len = this->len + s_len; | |
} | |
String new_string() | |
{ | |
String s = { | |
.len = 0, | |
.cap = INITIAL_SIZE}; | |
s.chars = malloc(INITIAL_SIZE); | |
memset(s.chars, '\0', INITIAL_SIZE); | |
s.append = append; | |
s.length = length; | |
return s; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
String s = new_string(); | |
s.append(&s, "abcd"); | |
s.append(&s, "abcd"); | |
s.append(&s, "abcd"); | |
printf("%s, length: %zu, cap: %zu\n", s.chars, s.length(&s), s.cap); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment