Debian Codegraph @

examples/file_read_write_vec.rs

raw symbols SCIP
1 /// Getting RON with type derives and reading/writing a Vec<T> to/from a file.
2 use ron::{error::SpannedResult, ser::PrettyConfig, Error};
3 use serde::{de::DeserializeOwned, Deserialize, Serialize};
4 use std::{
5 fs::File,
6 io::{Read, Write},
7 path::PathBuf,
8 str::FromStr,
9 };
10
11 #[derive(Debug, Deserialize, Serialize)]
12 struct MetaData {
13 created_at: String,
14 author: String,
15 }
16
17 #[derive(Debug, Deserialize, Serialize)]
18 enum UserRole {
19 User,
20 Admin { key: usize },
21 }
22
23 #[derive(Debug, Deserialize, Serialize)]
24 struct User {
25 name: String,
26 email: String,
27 comment: String,
28 role: UserRole,
29 meta: MetaData,
30 }
31
32 fn create_records() -> Vec<User> {
33 vec![
34 User {
35 name: "Alice".into(),
36 email: "[email protected]".into(),
37 comment: "New\nLine, and \"quotes\"".into(),
38 role: UserRole::Admin { key: 0xDEADFEED },
39 meta: MetaData {
40 created_at: "2025-06-22".into(),
41 author: "Admin".to_string(),
42 },
43 },
44 User {
45 name: "Bob".into(),
46 email: "[email protected]".into(),
47 comment: "Tabs\ttoo".into(),
48 role: UserRole::User,
49 meta: MetaData {
50 created_at: "2025-06-22".into(),
51 author: "Admin".to_string(),
52 },
53 },
54 ]
55 }
56
57 /// Serializes a list of T into a string with one record per line
58 fn write_ron_vec_to_str<T: Serialize>(records: &[T]) -> Result<String, Error> {
59 let mut mut_str = String::new();
60
61 let as_strings = {
62 records
63 .into_iter()
64 .map(|record| {
65 ron::ser::to_string_pretty(
66 &record,
67 PrettyConfig::new()
68 .compact_arrays(true)
69 .compact_maps(true)
70 .compact_structs(true)
71 .escape_strings(true),
72 )
73 })
74 .collect::<Result<Vec<_>, _>>()?
75 };
76
77 as_strings.into_iter().for_each(|s| {
78 mut_str.push_str(&s);
79 mut_str.push_str(if cfg!(not(target_os = "windows")) {
80 "\n"
81 } else {
82 "\r\n"
83 })
84 });
85
86 Ok(mut_str)
87 }
88
89 /// Serializes a list of T into a text file with one record per line
90 fn write_ron_vec_to_file<T: Serialize>(path: &PathBuf, records: &[T]) -> Result<usize, Error> {
91 let mut file = File::create(path).map_err(|e| Error::Io(e.to_string()))?;
92
93 file.write(write_ron_vec_to_str(records)?.as_bytes())
94 .map_err(|err| Error::Io(err.to_string()))
95 }
96
97 /// This reader assumes that every row has one entry, so it would not work if they are split across lines.
98 fn read_ron_vec_from_str<T: DeserializeOwned>(s: &str) -> SpannedResult<Vec<T>> {
99 s //_
100 .lines()
101 .map(|s| ron::from_str::<T>(s))
102 .collect::<Result<Vec<_>, _>>()
103 }
104
105 fn read_ron_vec_from_file<T: DeserializeOwned>(path: &PathBuf) -> Result<Vec<T>, Error> {
106 let mut file = File::open(path).map_err(|e| Error::Io(e.to_string()))?;
107
108 let mut content = String::new();
109
110 file.read_to_string(&mut content)
111 .map_err(|e| Error::Io(e.to_string()))?;
112
113 read_ron_vec_from_str(&content).map_err(|e| e.code)
114 }
115
116 pub fn main() {
117 let users = create_records();
118
119 let path = PathBuf::from_str("vec-example.ron").unwrap();
120
121 write_ron_vec_to_file(&path, &users).unwrap();
122
123 let read_users: Vec<User> = read_ron_vec_from_file(&path).unwrap();
124
125 // Comment this out if you want to view the file:
126 std::fs::remove_file("vec-example.ron").unwrap();
127
128 println!("{:?}", read_users);
129 }