| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::{borrow::Cow, cmp::min}; |
| 8 |
|
| 9 |
use crate::STREAM_IO_BUFFER_SIZE; |
| 10 |
|
| 11 |
#[derive(Debug)] |
| 12 |
pub struct SendData { |
| 13 |
data: Cow<'static, [u8]>, |
| 14 |
offset: usize, |
| 15 |
remaining: usize, |
| 16 |
total: usize, |
| 17 |
} |
| 18 |
|
| 19 |
impl From<&[u8]> for SendData { |
| 20 |
fn from(data: &[u8]) -> Self { |
| 21 |
Self::from(data.to_vec()) |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
impl From<Vec<u8>> for SendData { |
| 26 |
fn from(data: Vec<u8>) -> Self { |
| 27 |
let remaining = data.len(); |
| 28 |
Self { |
| 29 |
total: data.len(), |
| 30 |
data: Cow::Owned(data), |
| 31 |
offset: 0, |
| 32 |
remaining, |
| 33 |
} |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
impl From<&str> for SendData { |
| 38 |
fn from(data: &str) -> Self { |
| 39 |
Self::from(data.as_bytes()) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
impl SendData { |
| 44 |
pub const fn zeroes(total: usize) -> Self { |
| 45 |
const MESSAGE: &[u8] = &[0; STREAM_IO_BUFFER_SIZE]; |
| 46 |
Self { |
| 47 |
data: Cow::Borrowed(MESSAGE), |
| 48 |
offset: 0, |
| 49 |
remaining: total, |
| 50 |
total, |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
fn slice(&self) -> &[u8] { |
| 55 |
let end = min(self.data.len(), self.offset + self.remaining); |
| 56 |
&self.data[self.offset..end] |
| 57 |
} |
| 58 |
|
| 59 |
pub fn send(&mut self, mut f: impl FnMut(&[u8]) -> usize) -> bool { |
| 60 |
while self.remaining > 0 { |
| 61 |
match f(self.slice()) { |
| 62 |
0 => { |
| 63 |
return false; |
| 64 |
} |
| 65 |
sent => { |
| 66 |
self.remaining -= sent; |
| 67 |
self.offset = (self.offset + sent) % self.data.len(); |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
self.remaining == 0 |
| 73 |
} |
| 74 |
|
| 75 |
pub const fn len(&self) -> usize { |
| 76 |
self.total |
| 77 |
} |
| 78 |
} |