commit c8026372a752928e9ccbb6545e5238890c5e2f4e
parent a730d0cb3d1c8d6eb6821fd373719920aacc3c55
Author: Byron Torres <b@torresjrjr.com>
Date: Sun, 12 Sep 2021 11:11:42 +0100
Add buf_write, cmd_write, cmd_read
Diffstat:
M | buffer.ha | | | 30 | +++++++++++++++++++++++++----- |
M | command.ha | | | 38 | +++++++++++++++++++++++++++++++++++++- |
2 files changed, 62 insertions(+), 6 deletions(-)
diff --git a/buffer.ha b/buffer.ha
@@ -29,12 +29,13 @@ fn new_buffer() *buffer = {
});
};
-// Reads text from source, writes to a buffer.
-fn read(source: *io::stream, buf: *buffer) size = {
+// Reads text from *io::stream, writes to a buffer.
+// Buffer should be empty, otherwise, existing linenodes will be leaked.
+fn buf_read(buf: *buffer, source: *io::stream) size = {
let localhead = buf.head;
const localtail = buf.tail;
- let total = 0z;
+ let n = 0z;
for (true) {
const rawline = match (bufio::scanline(source)) {
@@ -43,7 +44,7 @@ fn read(source: *io::stream, buf: *buffer) size = {
rawline: []u8 => rawline,
};
//defer free(rawline);
- total += len(rawline);
+ n += len(rawline);
const value = fmt::bsprint(rawline);
@@ -59,6 +60,25 @@ fn read(source: *io::stream, buf: *buffer) size = {
localhead = ln;
};
- return total;
+ return n;
+};
+
+// Write contents of buffer to *io::stream.
+fn buf_write(buf: *buffer, dest: *io::stream) size = {
+ let ln = buf.head;
+ let n = 0z;
+ for (true) {
+ match (ln.value) {
+ headnode => {
+ ln = ln.next;
+ },
+ text: str => {
+ n += fmt::fprintln(dest, text)!;
+ ln = ln.next;
+ },
+ tailnode => break
+ };
+ };
+ return n;
};
diff --git a/command.ha b/command.ha
@@ -9,7 +9,7 @@ fn cmd_edit(buf: *buffer, fname: filename) void = {
fname: str => match (os::open(fname)) {
err: fs::error => fmt::fatal("Error {}", fs::strerror(err)),
f: io::file => {
- const n = read(&f, buf);
+ const n = buf_read(buf, &f);
if (!surpress) {
fmt::println(n)?;
};
@@ -18,3 +18,39 @@ fn cmd_edit(buf: *buffer, fname: filename) void = {
};
};
+// 'w' command
+fn cmd_write(buf: *buffer, fname: filename) void = {
+ const flags = [fs::flags::WRONLY, fs::flags::NOCTTY, fs::flags::CLOEXEC];
+ match (fname) {
+ void => void,
+ fname: str => match (os::open(fname, flags...)) {
+ err: fs::error => fmt::fatal("Error {}", fs::strerror(err)),
+ f: io::file => {
+ const n = buf_write(buf, &f);
+ if (!surpress) {
+ fmt::println(n)?;
+ };
+ },
+ },
+ };
+};
+
+// 'r' command
+fn cmd_read(buf: *buffer, fname: filename) void = {
+ const scratch = new_buffer();
+ match (fname) {
+ void => void,
+ fname: str => match (os::open(fname)) {
+ err: fs::error => fmt::fatal("Error {}", fs::strerror(err)),
+ f: io::file => {
+ const n = buf_read(scratch, &f);
+ if (!surpress) {
+ fmt::println(n)?;
+ };
+ },
+ },
+ };
+ // TODO: Insert scratch into buf appropriately.
+ // deps: buf_insert()
+};
+