Skip to content

Commit 1aff680

Browse files
committed
fix data saving / reading
1 parent 377be0f commit 1aff680

File tree

3 files changed

+22
-22
lines changed

3 files changed

+22
-22
lines changed

Cargo.lock

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "draw-together"
3-
version = "2.2.0"
3+
version = "2.2.1"
44
edition = "2021"
55

66
[[bin]]

src/data.rs

+20-20
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::sync::Arc;
22
use tokio::{
33
fs::{File, OpenOptions},
4-
io::{AsyncReadExt, AsyncWriteExt},
4+
io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
55
sync::Mutex,
66
};
77

@@ -169,7 +169,9 @@ impl Data {
169169
None => None,
170170
};
171171

172-
let mut data: Vec<u32>;
172+
let mut data: Vec<u32> = Vec::with_capacity(RESOLUTION);
173+
data.resize(RESOLUTION, 0);
174+
173175
if file.is_some() {
174176
let mut file_data: Vec<u8> = Vec::with_capacity(RESOLUTION * 4);
175177
file.as_mut()
@@ -178,21 +180,11 @@ impl Data {
178180
.await
179181
.unwrap();
180182

181-
data = file_data
182-
.chunks_exact(4)
183-
.map(|chunk| {
184-
let mut buf = [0; 4];
185-
buf.copy_from_slice(chunk);
186-
187-
u32::from_le_bytes(buf)
188-
})
189-
.collect::<Vec<u32>>();
190-
data.resize(RESOLUTION, 0);
191-
} else {
192-
data = Vec::with_capacity(RESOLUTION);
193-
data.resize(RESOLUTION, 0);
194-
195-
println!("data: {:?}", &data.len());
183+
data.iter_mut()
184+
.zip(file_data.chunks_exact(4))
185+
.for_each(|(data, chunk)| {
186+
*data = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
187+
});
196188
}
197189

198190
let data = Arc::new(Mutex::new(data));
@@ -206,10 +198,18 @@ impl Data {
206198

207199
println!("saving data...");
208200

201+
file.seek(std::io::SeekFrom::Start(0)).await.unwrap();
202+
209203
let data = task_data.lock().await;
210-
for chunk in data.iter() {
211-
file.write_all(&chunk.to_le_bytes()).await.unwrap();
212-
}
204+
file.write_all(
205+
&data
206+
.iter()
207+
.map(|data| data.to_le_bytes())
208+
.flatten()
209+
.collect::<Vec<u8>>(),
210+
)
211+
.await
212+
.unwrap();
213213

214214
println!("saving data... done");
215215

0 commit comments

Comments
 (0)