lambda-calc-1/string/new.c
2025-01-13 20:36:07 -06:00

140 lines
1.8 KiB
C

#include <wchar.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <debug.h>
#include <memory/smalloc.h>
#include "struct.h"
#include "new.h"
struct string* new_string(
const wchar_t* str,
size_t olen)
{
ENTER;
struct string* this = smalloc(sizeof(*this));
size_t len = wcsnlen(str, olen);
wchar_t* data = (wchar_t*) smalloc((len + 1) * sizeof(*data));
memcpy(data, str, len * sizeof(*data));
data[len] = 0;
this->data = data;
this->n = len;
this->refcount = 1;
EXIT;
return this;
}
struct string* new_string_from_ascii(
const char* str,
size_t olen)
{
ENTER;
size_t true_len = strnlen(str, olen);
wchar_t* data = smalloc((true_len + 1) * sizeof(*data));
wchar_t* writing = data;
for (const uint8_t* reading = (void*) str; *reading; )
{
switch (*reading)
{
case 0b00000000 ... 0b01111111:
{
*writing++ = (wchar_t) *reading++;
break;
}
default:
TODO;
break;
}
}
struct string* this = smalloc(sizeof(*this));
this->data = data;
this->n = (size_t) (writing - data);
this->refcount = 1;
EXIT;
return this;
}
struct string* new_string_from_ascii_format(
const char* fmt, ...)
{
ENTER;
va_list arg;
va_start(arg, fmt);
char *out = NULL;
int len = vasprintf(&out, fmt, arg);
if (len < 0)
{
TODO;
}
dpvs(out);
struct string* this = new_string_from_ascii(out, (size_t) len);
free(out);
va_end(arg);
EXIT;
return this;
}