-
Notifications
You must be signed in to change notification settings - Fork 0
/
score.rs
55 lines (49 loc) · 1.53 KB
/
score.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
use std::fs::File;
use std::io::{self, Read, Write};
fn write_into_file(content: &str, file_name: &str) -> io::Result<()> {
let mut f = File::create(file_name)?;
f.write_all(content.as_bytes())
}
fn read_from_file(file_name: &str) -> io::Result<String> {
let mut f = File::open(file_name)?;
let mut content = String::new();
f.read_to_string(&mut content)?;
Ok(content)
}
fn slice_to_string(slice: &[u32]) -> String {
slice
.iter()
.map(|highscore| highscore.to_string())
.collect::<Vec<String>>()
.join(" ")
}
fn line_to_slice(line: &str) -> Vec<u32> {
line.split(" ")
.filter_map(|nb| nb.parse::<u32>().ok())
.collect()
}
pub fn save_highscores_and_lines(highscores: &[u32], number_of_lines: &[u32]) -> bool {
let s_highscores = slice_to_string(highscores);
let s_number_of_lines = slice_to_string(number_of_lines);
write_into_file(
format!("{}\n{}\n", s_highscores.as_str(), s_number_of_lines).as_str(),
"scores.txt",
)
.is_ok()
}
pub fn load_highscores_and_lines() -> Option<(Vec<u32>, Vec<u32>)> {
if let Ok(content) = read_from_file("scores.txt") {
let mut lines = content
.splitn(2, "\n")
.map(|line| line_to_slice(line))
.collect::<Vec<_>>();
if lines.len() == 2 {
let (number_lines, highscores) = (lines.pop().unwrap(), lines.pop().unwrap());
Some((highscores, number_lines))
} else {
None
}
} else {
None
}
}