-
-
Save rust-play/605c9d2cc637ba1ed929caf6ab36faeb to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
#[derive(Debug)] | |
pub struct CharsStep<'a> { | |
string: &'a str, | |
match_len: usize, | |
} | |
impl<'a> CharsStep<'a> { | |
fn step(&self) -> Option<CharsStep<'a>> { | |
let string = &self.string[self.match_len..]; | |
if self.match_len > 5 { | |
Some(CharsStep {string, match_len: self.match_len + 1}) | |
} else { | |
None | |
} | |
} | |
} | |
// VVVVVVVVVVV Comment out this code and it compiles/runs | |
#[derive(Debug,Copy)] | |
pub struct Matched<'a> { | |
full_string: &'a str, | |
start: usize, | |
end: usize, | |
} | |
impl<'a> Clone for Matched<'a> { | |
fn clone(&self) -> Self { Matched {full_string: &self.full_string[..], start: self.start, end: self.end} } | |
} | |
impl<'a> Matched<'a> { | |
fn len(&self) -> usize { self.end - self.start } | |
fn len_chars(&self) -> usize { self.string().chars().count() } | |
fn string(&self) -> &str { &self.full_string[self.start..self.end] } | |
fn unterminated(&self) -> &str { &self.full_string[self.start..] } | |
fn remainder(&self) -> &str { &self.full_string[self.end..] } | |
fn next(&self, len: usize) -> Matched { Matched {full_string: &self.full_string[..], start: self.end, end: self.end + len }} | |
} | |
#[derive(Debug)] | |
pub struct CharsStepBad<'a> { | |
matched: Matched<'a>, | |
} | |
impl<'a> CharsStepBad<'a> { | |
fn step(&self) -> Option<CharsStepBad<'a>> { | |
if self.matched.end == self.matched.full_string.len() { return None; } | |
if let Some(size) = Some(self.matched.unterminated().len()) { | |
Some(CharsStepBad {matched: self.matched.next(size)}) | |
} else { None } | |
} | |
} | |
// ^^^^^^^^^^^ Comment out this code and it compiles/runs | |
fn main() { | |
let step = CharsStep {string: &"fourscrore and seven years ago", match_len: 6}; | |
let step2 = step.step(); | |
print!("{:?}", step2 ); | |
// VVVVVVVVVVV Comment out this code and it compiles/runs | |
let matched = Matched {full_string: "our forefathers brought forth", start: 0, end: 10}; | |
let step_bad = CharsStepBad { matched }; | |
let step_bad_2 = step_bad.step(); | |
print!("{:?}", step_bad_2 ); | |
// ^^^^^^^^^^^ Comment out this code and it compiles/runs | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment