feat: Buffered writes.

This commit is contained in:
jmug
2026-10-26 09:42:22 -07:00
parent 1fe8355928
commit 49cb6ab62a
+36 -7
View File
@@ -5,6 +5,7 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
@@ -118,29 +119,57 @@ int getWindowSize(int *rows, int *cols) {
return 0;
}
/*** append buffer ***/
struct abuf {
char *b;
int len;
};
#define ABUF_INIT {NULL, 0}
void abAppend(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b, ab->len + len);
if (new == NULL)
return;
// Copy s starting at the end of the existing content.
memcpy(&new[ab->len], s, len);
ab->b = new;
ab->len += len;
}
void abFree(struct abuf *ab) {
free(ab->b);
}
/*** output ***/
void editorDrawRows() {
void editorDrawRows(struct abuf *ab) {
for (int y = 0; y < E.screenrows; y++) {
write(STDOUT_FILENO, "~", 1);
abAppend(ab, "~", 1);
// No new line on the last line, the terminal scrolls past the
// first line otherwise.
if (y < E.screenrows - 1) {
write(STDOUT_FILENO, "\r\n", 2);
abAppend(ab, "\r\n", 2);
}
}
}
void editorRefreshScreen() {
struct abuf ab = ABUF_INIT;
// Clear the whole screen.
write(STDOUT_FILENO, "\x1b[2J", 4);
abAppend(&ab, "\x1b[2J", 4);
// Move cursor to top left.
write(STDOUT_FILENO, "\x1b[H", 3);
abAppend(&ab, "\x1b[H", 3);
editorDrawRows();
editorDrawRows(&ab);
write(STDOUT_FILENO, "\x1b[H", 3);
// Return cursor to top left after drawing.
abAppend(&ab, "\x1b[H", 3);
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
/*** input ***/