// String ADT Project3.cpp // EE 312 Project 3 submission by // Joseph Ryan // jbr2558 // Slip days used: 0 // Spring 2018 #include #include #include #include #include #include "String.h" #define SIGNATURE (~0xdeadbeef) /* * Helper macro to find the signature of a UTString * Treat this like a function that takes a UTString* * Accesses a uint32_t from where the signature should be located */ #define CHECK(s) (*(uint32_t*) ((s)->string + (s)->length + 1)) /* * Checks if a UTString is valid or not. */ bool isOurs(UTString* s) { if (CHECK(s) == SIGNATURE) { return true; } else { return false; } } UTString* addCheck(UTString* s) { s->string[s->length] = '\0'; CHECK(s) = ~0xdeadbeef; return s; } /* * Allocate a utstring on the heap. * Initialize the string correctly by copying src. * Return a pointer to the UTString. */ UTString* utstrdup(const char* src) { UTString* newstr = (UTString*)malloc(sizeof(UTString)); newstr->length = strlen(src); newstr->capacity = newstr->length; newstr->string = strdup(src); addCheck(newstr); return newstr; } /* * Returns the length of s. * s must be a valid UTString. */ uint32_t utstrlen(const UTString* s) { assert(isOurs((UTString*)s)); return s->length; } /* * Append the string suffix to the UTString s. * s must be a valid UTString. * Do not allocate any additional storage: only append as many characters * as will actually fit in s. * Update the length of s. * Return s with the above changes. */ UTString* utstrcat(UTString* s, const char* suffix) { assert(isOurs(s)); int32_t len = strlen(suffix); for(int32_t i = 0; s->length < s->capacity && i < len; ++i, ++s->length) { s->string[s->length] = suffix[i]; } addCheck(s); return s; } /* * Copy src into dst. * dst must be a valid UTString. * src is an ordinary string. * Do not allocate any additional storage: only copy as many characters * as will actually fit in dst. * Update the length of dst. * Return dst with the above changes. */ UTString* utstrcpy(UTString* dst, const char* src) { assert(isOurs(dst)); dst->length = 0; utstrcat(dst, src); return dst; } /* * Free all memory associated with the given UTString. */ void utstrfree(UTString* self) { assert(isOurs(self)); free(self->string); free(self); } /* * Make s have at least as much capacity as new_capacity. * s must be a valid UTString. * If s has enough capacity already, do nothing. * If s does not have enough capacity, then allocate enough capacity, * copy the old string and the null terminator, free the old string, * and update all relevant metadata. * Return s with the above changes. */ UTString* utstrrealloc(UTString* s, uint32_t new_capacity) { assert(isOurs(s)); if(new_capacity <= s->capacity) { return s; } s->capacity = new_capacity; s->string = (char*)realloc(s->string, new_capacity + 5); addCheck(s); return s; }