forked from rust-embedded-community/embedded-sdmmc-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_test.rs
223 lines (204 loc) · 7.31 KB
/
write_test.rs
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
//! # Tests the Embedded SDMMC Library
//! ```bash
//! $ cargo run --example write_test -- /dev/mmcblk0
//! $ cargo run --example write_test -- /dev/sda
//! ```
//!
//! If you pass a block device it should be unmounted. No testing has been
//! performed with Windows raw block devices - please report back if you try
//! this!
//!
//! ```bash
//! gunzip -kf ./disk.img.gz
//! $ cargo run --example write_test -- ./disk.img
//! ```
extern crate embedded_sdmmc;
const FILE_TO_WRITE: &str = "README.TXT";
use embedded_sdmmc::{
Block, BlockCount, BlockDevice, BlockIdx, Error, Mode, TimeSource, Timestamp, VolumeIdx,
VolumeManager,
};
use std::cell::RefCell;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::Path;
#[derive(Debug)]
struct LinuxBlockDevice {
file: RefCell<File>,
print_blocks: bool,
}
impl LinuxBlockDevice {
fn new<P>(device_name: P, print_blocks: bool) -> Result<LinuxBlockDevice, std::io::Error>
where
P: AsRef<Path>,
{
Ok(LinuxBlockDevice {
file: RefCell::new(
OpenOptions::new()
.read(true)
.write(true)
.open(device_name)?,
),
print_blocks,
})
}
}
impl BlockDevice for LinuxBlockDevice {
type Error = std::io::Error;
fn read(
&self,
blocks: &mut [Block],
start_block_idx: BlockIdx,
reason: &str,
) -> Result<(), Self::Error> {
self.file
.borrow_mut()
.seek(SeekFrom::Start(start_block_idx.into_bytes()))?;
for block in blocks.iter_mut() {
self.file.borrow_mut().read_exact(&mut block.contents)?;
if self.print_blocks {
println!(
"Read block ({}) {:?}: {:?}",
reason, start_block_idx, &block
);
}
}
Ok(())
}
fn write(&self, blocks: &[Block], start_block_idx: BlockIdx) -> Result<(), Self::Error> {
self.file
.borrow_mut()
.seek(SeekFrom::Start(start_block_idx.into_bytes()))?;
for block in blocks.iter() {
self.file.borrow_mut().write_all(&block.contents)?;
if self.print_blocks {
println!("Wrote: {:?}", &block);
}
}
Ok(())
}
fn num_blocks(&self) -> Result<BlockCount, Self::Error> {
let num_blocks = self.file.borrow().metadata().unwrap().len() / 512;
Ok(BlockCount(num_blocks as u32))
}
}
struct Clock;
impl TimeSource for Clock {
fn get_timestamp(&self) -> Timestamp {
Timestamp {
year_since_1970: 0,
zero_indexed_month: 0,
zero_indexed_day: 0,
hours: 0,
minutes: 0,
seconds: 0,
}
}
}
fn main() {
env_logger::init();
let mut args = std::env::args().skip(1);
let filename = args.next().unwrap_or_else(|| "/dev/mmcblk0".into());
println!("Opening {:?}", filename);
let print_blocks = args.find(|x| x == "-v").map(|_| true).unwrap_or(false);
let lbd = LinuxBlockDevice::new(filename, print_blocks)
.map_err(Error::DeviceError)
.unwrap();
println!("lbd: {:?}", lbd);
let mut volume_mgr = VolumeManager::new(lbd, Clock);
for volume_idx in 0..=3 {
let volume = volume_mgr.get_volume(VolumeIdx(volume_idx));
println!("volume {}: {:#?}", volume_idx, volume);
if let Ok(mut volume) = volume {
let root_dir = volume_mgr.open_root_dir(&volume).unwrap();
println!("\tListing root directory:");
volume_mgr
.iterate_dir(&volume, &root_dir, |x| {
println!("\t\tFound: {:?}", x);
})
.unwrap();
// This will panic if the file doesn't exist, use ReadWriteCreateOrTruncate or
// ReadWriteCreateOrAppend instead. ReadWriteCreate also creates a file, but it returns an
// error if the file already exists
let mut f = volume_mgr
.open_file_in_dir(&mut volume, &root_dir, FILE_TO_WRITE, Mode::ReadOnly)
.unwrap();
println!("\nReading from file {}\n", FILE_TO_WRITE);
println!("FILE STARTS:");
while !f.eof() {
let mut buffer = [0u8; 32];
let num_read = volume_mgr.read(&volume, &mut f, &mut buffer).unwrap();
for b in &buffer[0..num_read] {
if *b == 10 {
print!("\\n");
}
print!("{}", *b as char);
}
}
println!("EOF\n");
volume_mgr.close_file(&volume, f).unwrap();
let mut f = volume_mgr
.open_file_in_dir(&mut volume, &root_dir, FILE_TO_WRITE, Mode::ReadWriteAppend)
.unwrap();
let buffer1 = b"\nFile Appended\n";
let buffer = [b'a'; 8192];
println!("\nAppending to file");
let num_written1 = volume_mgr.write(&mut volume, &mut f, &buffer1[..]).unwrap();
let num_written = volume_mgr.write(&mut volume, &mut f, &buffer[..]).unwrap();
println!("Number of bytes written: {}\n", num_written + num_written1);
f.seek_from_start(0).unwrap();
println!("\tFinding {}...", FILE_TO_WRITE);
println!(
"\tFound {}?: {:?}",
FILE_TO_WRITE,
volume_mgr.find_directory_entry(&volume, &root_dir, FILE_TO_WRITE)
);
println!("\nFILE STARTS:");
while !f.eof() {
let mut buffer = [0u8; 32];
let num_read = volume_mgr.read(&volume, &mut f, &mut buffer).unwrap();
for b in &buffer[0..num_read] {
if *b == 10 {
print!("\\n");
}
print!("{}", *b as char);
}
}
println!("EOF");
volume_mgr.close_file(&volume, f).unwrap();
println!("\nTruncating file");
let mut f = volume_mgr
.open_file_in_dir(
&mut volume,
&root_dir,
FILE_TO_WRITE,
Mode::ReadWriteTruncate,
)
.unwrap();
let buffer = b"Hello\n";
let num_written = volume_mgr.write(&mut volume, &mut f, &buffer[..]).unwrap();
println!("\nNumber of bytes written: {}\n", num_written);
println!("\tFinding {}...", FILE_TO_WRITE);
println!(
"\tFound {}?: {:?}",
FILE_TO_WRITE,
volume_mgr.find_directory_entry(&volume, &root_dir, FILE_TO_WRITE)
);
f.seek_from_start(0).unwrap();
println!("\nFILE STARTS:");
while !f.eof() {
let mut buffer = [0u8; 32];
let num_read = volume_mgr.read(&volume, &mut f, &mut buffer).unwrap();
for b in &buffer[0..num_read] {
if *b == 10 {
print!("\\n");
}
print!("{}", *b as char);
}
}
println!("EOF");
volume_mgr.close_file(&volume, f).unwrap();
}
}
}