#Trying to get a bytes.Buffer from a file

1 messages · Page 1 of 1 (latest)

royal grail
#

I need a file data representation that can be easily modified (insertions, deletions, etc). I have tried to use byte.Buffer however using bytes.buffer_read_from does not seem to be working as expected ( it loops for eternity )

package txt

import "core:bytes"
import "core:fmt"
import "core:io"
import "core:os"

// This file handles replacing data section of files

buffer_from_filename :: proc(path: string) -> (b: bytes.Buffer, ok: bool) {
    handle, err := os.open(path)
    if err != 0 {
        ok = false
        return
    }

    s := os.stream_from_handle(handle)
    return buffer_from_stream(s)
}

buffer_from_stream :: proc(s: io.Stream) -> (b: bytes.Buffer, ok: bool) {
    r := io.to_reader(s) or_return

    err: io.Error
    for _, err = bytes.buffer_read_from(&b, r);
        err == .None;
        _, err = bytes.buffer_read_from(&b, r) {}

    if err != .EOF {
        bytes.buffer_destroy(&b)
        ok = false
        return
    }

    return b, true
}

buffer_from :: proc {
    buffer_from_filename,
    buffer_from_stream,
}
calm jolt
#

If you want a bytes buffer you can just read the entire file and store into the buffer

buffer_from_file :: proc(file_name: string) -> (bs: bytes.Buffer, ok: bool) {
    data: []byte
    data, ok = os.read_entire_file(file_name)
    if !ok do return
    bytes.buffer_init(&bs, data)
    return
}
royal grail
#

Ahh yeah that works, though still unsure what I was doing wrong

calm jolt
#

I think you are reading infinetly into the stream. buffer_read_from reads the stream into the buffer and then you work with the buffer. It already loops over the entire stream inside the function