Cleaned up some code and set up some TString functions.
This commit is contained in:
@@ -1,4 +1,10 @@
|
||||
#include "tstring.h"
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int GetGlyphByteWidth(const char* glyph);
|
||||
void TStringCopyGlyph(const char* glyph, int length, TString* string);
|
||||
|
||||
struct __tstring {
|
||||
char* Characters;
|
||||
@@ -20,11 +26,32 @@ TString* TStringCreate(void) {
|
||||
}
|
||||
|
||||
void TStringAppendText(const char* text, TString* string) {
|
||||
int totalLength = strlen(text);
|
||||
int glyphLength = GetGlyphByteWidth(text);
|
||||
|
||||
//If the two lengths are the same then that means we have a single character.
|
||||
//Simply append it to the list and return.
|
||||
if (totalLength == glyphLength) {
|
||||
TStringCopyGlyph(text, glyphLength, string);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
char* TStringGetString(const TString* string) {
|
||||
if (!string) return NULL;
|
||||
|
||||
char* text = calloc(string->ByteCount + 1, sizeof(char));
|
||||
|
||||
if (!text) {
|
||||
fprintf(stderr, "Failed to calloc memory for TString text. %s.\n", strerror(errno));
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memcpy(text, string->Characters, string->ByteCount);
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
void TStringGetGlyph(int index, char buffer[8], const TString* string) {
|
||||
@@ -37,4 +64,48 @@ void TStringFree(TString* string) {
|
||||
if (string->Characters) free(string->Characters);
|
||||
|
||||
free(string);
|
||||
}
|
||||
|
||||
int GetGlyphByteWidth(const char* glyph) {
|
||||
// printf("Bytes for '%s': ", glyph);
|
||||
|
||||
// for(size_t i = 0; i < strlen(glyph); i++) {
|
||||
// printf("%02X ", 0xFF & glyph[i]);
|
||||
// }
|
||||
// printf("\n");
|
||||
|
||||
if ((*glyph & 0x80) == 0) {
|
||||
return 1;
|
||||
}
|
||||
else if ((*glyph & 0xE0) == 0xC0) {
|
||||
return 2;
|
||||
}
|
||||
else if ((*glyph & 0xF0) == 0xE0) {
|
||||
return 3;
|
||||
}
|
||||
else if ((*glyph & 0xF8) == 0xF0) {
|
||||
return 4;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void TStringCopyGlyph(const char* glyph, int length, TString* string) {
|
||||
if (string->ByteCount + length > string->Capacity) {
|
||||
char* buffer = realloc(string->Characters, string->Capacity * 2);
|
||||
|
||||
if (!buffer) {
|
||||
fprintf(stderr, "Failed to realloc memory TString. %s.\n", strerror(errno));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
string->Characters = buffer;
|
||||
string->Capacity *= 2;
|
||||
}
|
||||
|
||||
memcpy(&string->Characters[string->ByteCount], glyph, length);
|
||||
|
||||
string->ByteCount += length;
|
||||
string->Length++;
|
||||
}
|
||||
Reference in New Issue
Block a user