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
pub use self::file::*;
pub use self::memory::memory_stream::MemoryStream;
pub use self::stream_rw::stream_reader::StreamReader;
pub use self::stream_rw::stream_writer::StreamWriter;
use std::error::Error;
use StreamError;
use StreamErrorKind;
pub mod file;
pub mod memory;
pub mod stream_rw;
pub enum SeekOrigin {
Begin = 0,
Current = 1,
End = 2,
}
pub trait Stream {
fn copy_to(&mut self, target: &mut Stream) -> Result<(), Box<dyn Error>> {
if !self.can_read() {
StreamError::from_str("the current stream cannot read")?
}
if !target.can_write() {
StreamError::from_str("the target stream cannot read")?
}
let _potion = self.position();
self.set_position(0)?;
const LENGTH: usize = 1024;
let mut buffs: [u8; LENGTH] = [0; LENGTH];
loop {
let result = self.read(&mut buffs, 0, LENGTH);
match result {
Ok(size) => {
if size == 0 {
break;
} else {
let mut lp = target.write(&buffs, 0, size)?;
while lp < size {
let have = size - lp;
lp = target.write(&buffs, lp, have)?;
}
}
}
Err(e) => {
if let StreamErrorKind::End = e.err_type {
break;
} else {
return Err(Box::new(e));
}
}
}
}
target.flush()?;
self.set_position(_potion)?;
Ok(())
}
fn set_position(&mut self, _potion: u64) -> Result<(), Box<dyn Error>>;
fn position(&mut self) -> u64;
fn length(&mut self) -> u64;
fn set_length(&mut self, len:u64) -> Result<(), Box<dyn Error>>;
fn can_write(&mut self) -> bool;
fn can_read(&mut self) -> bool;
fn can_seek(&mut self) -> bool;
fn read_all(&mut self, buf: &mut Vec<u8>) -> Result<usize, StreamError>;
fn read(&mut self, buf: &mut [u8], offset: usize, count: usize) -> Result<usize, StreamError>;
fn read_byte(&mut self) -> Result<u8, StreamError>;
fn seek(&mut self, offset: i64, origin: SeekOrigin) -> Result<u64, Box<dyn Error>>;
fn write_all(&mut self, buf: &[u8]) -> Result<(), Box<dyn Error>>;
fn write(&mut self, buf: &[u8], offset: usize, count: usize) -> Result<usize, Box<dyn Error>>;
fn flush(&mut self) -> Result<(), Box<dyn Error>>;
}