Created
April 25, 2019 15:42
-
-
Save raphlinus/c11541872ea2a75be357fb7dccdb3359 to your computer and use it in GitHub Desktop.
Sketch of StrSource trait for access to string data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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