1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! # Embedded Serial traits
//!
//! Traits to describe Serial port (UART) functionality.
//!
//! A serial port is taken here to mean a device which can send and/or receive
//! data one octet at a time, in order. Octets are represented using the `u8`
//! type. We are careful here to talk only in octets, not characters (although
//! if you ASCII or UTF-8 encode your strings, they become a sequence of
//! octets).
//!
//! This crate contains traits that are suitable for embedded development.
//! This allows developers to produce crates that depend upon generic UART
//! functionality (for example, an AT command interface), allowing the
//! application developer to combine the crate with the specific UART
//! available on their board.
//!
//! It is similar to the C idea of using the functions `getc` and `putc` to
//! decouple the IO device from the library, but in a more Rustic fashion.
//!
//! Here's an example with the `MutBlockingTx` trait.
//!
//! ```
//! use embedded_serial::MutBlockingTx;
//!
//! struct SomeStruct<T> { uart: T };
//!
//! impl<T> SomeStruct<T> where T: MutBlockingTx {
//!     fn new(uart: T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart }
//!     }
//!
//!     fn write_data(&mut self) -> Result<(), <T as MutBlockingTx>::Error> {
//!         self.uart.puts(b"AT\n").map_err(|e| e.1)?;
//!         Ok(())
//!     }
//! }
//! ```
//!
//! Here's an example with the `MutBlockingTxWithTimeout` trait.
//!
//! ```
//! struct SomeStruct<T> { uart: T };
//!
//! use embedded_serial::MutBlockingTxWithTimeout;
//!
//! impl<T> SomeStruct<T> where T: MutBlockingTxWithTimeout {
//!     fn new(uart: T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart }
//!     }
//!
//!     fn write_data(&mut self, timeout: &<T as MutBlockingTxWithTimeout>::Timeout) -> Result<bool, <T as MutBlockingTxWithTimeout>::Error> {
//!         let len = self.uart.puts_wait(b"AT\n", timeout).map_err(|e| e.1)?;
//!         Ok(len == 3)
//!     }
//! }
//! ```
//!
//! Here's an example with the `MutNonBlockingTx` trait. You would call the `write_data` function until it returned `Ok(true)`.
//!
//! ```
//! use embedded_serial::MutNonBlockingTx;
//!
//! struct SomeStruct<T> {
//!     sent: Option<usize>,
//!     uart: T
//! };
//!
//! impl<T> SomeStruct<T> where T: MutNonBlockingTx {
//!
//!     fn new(uart: T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart, sent: Some(0) }
//!     }
//!
//!     fn write_data(&mut self) -> Result<bool, <T as MutNonBlockingTx>::Error> {
//!         let data = b"AT\n";
//!         if let Some(len) = self.sent {
//!             match self.uart.puts_try(&data[len..]) {
//!                 // Sent some or more of the data
//!                 Ok(sent) => {
//!                     let total = len + sent;
//!                     self.sent = if total == data.len() {
//!                         None
//!                     } else {
//!                         Some(total)
//!                     };
//!                     Ok(false)
//!                 }
//!                 // Sent some of the data but errored out
//!                 Err((sent, e)) => {
//!                     let total = len + sent;
//!                     self.sent = if total == data.len() {
//!                         None
//!                     } else {
//!                         Some(total)
//!                     };
//!                     Err(e)
//!                 }
//!             }
//!         } else {
//!             Ok(true)
//!         }
//!     }
//! }
//! ```
//!
//! In this example, we read three octets from a blocking serial port.
//!
//! ```
//! use embedded_serial::MutBlockingRx;
//!
//! pub struct SomeStruct<T> { uart: T }
//!
//! impl<T> SomeStruct<T> where T: MutBlockingRx {
//!     pub fn new(uart: T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart }
//!     }
//!
//!     pub fn read_response(&mut self) -> Result<(), <T as MutBlockingRx>::Error> {
//!         let mut buffer = [0u8; 3];
//!         // If we got an error, we don't care any many we actually received.
//!         self.uart.gets(&mut buffer).map_err(|e| e.1)?;
//!         // process data in buffer here
//!         Ok(())
//!     }
//! }
//! ```
//!
//! In this example, we read three octets from a blocking serial port, with a timeout.
//!
//! ```
//! use embedded_serial::MutBlockingRxWithTimeout;
//!
//! pub struct SomeStruct<T> { uart: T }
//!
//! impl<T> SomeStruct<T> where T: MutBlockingRxWithTimeout {
//!     pub fn new(uart: T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart }
//!     }
//!
//!     pub fn read_response(&mut self, timeout: &<T as MutBlockingRxWithTimeout>::Timeout) -> Result<bool, <T as MutBlockingRxWithTimeout>::Error> {
//!         let mut buffer = [0u8; 3];
//!         // If we got an error, we don't care any many we actually received.
//!         let len = self.uart.gets_wait(&mut buffer, timeout).map_err(|e| e.1)?;
//!         // process data in buffer here
//!         Ok(len == buffer.len())
//!     }
//! }
//! ```
//!
//! In this example, we read 16 octets from a non-blocking serial port into a
//! vector which grows to contain exactly as much as we have read so far. You
//! would call the `read_data` function until it returned `Ok(true)`. This differs
//! from the other examples in that we have an immutable reference to our UART
//! instead of owning it.
//!
//! ```
//! use embedded_serial::ImmutNonBlockingRx;
//!
//! struct SomeStruct<'a, T> where T: 'a {
//!     buffer: Vec<u8>,
//!     uart: &'a T
//! };
//!
//! const CHUNK_SIZE: usize = 4;
//! const WANTED: usize = 16;
//!
//! impl<'a, T> SomeStruct<'a, T> where T: ImmutNonBlockingRx {
//!
//!     fn new(uart: &T) -> SomeStruct<T> {
//!         SomeStruct { uart: uart, buffer: Vec::new() }
//!     }
//!
//!     fn read_data(&mut self) -> Result<bool, <T as ImmutNonBlockingRx>::Error> {
//!         let mut buffer = [0u8; CHUNK_SIZE];
//!         if self.buffer.len() < WANTED {
//!             let needed = WANTED - self.buffer.len();
//!             let this_time = if needed < CHUNK_SIZE { needed } else { CHUNK_SIZE };
//!             match self.uart.gets_try(&mut buffer[0..needed]) {
//!                 // Read some or more of the data
//!                 Ok(read) => {
//!                     self.buffer.extend(&buffer[0..read]);
//!                     Ok(self.buffer.len() == WANTED)
//!                 }
//!                 // Sent some of the data but errored out
//!                 Err((read, e)) => {
//!                     self.buffer.extend(&buffer[0..read]);
//!                     Err(e)
//!                 }
//!             }
//!         } else {
//!             Ok(true)
//!         }
//!     }
//! }
//! ```

#![no_std]
#![deny(missing_docs)]

// Earlier names for the traits, which assume mutability.
pub use MutBlockingTx as BlockingTx;
pub use MutBlockingTxWithTimeout as BlockingTxWithTimeout;
pub use MutNonBlockingTx as NonBlockingTx;
pub use MutBlockingRx as BlockingRx;
pub use MutBlockingRxWithTimeout as BlockingRxWithTimeout;
pub use MutNonBlockingRx as NonBlockingRx;

/// Implementors of this trait offer octet based serial data transmission
/// using a blocking API and requiring a mutable reference to self.
pub trait MutBlockingTx {
    /// The error type returned if a function fails.
    type Error;

    /// Write a single octet to the port's transmitter,
    /// blocking until the octet can be stored in the buffer
    /// (not necessarily that the octet has been transmitted).
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn putc(&mut self, ch: u8) -> Result<(), Self::Error>;

    /// Write a complete string to the UART.
    /// If this returns `Ok(())`, all the data was sent.
    /// Otherwise you get number of octets sent and the error.
    fn puts<I: ?Sized>(&mut self, data: &I) -> Result<(), (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        for (count, octet) in data.as_ref().iter().enumerate() {
            self.putc(*octet).map_err(|e| (count, e))?;
        }
        Ok(())
    }
}

/// Implementors of this trait offer octet based serial data transmission
/// using a blocking API with an upper bound on blocking time, and requiring a
/// mutable reference to self.
pub trait MutBlockingTxWithTimeout {
    /// The type used to specify the timeout.
    type Timeout;
    /// The error type returned if a function fails.
    type Error;

    /// Write a single octet to the port's transmitter, blocking until the
    /// octet can be stored in the buffer (not necessarily that the
    /// octet has been transmitted) or some timeout occurs.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If it times out, `Ok(None)` is returned.
    /// If it sends the data, `Ok(Some(ch))` is returned.
    /// If it fails, `Err(...)` is returned.
    fn putc_wait(&mut self, ch: u8, timeout: &Self::Timeout) -> Result<Option<u8>, Self::Error>;

    /// Attempts to write a complete string to the UART.
    /// Returns number of octets written, or an error and the number of octets written.
    /// The timeout applies to each octet individually.
    ///
    /// A result of `Ok(data.len())` means all the data was sent.
    /// A result of `Ok(size < data.len())` means only some of the data was sent then there was a timeout.
    /// A result of `Err(size, e)` means some (or all) of the data was sent then there was an error.
    fn puts_wait<I: ?Sized>(&mut self,
                            data: &I,
                            timeout: &Self::Timeout)
                            -> Result<usize, (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        let mut count: usize = 0;
        for octet in data.as_ref() {
            // If we get an error, return it (with the number of bytes sent),
            // else if we get None, we timed out so abort.
            if self.putc_wait(*octet, timeout).map_err(|e| (count, e))?.is_none() {
                break;
            }
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data transmission
/// using a non-blocking API and requiring a mutable reference to self.
pub trait MutNonBlockingTx {
    /// The error type returned if function fails.
    type Error;

    /// Try and write a single octet to the port's transmitter.
    /// Will return `Ok(None)` if the FIFO/buffer was full
    /// and the octet couldn't be stored or `Ok(Some(ch))`
    /// if it was stored OK.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn putc_try(&mut self, ch: u8) -> Result<Option<u8>, Self::Error>;

    /// Write as much of a complete string to the UART as possible.
    /// Returns the number of octets sent, plus the result from the
    /// last `putc` call. Aborts early if `putc` fails in any way.
    fn puts_try<I: ?Sized>(&mut self, data: &I) -> Result<usize, (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        let mut count = 0;
        for octet in data.as_ref() {
            // If we get an error, return it (with the number of bytes sent),
            // else if we get None, we timed out so abort.
            if self.putc_try(*octet).map_err(|e| (count, e))?.is_none() {
                break;
            }
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data reception
/// using a blocking API and requiring a mutable reference to self.
pub trait MutBlockingRx {
    /// The error type returned if a function fails.
    type Error;

    /// Read a single octet from the port's receiver,
    /// blocking until the octet can be read from the buffer.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn getc(&mut self) -> Result<u8, Self::Error>;

    /// Read a specified number of octets into the given buffer, blocking
    /// until that many have been read.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn gets<I: ?Sized>(&mut self, buffer: &mut I) -> Result<(), (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        for (count, space) in buffer.as_mut().iter_mut().enumerate() {
            *space = self.getc().map_err(|e| (count, e))?;
        }
        Ok(())
    }
}

/// Implementors of this trait offer octet based serial data reception using a
/// blocking API with an upper bound on blocking time, and requiring a mutable
/// reference to self.
pub trait MutBlockingRxWithTimeout {
    /// The type used to specify the timeout.
    type Timeout;
    /// The error type returned if `getc` fails.
    type Error;

    /// Read a single octet from the port's receiver,
    /// blocking until the octet can be read from the buffer.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If it times out, Ok(None) is returned.
    /// If it receives data, Ok(Some(data)) is returned.
    /// If it fails, Err(...) is returned.
    fn getc_wait(&mut self, timeout: &Self::Timeout) -> Result<Option<u8>, Self::Error>;

    /// Read a specified number of octets into the given buffer, blocking
    /// until that many have been read or a timeout occurs.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If the result is `Ok(size)` but `size <= buffer.len()`, you had a timeout.
    fn gets_wait<I: ?Sized>(&mut self,
                            buffer: &mut I,
                            timeout: &Self::Timeout)
                            -> Result<usize, (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        let mut count: usize = 0;
        for space in buffer.as_mut() {
            *space = match self.getc_wait(timeout) {
                Err(e) => return Err((count, e)),
                Ok(None) => return Ok(count),
                Ok(Some(ch)) => ch,
            };
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data reception using a
/// non-blocking API, and requiring a mutable reference to self.
pub trait MutNonBlockingRx {
    /// The error type returned if `getc` fails.
    type Error;

    /// Attempt to read a single octet from the port's receiver; if the buffer
    /// is empty return None.
    ///
    /// In some implementations, this can result in an Error. If not, use
    /// `type Error = !`.
    ///
    /// If it times out, Ok(None) is returned.
    /// If it receives data, Ok(Some(data)) is returned.
    /// If it fails, Err(...) is returned.
    fn getc_try(&mut self) -> Result<Option<u8>, Self::Error>;

    /// Read a specified number of octets into the given buffer, or until the
    /// data runs out.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If the result is `Ok(size)` but `size <= buffer.len()`, you ran out of data.
    fn gets_try<I: ?Sized>(&mut self, buffer: &mut I) -> Result<usize, (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        let mut count: usize = 0;
        for space in buffer.as_mut() {
            *space = match self.getc_try() {
                Err(e) => return Err((count, e)),
                Ok(None) => return Ok(count),
                Ok(Some(ch)) => ch,
            };
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data transmission
/// using a blocking API and only requiring an immutable reference to self.
pub trait ImmutBlockingTx {
    /// The error type returned if a function fails.
    type Error;

    /// Write a single octet to the port's transmitter,
    /// blocking until the octet can be stored in the buffer
    /// (not necessarily that the octet has been transmitted).
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn putc(&self, ch: u8) -> Result<(), Self::Error>;

    /// Write a complete string to the UART.
    /// If this returns `Ok(())`, all the data was sent.
    /// Otherwise you get number of octets sent and the error.
    fn puts<I: ?Sized>(&self, data: &I) -> Result<(), (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        for (count, octet) in data.as_ref().iter().enumerate() {
            self.putc(*octet).map_err(|e| (count, e))?;
        }
        Ok(())
    }
}

/// Implementors of this trait offer octet based serial data transmission
/// using a blocking API with an upper bound on blocking time, and requiring a
/// mutable reference to self.
pub trait ImmutBlockingTxWithTimeout {
    /// The type used to specify the timeout.
    type Timeout;
    /// The error type returned if a function fails.
    type Error;

    /// Write a single octet to the port's transmitter, blocking until the
    /// octet can be stored in the buffer (not necessarily that the
    /// octet has been transmitted) or some timeout occurs.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If it times out, `Ok(None)` is returned.
    /// If it sends the data, `Ok(Some(ch))` is returned.
    /// If it fails, `Err(...)` is returned.
    fn putc_wait(&self, ch: u8, timeout: &Self::Timeout) -> Result<Option<u8>, Self::Error>;

    /// Attempts to write a complete string to the UART.
    /// Returns number of octets written, or an error and the number of octets written.
    /// The timeout applies to each octet individually.
    ///
    /// A result of `Ok(data.len())` means all the data was sent.
    /// A result of `Ok(size < data.len())` means only some of the data was sent then there was a timeout.
    /// A result of `Err(size, e)` means some (or all) of the data was sent then there was an error.
    fn puts_wait<I: ?Sized>(&self,
                            data: &I,
                            timeout: &Self::Timeout)
                            -> Result<usize, (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        let mut count: usize = 0;
        for octet in data.as_ref() {
            // If we get an error, return it (with the number of bytes sent),
            // else if we get None, we timed out so abort.
            if self.putc_wait(*octet, timeout).map_err(|e| (count, e))?.is_none() {
                break;
            }
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data transmission
/// using a non-blocking API and requiring a mutable reference to self.
pub trait ImmutNonBlockingTx {
    /// The error type returned if function fails.
    type Error;

    /// Try and write a single octet to the port's transmitter.
    /// Will return `Ok(None)` if the FIFO/buffer was full
    /// and the octet couldn't be stored or `Ok(Some(ch))`
    /// if it was stored OK.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn putc_try(&self, ch: u8) -> Result<Option<u8>, Self::Error>;

    /// Write as much of a complete string to the UART as possible.
    /// Returns the number of octets sent, plus the result from the
    /// last `putc` call. Aborts early if `putc` fails in any way.
    fn puts_try<I: ?Sized>(&self, data: &I) -> Result<usize, (usize, Self::Error)>
        where I: AsRef<[u8]>
    {
        let mut count: usize = 0;
        for octet in data.as_ref() {
            // If we get an error, return it (with the number of bytes sent),
            // else if we get None, we timed out so abort.
            if self.putc_try(*octet).map_err(|e| (count, e))?.is_none() {
                break;
            }
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data reception
/// using a blocking API and requiring a mutable reference to self.
pub trait ImmutBlockingRx {
    /// The error type returned if a function fails.
    type Error;

    /// Read a single octet from the port's receiver,
    /// blocking until the octet can be read from the buffer.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn getc(&self) -> Result<u8, Self::Error>;

    /// Read a specified number of octets into the given buffer, blocking
    /// until that many have been read.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    fn gets<I: ?Sized>(&self, buffer: &mut I) -> Result<(), (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        for (count, space) in buffer.as_mut().iter_mut().enumerate() {
            *space = self.getc().map_err(|e| (count, e))?;
        }
        Ok(())
    }
}

/// Implementors of this trait offer octet based serial data reception using a
/// blocking API with an upper bound on blocking time, and requiring a mutable
/// reference to self.
pub trait ImmutBlockingRxWithTimeout {
    /// The type used to specify the timeout.
    type Timeout;
    /// The error type returned if `getc` fails.
    type Error;

    /// Read a single octet from the port's receiver,
    /// blocking until the octet can be read from the buffer.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If it times out, Ok(None) is returned.
    /// If it receives data, Ok(Some(data)) is returned.
    /// If it fails, Err(...) is returned.
    fn getc_wait(&self, timeout: &Self::Timeout) -> Result<Option<u8>, Self::Error>;

    /// Read a specified number of octets into the given buffer, blocking
    /// until that many have been read or a timeout occurs.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If the result is `Ok(size)` but `size <= buffer.len()`, you had a timeout.
    fn gets_wait<I: ?Sized>(&self,
                            buffer: &mut I,
                            timeout: &Self::Timeout)
                            -> Result<usize, (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        let mut count: usize = 0;
        for space in buffer.as_mut() {
            *space = match self.getc_wait(timeout) {
                Err(e) => return Err((count, e)),
                Ok(None) => return Ok(count),
                Ok(Some(ch)) => ch,
            };
            count += 1;
        }
        Ok(count)
    }
}

/// Implementors of this trait offer octet based serial data reception using a
/// non-blocking API, and requiring a mutable reference to self.
pub trait ImmutNonBlockingRx {
    /// The error type returned if `getc` fails.
    type Error;

    /// Attempt to read a single octet from the port's receiver; if the buffer
    /// is empty return None.
    ///
    /// In some implementations, this can result in an Error. If not, use
    /// `type Error = !`.
    ///
    /// If it times out, Ok(None) is returned.
    /// If it receives data, Ok(Some(data)) is returned.
    /// If it fails, Err(...) is returned.
    fn getc_try(&self) -> Result<Option<u8>, Self::Error>;

    /// Read a specified number of octets into the given buffer, or until the
    /// data runs out.
    ///
    /// In some implementations, this can result in an Error.
    /// If not, use `type Error = !`.
    ///
    /// If the result is `Ok(size)` but `size <= buffer.len()`, you ran out of data.
    fn gets_try<I: ?Sized>(&self, buffer: &mut I) -> Result<usize, (usize, Self::Error)>
        where I: AsMut<[u8]>
    {
        let mut count: usize = 0;
        for space in buffer.as_mut() {
            *space = match self.getc_try() {
                Err(e) => return Err((count, e)),
                Ok(None) => return Ok(count),
                Ok(Some(ch)) => ch,
            };
            count += 1;
        }
        Ok(count)
    }
}

// ****************************************************************************
//
// End Of File
//
// ****************************************************************************