1
1
use std:: env;
2
+ use std:: convert:: TryFrom as _;
2
3
use std:: fmt:: Display ;
3
4
use std:: fs;
4
5
use std:: io:: { self , BufRead , BufReader } ;
@@ -212,7 +213,7 @@ fn read_single_char(fd: RawFd) -> io::Result<Option<char>> {
212
213
// if there is something to be read, take 1 byte from it
213
214
let mut buf: [ u8 ; 1 ] = [ 0 ] ;
214
215
215
- read_bytes ( fd, & mut buf, 1 ) ?;
216
+ read_bytes ( fd, & mut buf) ?;
216
217
Ok ( Some ( buf[ 0 ] as char ) )
217
218
} else {
218
219
//there is nothing to be read
@@ -223,22 +224,25 @@ fn read_single_char(fd: RawFd) -> io::Result<Option<char>> {
223
224
// Similar to libc::read. Read count bytes into slice buf from descriptor fd.
224
225
// If successful, return the number of bytes read.
225
226
// Will return an error if nothing was read, i.e when called at end of file.
226
- fn read_bytes ( fd : RawFd , buf : & mut [ u8 ] , count : u8 ) -> io:: Result < u8 > {
227
- let read = unsafe { libc:: read ( fd, buf. as_mut_ptr ( ) as * mut _ , count as usize ) } ;
228
- if read < 0 {
229
- Err ( io:: Error :: last_os_error ( ) )
230
- } else if read == 0 {
231
- Err ( io:: Error :: new (
232
- io:: ErrorKind :: UnexpectedEof ,
233
- "Reached end of file" ,
234
- ) )
235
- } else if buf[ 0 ] == b'\x03' {
236
- Err ( io:: Error :: new (
237
- io:: ErrorKind :: Interrupted ,
238
- "read interrupted" ,
239
- ) )
240
- } else {
241
- Ok ( read as u8 )
227
+ fn read_bytes ( fd : RawFd , buf : & mut [ u8 ] ) -> io:: Result < ( ) > {
228
+ let read = unsafe { libc:: read ( fd, buf. as_mut_ptr ( ) as * mut _ , buf. len ( ) ) } ;
229
+ match usize:: try_from ( read) {
230
+ Err ( std:: num:: TryFromIntError { .. } ) => Err ( io:: Error :: last_os_error ( ) ) ,
231
+ Ok ( read) => {
232
+ if read != buf. len ( ) {
233
+ Err ( io:: Error :: new (
234
+ io:: ErrorKind :: UnexpectedEof ,
235
+ "Reached end of file" ,
236
+ ) )
237
+ } else if buf. starts_with ( b"\x03 " ) {
238
+ Err ( io:: Error :: new (
239
+ io:: ErrorKind :: Interrupted ,
240
+ "read interrupted" ,
241
+ ) )
242
+ } else {
243
+ Ok ( ( ) )
244
+ }
245
+ }
242
246
}
243
247
}
244
248
@@ -301,15 +305,15 @@ fn read_single_key_impl(fd: RawFd) -> Result<Key, io::Error> {
301
305
302
306
break if byte & 224u8 == 192u8 {
303
307
// a two byte unicode character
304
- read_bytes ( fd, & mut buf[ 1 ..] , 1 ) ?;
308
+ read_bytes ( fd, & mut buf[ 1 ..] [ .. 1 ] ) ?;
305
309
Ok ( key_from_utf8 ( & buf[ ..2 ] ) )
306
310
} else if byte & 240u8 == 224u8 {
307
311
// a three byte unicode character
308
- read_bytes ( fd, & mut buf[ 1 ..] , 2 ) ?;
312
+ read_bytes ( fd, & mut buf[ 1 ..] [ .. 2 ] ) ?;
309
313
Ok ( key_from_utf8 ( & buf[ ..3 ] ) )
310
314
} else if byte & 248u8 == 240u8 {
311
315
// a four byte unicode character
312
- read_bytes ( fd, & mut buf[ 1 ..] , 3 ) ?;
316
+ read_bytes ( fd, & mut buf[ 1 ..] [ .. 3 ] ) ?;
313
317
Ok ( key_from_utf8 ( & buf[ ..4 ] ) )
314
318
} else {
315
319
Ok ( match c {
0 commit comments