11//! Unblocking reader which supports waiting for strings/regexes and EOF to be present
22
33use crate :: error:: Error ;
4+ use crate :: encoding:: Encoding ;
45pub use regex:: Regex ;
56use std:: io:: prelude:: * ;
67use std:: io:: { self , BufReader } ;
@@ -108,6 +109,7 @@ pub struct NBReader {
108109 buffer : String ,
109110 eof : bool ,
110111 timeout : Option < time:: Duration > ,
112+ encoding : Encoding ,
111113}
112114
113115impl NBReader {
@@ -154,6 +156,7 @@ impl NBReader {
154156 buffer : String :: with_capacity ( 1024 ) ,
155157 eof : false ,
156158 timeout : timeout. map ( time:: Duration :: from_millis) ,
159+ encoding : Encoding :: UTF8 ,
157160 }
158161 }
159162
@@ -162,21 +165,22 @@ impl NBReader {
162165 if self . eof {
163166 return Ok ( ( ) ) ;
164167 }
165- // FIXME: Temporary flag to demonstrate utf-8 capabilities
166- let unicode = true ;
168+ // NOTE: When UTF-8 mode is on, there is no handling to salvage a
169+ // stream of chars if a broken unicode char is not completed.
167170 let mut char_buf: Vec < u8 > = Vec :: new ( ) ;
168171
169172 while let Ok ( from_channel) = self . reader . try_recv ( ) {
170173 match from_channel {
171174 Ok ( PipedChar :: Char ( c) ) => {
172- if unicode {
173- char_buf. push ( c) ;
174- if let Ok ( s) = std:: str:: from_utf8 ( & char_buf) {
175- self . buffer . push ( s. chars ( ) . next ( ) . unwrap ( ) ) ;
176- char_buf. clear ( ) ;
175+ match & self . encoding {
176+ Encoding :: ASCII => self . buffer . push ( c as char ) ,
177+ Encoding :: UTF8 => {
178+ char_buf. push ( c) ;
179+ if let Ok ( s) = std:: str:: from_utf8 ( & char_buf) {
180+ self . buffer . push ( s. chars ( ) . next ( ) . unwrap ( ) ) ;
181+ char_buf. clear ( ) ;
182+ }
177183 }
178- } else {
179- self . buffer . push ( c as char )
180184 }
181185 } ,
182186 Ok ( PipedChar :: EOF ) => self . eof = true ,
0 commit comments