Is there a anything in Rust that is like bufio.Reader.ReadSlice in Go?

Viewed 196

In Go, the bufio.Reader has a method ReadSlice which reads until a delimeter and returns a slice representing the data. The returned slice is essentially a view to the internal buffer. Therefore, no copying of buffer is involved in this process, although it can't do things like reading lines longer than the internal buffer size.

Is there anything similar to this (reading until delimiter without copying) in Rust standard library or any third-party crates?

1 Answers

See read_until:
Read all bytes into buf until the delimiter byte or EOF is reached.

This function will read bytes from the underlying stream until the delimiter or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

If successful, this function will return the total number of bytes read.

Example in Rust:

fn main() {
    use std::io::{self, BufRead};
    let mut cursor = io::Cursor::new(b"a-b-c");
    let mut buf = vec![];
    let num_bytes = cursor
        .read_until(b'-', &mut buf)
        .expect("reading from cursor won't fail");
    println!("{}", num_bytes); // 2
    println!("{:?}", buf); // [97, 45]
    let s = String::from_utf8(buf).expect("Invalid UTF-8");
    println!("{}", s); // a-
}

Example in Go:

package main

import (
    "bufio"
    "fmt"
    "log"
    "strings"
)

func main() {
    s := `a-b-c`
    r := strings.NewReader(s)    // type Reader interface { Read(p []byte) (n int, err error) }
    br := bufio.NewReader(r)     // NewReaderSize(4096)
    bs, err := br.ReadSlice('-') // reads to the internal buffer
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(bs)         // [97 45]
    fmt.Println(string(bs)) //a-
}
Related