Skip to content

str-of-bytes - provide as many str methods as possible over owned storage

[Home | GitLab | crates.io | ReadTheDocs]

Overview

The main goal of the str-of-bytes library is to provide a way to use zero-copy deserialization routines over data that may quickly disappear, e.g. successive lines read from a file. The StrOfBytes type should help with that.

It also provides the StrLike trait so that other libraries may handle owned str-like objects on their own.

Example

Here's a function that only wants to handle string slices, but must be passed something borrowed from an ephemeral String that will be dropped after processing the current iterator item:

use std::io::{BufRead as _, BufReader};
use std::result::Result as StdResult;

use eyre::{Result, WrapErr as _};
use itertools::Itertools as _;

use str_of_bytes::{StrLike, StrOfBytes};

/// The text to handle.
const TEXT: &str = "This is a test.
Maybe... this is only a test.
Or something.
Asinglewordword!";

fn get_first_word<S>(value: S) -> S
where
    S: StrLike,
{
    value.split_once_m_char(' ').map_or(value, |pair| pair.0)
}

fn main() -> Result<()> {
    let rdr = BufReader::new(TEXT.as_bytes());
    let words: Vec<StrOfBytes> = rdr
        .lines()
        .map_ok(|line| get_first_word(StrOfBytes::from(line)))
        .collect::<StdResult<_, _>>()
        .context("handle lines")?;
    assert_eq!(words, ["This", "Maybe...", "Or", "Asinglewordword!"]);
    Ok(())
}

Crate features

  • alloc - add the AdoptableStr::from_string function and implement it in the StrOfBytes class, along with a From<String> conversion

To do

  • maybe figure out a better way to deal with the generic functions that internally use the experimental core::str::pattern::Pattern trait
  • implement more of the associated functions of the str class

Contact

The str-of-bytes library was written by Peter Pentchev. It is developed in a GitLab repository. This documentation is hosted at Ringlet with a copy at ReadTheDocs.