abufs should have a capacity

This commit is contained in:
Kyle Isom 2020-02-18 22:31:23 +00:00
parent e9fcf3842f
commit f680d078b6
3 changed files with 23 additions and 9 deletions

View File

@ -21,7 +21,7 @@ then
fi fi
if [ -e "/usr/lib/libefence.a" ] if [ -e "/usr/lib/libefence.a" ]
then then
OS_LIBS="${OS_LIBS} -lefence" OS_LIBS="${OS_LIBS}" # -lefence"
fi fi
else else
OS_CFLAGS="" OS_CFLAGS=""

View File

@ -3,6 +3,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
#include <wctype.h>
struct termios orig_termios; struct termios orig_termios;
@ -33,15 +34,16 @@ main()
{ {
enableRawMode(); enableRawMode();
char c; wchar_t c;
while (read(STDIN_FILENO, &c, 1) == 1 && c != 'q') { while (read(STDIN_FILENO, &c, sizeof(c)) > 0 && c != 'q') {
if (iscntrl(c)) { if (iswcntrl(c)) {
printf("$%02x\n", c); printf("$%02x\n", c);
} else { } else {
printf("$%02x ('%c')\n", c, c); printf("$%02x ('%lc')\n", c, c);
} }
} }
perror("read");
return 0; return 0;
} }

View File

@ -51,8 +51,9 @@
struct abuf { struct abuf {
char *b; char *b;
int len; int len;
int cap;
}; };
#define ABUF_INIT {NULL, 0} #define ABUF_INIT {NULL, 0, 0}
void ab_append(struct abuf *buf, const char *s, int len); void ab_append(struct abuf *buf, const char *s, int len);
void ab_free(struct abuf *buf); void ab_free(struct abuf *buf);
@ -157,10 +158,19 @@ struct editor_t {
void void
ab_append(struct abuf *buf, const char *s, int len) ab_append(struct abuf *buf, const char *s, int len)
{ {
char *nc = realloc(buf->b, buf->len + len); char *nc = buf->b;
int sz = buf->len + len;
if (nc == NULL) { if (sz >= buf->cap) {
abort(); while (sz > buf->cap) {
if (buf->cap == 0) {
buf->cap = 1;
} else {
buf->cap *= 2;
}
}
nc = realloc(nc, buf->cap);
assert(nc != NULL);
} }
memcpy(&nc[buf->len], s, len); memcpy(&nc[buf->len], s, len);
@ -174,6 +184,8 @@ ab_free(struct abuf *buf)
{ {
free(buf->b); free(buf->b);
buf->b = NULL; buf->b = NULL;
buf->len = 0;
buf->cap = 0;
} }
char char