diff options
author | Holden Rohrer <hr@hrhr.dev> | 2020-03-30 17:21:54 -0400 |
---|---|---|
committer | Holden Rohrer <hr@hrhr.dev> | 2020-03-30 17:21:56 -0400 |
commit | f89d0c407e0a581826559dc1e118cb6583889849 (patch) | |
tree | 2898732b04b49c5bd7e7f6f9c0dc01a901614d17 | |
parent | 463bf27d90a66ffe027b252cbce0d0167d1bfc0a (diff) |
cleanup and a bugfix
peekstrbuf didn't properly move its str pointer when creating, so it
only worked on the granularity of the object. There is a pattern here
that still needs to be cleaned up significantly (iterators using min()
internally to determine their end, sort of).
-rw-r--r-- | buf.c | 36 |
1 files changed, 21 insertions, 15 deletions
@@ -52,28 +52,34 @@ void shortenbuf(buf* buffer){ buf_node* tmp = buffer->tail; buffer->tail = buffer->tail->next; free(tmp); - buffer->pop = 0; } char popchrbuf(buf* buffer){ - if (buffer->pop == buffer->cap) shortenbuf(buffer); + if (buffer->pop == buffer->cap){ + shortenbuf(buffer); + buffer->pop = 0; + } buffer->pop++; return buffer->tail->text[buffer->pop-1]; } char* popstrbuf(buf* buffer, size_t ct){ char* str = malloc((ct+1)*sizeof(char)); str[ct] = 0; - size_t rem; - for (size_t loc = 0; ct>loc; loc += rem){ - if (buffer->pop == buffer->cap) shortenbuf(buffer); - rem = min(buffer->cap, ct-loc); - memcpy(str+loc, buffer->tail->text+buffer->pop, rem); - buffer->pop += rem; - } /* probably some inefficiencies here*/ + memcpy(str, buffer->tail->text+buffer->pop, + min(ct, buffer->cap-buffer->pop)); + size_t loc; + for (loc = buffer->cap - buffer->pop; loc < ct; loc += buffer->cap){ + shortenbuf(buffer); + memcpy(str+loc, buffer->tail->text, min(ct-loc, buffer->cap)); + } + buffer->pop = ct - loc + buffer->cap; return str; } void inschrbuf(buf* buffer, char chr){ - if (buffer->ins == buffer->cap) extendbuf(buffer); + if (buffer->ins == buffer->cap){ + extendbuf(buffer); + buffer->ins = 0; + } buffer->ins++; buffer->head->text[buffer->ins-1] = chr; } @@ -81,12 +87,11 @@ void insstrbuf(buf* buffer, char* str){ size_t len = strlen(str); size_t tgt = min(len, buffer->cap - buffer->ins); memcpy(buffer->head->text+buffer->ins, str, tgt); - buffer->ins += len; - buffer->ins %= buffer->cap; for (;tgt<len; tgt += buffer->cap){ extendbuf(buffer); memcpy(buffer->head->text, str+tgt, min(len-tgt, buffer->cap)); } + buffer->ins = len - tgt + buffer->cap; } char* peekstrbuf(buf* buffer, size_t loc, size_t len){ @@ -96,9 +101,10 @@ char* peekstrbuf(buf* buffer, size_t loc, size_t len){ loc += buffer->pop; for (start = buffer->tail; loc>buffer->cap; loc -= buffer->cap) start = start->next; // start,loc is where one starts streaming - while (len > 0){ - memcpy(str, start->text+loc, min(buffer->cap-loc, len)); - len -= min(buffer->cap - loc, len); + size_t bytect; + for (size_t tgt = 0; len > 0; len -= bytect, tgt += bytect){ + bytect = min(buffer->cap - loc, len); + memcpy(str+tgt, start->text+loc, bytect); loc = 0; } return str; |