diff --git a/src/exercises/rcchars.md b/src/exercises/rcchars.md index de6a1b4..683c621 100644 --- a/src/exercises/rcchars.md +++ b/src/exercises/rcchars.md @@ -6,24 +6,12 @@ [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html ```rust -# mod rcchars { -# pub struct RcChars { _rc: std::rc::Rc, chars: std::mem::MaybeUninit> } -# impl Iterator for RcChars { -# type Item = char; -# fn next(&mut self) -> Option { unsafe { self.chars.assume_init_mut() }.next() } -# } -# impl RcChars { -# pub fn from_rc(rc: std::rc::Rc) -> Self { -# let mut new = Self { _rc: rc, chars: std::mem::MaybeUninit::uninit() }; -# new.chars.write(unsafe { &*std::rc::Rc::as_ptr(&new._rc) }.chars()); -# new -# } -# } +# mod rcchars { pub struct RcChars { rc: std::rc::Rc, index: usize } +# impl Iterator for RcChars { type Item = char; fn next(&mut self) -> Option { +# let s = self.rc.get(self.index..)?; let c = s.chars().next()?; self.index += c.len_utf8(); Some(c) +# } } impl RcChars { pub fn from_rc(rc: std::rc::Rc) -> Self { Self { rc, index: 0 } } } # impl From> for RcChars { fn from(value: std::rc::Rc) -> Self { Self::from_rc(value) } } -# impl Drop for RcChars { fn drop(&mut self) { unsafe { self.chars.assume_init_drop() } } } -# } -# use std::rc::Rc; -# use rcchars::RcChars; +# } use {std::rc::Rc, rcchars::RcChars}; { let rc = Rc::new("abc".to_string()); let rcc = RcChars::from(rc.clone()); @@ -40,6 +28,7 @@ ## Solutions +- The one in hidden code (slightly compacted). - [Implementation] used in rattlescript. - [Same solution] but with some extra comments. - [Another solution]. I prefer this one.