Repository navigation
Expand file tree
/
Copy pathtextfiles.rs
More file actions
214 lines (179 loc) · 7.16 KB
/
Copy pathtextfiles.rs
File metadata and controls
214 lines (179 loc) · 7.16 KB
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
/*
Made by: Mathew Dusome
Sept 10 2026
In your utils.rs file add the following to the end of the file
pub mod textfiles;
Add with the other use statements
use crate::utils::textfiles::TextFile;
Simple examples:
1. Save different data to separate files:
// Save string data (player names)
let names = vec!["Alice", "Bob", "Charlie"];
let result = TextFile::save_strings("player_names.txt", names).await;
if let Err(e) = result {
println!("Error saving names: {}", e);
}
// Save integer data (scores)
let scores = vec![100, 85, 92];
let result = TextFile::save_numbers("high_scores.txt", scores).await;
if let Err(e) = result {
println!("Error saving scores: {}", e);
}
2. Load different data from separate files:
// Load player names
let result = TextFile::load_strings("player_names.txt").await;
Without error checking:
let names: Vec<String> = result.unwrap_or_default();
With error checking:
if let Ok(names) = result {
for name in names {
println!("Player: {}", name);
}
} else if let Err(e) = result {
println!("Error loading names: {}", e);
}
// Load high scores
let result = TextFile::load_numbers::<i32>("high_scores.txt").await;
if let Ok(scores) = result {
for score in scores {
println!("Score: {}", score);
}
} else if let Err(e) = result {
println!("Error loading scores: {}", e);
}
3. Load game configuration from an asset file:
let result = TextFile::load_asset("assets/config.txt").await;
if let Ok(content) = result {
for line in content.lines() {
println!("Config: {}", line);
}
} else if let Err(e) = result {
println!("Error loading config: {}", e);
}
Platform notes:
- On desktop: Saves files with the exact filename you provide (include .txt extension)
- On web: Uses browser's localStorage
- Asset loading works on both platforms, but web requires files in the assets directory
*/
use macroquad::prelude::*;
// Only use extern "C" for localStorage in WASM
#[cfg(target_arch = "wasm32")]
extern "C" {
// Save a string to localStorage: js_local_storage_set(key_ptr, key_len, value_ptr, value_len)
fn js_local_storage_set(key_ptr: *const u8, key_len: usize, value_ptr: *const u8, value_len: usize);
// Get a string from localStorage: returns length, fills buffer with value if found
// Returns length of value, or 0 if not found
fn js_local_storage_get(key_ptr: *const u8, key_len: usize, out_ptr: *mut u8, out_len: usize) -> usize;
}
/// TextFile is a utility module for reading and writing text files
/// that works across all platforms, including web.
pub struct TextFile;
impl TextFile {
/// Saves a vector of strings to a file or local storage (for web)
pub async fn save(name: &str, data: Vec<String>) -> Result<(), String> {
let joined = data.join("\n");
#[cfg(target_arch = "wasm32")]
{
// Call JS FFI to save to localStorage
let key_bytes = name.as_bytes();
let value_bytes = joined.as_bytes();
unsafe {
js_local_storage_set(
key_bytes.as_ptr(), key_bytes.len(),
value_bytes.as_ptr(), value_bytes.len()
);
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
{
// Use the exact filename provided (no auto extension)
let filename = name;
std::fs::write(&filename, joined)
.map_err(|e| format!("Failed to write to file {}: {}", filename, e))
}
}
/// Loads a vector of strings from a file or local storage (for web)
pub async fn load(name: &str) -> Result<Vec<String>, String> {
#[cfg(target_arch = "wasm32")]
{
// Call JS FFI to load from localStorage
let key_bytes = name.as_bytes();
// Allocate a buffer for the value (max 16KB)
let mut buf = vec![0u8; 16 * 1024];
let len = unsafe {
js_local_storage_get(
key_bytes.as_ptr(), key_bytes.len(),
buf.as_mut_ptr(), buf.len()
)
};
if len == 0 {
return Ok(Vec::new());
}
let content = String::from_utf8_lossy(&buf[..len]).to_string();
Ok(content.lines().map(|s| s.to_string()).collect::<Vec<String>>())
}
#[cfg(not(target_arch = "wasm32"))]
{
// Use the exact filename provided (no auto extension)
let filename = name;
match std::fs::read_to_string(&filename) {
Ok(content) => Ok(content.lines().map(|s| s.to_string()).collect()),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(Vec::new()) // Return empty vector if file doesn't exist yet
} else {
Err(format!("Failed to read file {}: {}", filename, e))
}
}
}
}
}
/// Saves a vector of strings to a file or local storage (for web)
/// Convenience method that takes Vec<&str> directly
pub async fn save_strings<T: AsRef<str>>(name: &str, data: Vec<T>) -> Result<(), String> {
let string_data: Vec<String> = data.into_iter()
.map(|s| s.as_ref().to_string())
.collect();
Self::save(name, string_data).await
}
/// Saves a vector of numbers to a file or local storage (for web)
/// Handles any type that can be converted to a string
#[allow(dead_code)]
pub async fn save_numbers<T: ToString>(name: &str, data: Vec<T>) -> Result<(), String> {
let string_data: Vec<String> = data.into_iter()
.map(|n| n.to_string())
.collect();
Self::save(name, string_data).await
}
/// Loads a vector of strings from a file or local storage (for web)
/// Alias for load() for consistent naming with save_strings()
pub async fn load_strings(name: &str) -> Result<Vec<String>, String> {
Self::load(name).await
}
/// Loads a vector of numbers from a file or local storage (for web)
/// Handles any type that can be parsed from a string
#[allow(dead_code)]
pub async fn load_numbers<T>(name: &str) -> Result<Vec<T>, String>
where
T: std::str::FromStr,
{
let strings = Self::load(name).await?;
let mut numbers = Vec::with_capacity(strings.len());
for s in strings {
match s.parse::<T>() {
Ok(n) => numbers.push(n),
Err(_) => return Err(format!("Failed to parse '{}' as number", s))
}
}
Ok(numbers)
}
/// Loads an asset file (read-only data)
#[allow(dead_code)]
pub async fn load_asset(path: &str) -> Result<String, String> {
match load_string(path).await {
Ok(content) => Ok(content),
Err(e) => Err(format!("Failed to load asset '{}': {:?}", path, e))
}
}
}