Skip to content

Commit 7985fbc

Browse files
committed
auto merge of #12120 : gifnksm/rust/buffered-chars, r=alexcrichton
Add `std::io::Chars` iterator and `Buffer#chars()` method
2 parents 2780d9d + 3a610e9 commit 7985fbc

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/libstd/io/buffered.rs

+10
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,16 @@ mod test {
552552
assert_eq!(reader.read_char(), Ok('ß'));
553553
}
554554

555+
#[test]
556+
fn test_chars() {
557+
let buf = [195u8, 159u8, 'a' as u8];
558+
let mut reader = BufferedReader::with_capacity(1, BufReader::new(buf));
559+
let mut it = reader.chars();
560+
assert_eq!(it.next(), Some('ß'));
561+
assert_eq!(it.next(), Some('a'));
562+
assert_eq!(it.next(), None);
563+
}
564+
555565
#[bench]
556566
fn bench_buffered_reader(bh: &mut Harness) {
557567
bh.iter(|| {

src/libstd/io/mod.rs

+35
Original file line numberDiff line numberDiff line change
@@ -1001,6 +1001,30 @@ impl<'r, T: Buffer> Iterator<~str> for Lines<'r, T> {
10011001
}
10021002
}
10031003

1004+
/// An iterator that reads a utf8-encoded character on each iteration,
1005+
/// until `.read_char()` returns `None`.
1006+
///
1007+
/// # Notes about the Iteration Protocol
1008+
///
1009+
/// The `Chars` may yield `None` and thus terminate
1010+
/// an iteration, but continue to yield elements if iteration
1011+
/// is attempted again.
1012+
///
1013+
/// # Error
1014+
///
1015+
/// This iterator will swallow all I/O errors, transforming `Err` values to
1016+
/// `None`. If errors need to be handled, it is recommended to use the
1017+
/// `read_char` method directly.
1018+
pub struct Chars<'r, T> {
1019+
priv buffer: &'r mut T
1020+
}
1021+
1022+
impl<'r, T: Buffer> Iterator<char> for Chars<'r, T> {
1023+
fn next(&mut self) -> Option<char> {
1024+
self.buffer.read_char().ok()
1025+
}
1026+
}
1027+
10041028
/// A Buffer is a type of reader which has some form of internal buffering to
10051029
/// allow certain kinds of reading operations to be more optimized than others.
10061030
/// This type extends the `Reader` trait with a few methods that are not
@@ -1146,6 +1170,17 @@ pub trait Buffer: Reader {
11461170
None => Err(standard_error(InvalidInput))
11471171
}
11481172
}
1173+
1174+
/// Create an iterator that reads a utf8-encoded character on each iteration until EOF.
1175+
///
1176+
/// # Error
1177+
///
1178+
/// This iterator will transform all error values to `None`, discarding the
1179+
/// cause of the error. If this is undesirable, it is recommended to call
1180+
/// `read_char` directly.
1181+
fn chars<'r>(&'r mut self) -> Chars<'r, Self> {
1182+
Chars { buffer: self }
1183+
}
11491184
}
11501185

11511186
pub enum SeekStyle {

0 commit comments

Comments
 (0)