Skip to content

Commit dc4d159

Browse files
imtsukiHadrienG2
authored andcommitted
Implement Debug&Display traits for CStr16 (#114)
* Implement Debug/Display Trait for CStr16
1 parent ba8cb63 commit dc4d159

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/data_types/strs.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use super::chars::{Char16, Char8, NUL_16, NUL_8};
22
use core::convert::TryInto;
3+
use core::fmt;
4+
use core::iter::Iterator;
35
use core::result::Result;
46
use core::slice;
57

@@ -151,4 +153,47 @@ impl CStr16 {
151153
pub fn to_u16_slice_with_nul(&self) -> &[u16] {
152154
unsafe { &*(&self.0 as *const [Char16] as *const [u16]) }
153155
}
156+
157+
/// Returns an iterator over this C string
158+
pub fn iter<'a>(&'a self) -> CStr16Iter<'a> {
159+
CStr16Iter {
160+
inner: self,
161+
pos: 0,
162+
}
163+
}
164+
}
165+
166+
/// An iterator over `CStr16`.
167+
#[derive(Debug)]
168+
pub struct CStr16Iter<'a> {
169+
inner: &'a CStr16,
170+
pos: usize,
171+
}
172+
173+
impl<'a> Iterator for CStr16Iter<'a> {
174+
type Item = &'a Char16;
175+
176+
fn next(&mut self) -> Option<Self::Item> {
177+
if self.pos >= self.inner.0.len() - 1 {
178+
None
179+
} else {
180+
self.pos += 1;
181+
self.inner.0.get(self.pos - 1)
182+
}
183+
}
184+
}
185+
186+
impl fmt::Debug for CStr16 {
187+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188+
write!(f, "CStr16({:?})", &self.0)
189+
}
190+
}
191+
192+
impl fmt::Display for CStr16 {
193+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194+
for c in self.iter() {
195+
<Char16 as fmt::Display>::fmt(&c, f)?;
196+
}
197+
Ok(())
198+
}
154199
}

0 commit comments

Comments
 (0)