add string type
This commit is contained in:
60
include/lstring.h
Normal file
60
include/lstring.h
Normal file
@@ -0,0 +1,60 @@
|
||||
#ifndef LTYPES_STRING_H
|
||||
#define LTYPES_STRING_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_STRING_LEN 1024
|
||||
|
||||
typedef struct {
|
||||
char* buf;
|
||||
size_t len;
|
||||
} LString;
|
||||
|
||||
LString* l_string_new(const char* fmt, ...);
|
||||
void l_string_delete(LString* str);
|
||||
int l_string_cmp(LString* strA, LString* strB);
|
||||
LString* l_string_concat(LString* strA, LString* strB);
|
||||
|
||||
#ifdef L_STRING_IMPLEMENTATION
|
||||
|
||||
#include <stdarg.h>
|
||||
|
||||
LString* l_string_new(const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
|
||||
char temp_string[MAX_STRING_LEN];
|
||||
vsnprintf(temp_string, MAX_STRING_LEN, fmt, args);
|
||||
|
||||
va_end(args);
|
||||
|
||||
LString* str = calloc(1, sizeof(LString));
|
||||
str->len = strlen(temp_string);
|
||||
|
||||
str->buf = malloc(str->len + 1);
|
||||
if (str->buf != NULL) {
|
||||
strcpy(str->buf, temp_string);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
void l_string_delete(LString* str) {
|
||||
free(str);
|
||||
}
|
||||
|
||||
int l_string_cmp(LString* strA, LString* strB) {
|
||||
int num_chars = (strA->len <= strB->len) ? strB->len : strA->len;
|
||||
return strncmp(strA->buf, strB->buf, num_chars);
|
||||
}
|
||||
|
||||
LString* l_string_concat(LString* strA, LString* strB) {
|
||||
return l_string_new("%.*s%.*s", strA->len, strA->buf, strB->len, strB->buf);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user