Skip to content

Instantly share code, notes, and snippets.

@raphlinus
Created April 25, 2019 15:42
Show Gist options
  • Save raphlinus/c11541872ea2a75be357fb7dccdb3359 to your computer and use it in GitHub Desktop.
Save raphlinus/c11541872ea2a75be357fb7dccdb3359 to your computer and use it in GitHub Desktop.
Sketch of StrSource trait for access to string data
use std::borrow::Cow;
pub trait StrSource {
fn len(&self) -> usize;
fn str_at(&self, ix: usize) -> &str;
fn str_before(&self, ix: usize) -> &str;
fn to_string(&self) -> String {
let len = self.len();
let mut s = String::with_capacity(len);
while s.len() < len {
s.push_str(self.str_at(s.len()));
}
s
}
fn len_utf16(&self) -> usize {
let len = self.len();
let mut ix = 0;
let mut len_utf16 = 0;
while ix < len {
let s = self.str_at(ix);
for c in s.chars() {
len_utf16 += c.len_utf16()
}
ix += s.len();
}
len_utf16
}
}
impl<'a> StrSource for &'a str {
fn len(&self) -> usize {
str::len(self)
}
fn str_at(&self, ix: usize) -> &str {
&self[ix..]
}
fn str_before(&self, ix: usize) -> &str {
&self[..ix]
}
}
impl StrSource for String {
fn len(&self) -> usize {
str::len(self)
}
fn str_at(&self, ix: usize) -> &str {
&self[ix..]
}
fn str_before(&self, ix: usize) -> &str {
&self[..ix]
}
}
impl<'a> StrSource for Cow<'a, str> {
fn len(&self) -> usize {
str::len(self)
}
fn str_at(&self, ix: usize) -> &str {
&self[ix..]
}
fn str_before(&self, ix: usize) -> &str {
&self[..ix]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment