1use crate::types::{Rom, RomFile, RomFileCategory};
2
3#[derive(Debug, Clone)]
5pub struct RomGroup {
6 pub name: String,
7 pub primary: Rom,
8 pub others: Vec<Rom>,
9}
10
11pub fn group_roms_by_name(items: &[Rom]) -> Vec<RomGroup> {
14 use std::collections::HashMap;
15 let mut by_name: HashMap<String, Vec<Rom>> = HashMap::new();
16 for rom in items {
17 by_name
18 .entry(rom.name.clone())
19 .or_default()
20 .push(rom.clone());
21 }
22 let mut groups = Vec::with_capacity(by_name.len());
23 for (name, mut roms) in by_name {
24 roms.sort_by(|a, b| {
25 let a_extra = a.fs_name.to_lowercase().contains("[update]")
26 || a.fs_name.to_lowercase().contains("[dlc]");
27 let b_extra = b.fs_name.to_lowercase().contains("[update]")
28 || b.fs_name.to_lowercase().contains("[dlc]");
29 match (a_extra, b_extra) {
30 (false, true) => std::cmp::Ordering::Less,
31 (true, false) => std::cmp::Ordering::Greater,
32 _ => std::cmp::Ordering::Equal,
33 }
34 });
35 let primary = roms.remove(0);
36 groups.push(RomGroup {
37 name,
38 primary,
39 others: roms,
40 });
41 }
42 groups.sort_by(|a, b| a.name.cmp(&b.name));
43 groups
44}
45
46pub fn format_size(bytes: u64) -> String {
48 const KB: u64 = 1024;
49 const MB: u64 = KB * 1024;
50 const GB: u64 = MB * 1024;
51 if bytes >= GB {
52 format!("{:.2} GB", bytes as f64 / GB as f64)
53 } else if bytes >= MB {
54 format!("{:.2} MB", bytes as f64 / MB as f64)
55 } else if bytes >= KB {
56 format!("{:.2} KB", bytes as f64 / KB as f64)
57 } else {
58 format!("{} B", bytes)
59 }
60}
61
62fn category_bucket_index(cat: Option<&RomFileCategory>) -> usize {
63 match cat {
64 Some(RomFileCategory::Game) => 0,
65 Some(RomFileCategory::Update) => 1,
66 Some(RomFileCategory::Dlc) => 2,
67 Some(RomFileCategory::Patch) => 3,
68 Some(RomFileCategory::Hack) => 4,
69 Some(RomFileCategory::Mod) => 5,
70 Some(RomFileCategory::Translation) => 6,
71 Some(RomFileCategory::Demo) => 7,
72 Some(RomFileCategory::Prototype) => 8,
73 Some(RomFileCategory::Cheat) => 9,
74 Some(RomFileCategory::Manual) => 10,
75 None => 11,
76 }
77}
78
79const CATEGORY_BUCKET_LABELS: [&str; 12] = [
80 "game",
81 "update",
82 "dlc",
83 "patch",
84 "hack",
85 "mod",
86 "translation",
87 "demo",
88 "prototype",
89 "cheat",
90 "manual",
91 "other",
92];
93
94pub fn size_breakdown_by_category(files: &[RomFile]) -> Vec<(&'static str, u64)> {
99 if files.is_empty() {
100 return Vec::new();
101 }
102 let mut sums = [0u64; 12];
103 for f in files {
104 let i = category_bucket_index(f.category.as_ref());
105 sums[i] = sums[i].saturating_add(f.file_size_bytes);
106 }
107 let mut out = Vec::new();
108 for (i, label) in CATEGORY_BUCKET_LABELS.iter().enumerate() {
109 if sums[i] > 0 {
110 out.push((*label, sums[i]));
111 }
112 }
113 out
114}
115
116pub fn format_size_with_breakdown(total: u64, files: &[RomFile]) -> String {
121 let breakdown = size_breakdown_by_category(files);
122 if breakdown.is_empty() {
123 return format_size(total);
124 }
125 if breakdown.len() == 1 && breakdown[0].0 == "game" {
126 return format_size(total);
127 }
128 let parts: Vec<String> = breakdown
129 .iter()
130 .map(|(label, bytes)| format!("{} {}", label, format_size(*bytes)))
131 .collect();
132 format!("{} ({})", format_size(total), parts.join(" + "))
133}
134
135pub fn sanitize_filename(name: &str) -> String {
137 name.chars()
138 .map(|c| {
139 if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' || c == ' ' {
140 c
141 } else {
142 '_'
143 }
144 })
145 .collect()
146}
147
148pub fn truncate(s: &str, max: usize) -> String {
150 let s = s.trim();
151 if s.chars().count() <= max {
152 s.to_string()
153 } else {
154 format!(
155 "{}…",
156 s.chars().take(max.saturating_sub(1)).collect::<String>()
157 )
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164 use crate::types::Rom;
165
166 fn rom(id: u64, name: &str, fs_name: &str) -> Rom {
167 Rom {
168 id,
169 platform_id: 1,
170 platform_slug: None,
171 platform_fs_slug: None,
172 platform_custom_name: Some("NES".to_string()),
173 platform_display_name: Some("NES".to_string()),
174 fs_name: fs_name.to_string(),
175 fs_name_no_tags: name.to_string(),
176 fs_name_no_ext: name.to_string(),
177 fs_extension: "zip".to_string(),
178 fs_path: format!("/roms/{}.zip", id),
179 fs_size_bytes: 1,
180 name: name.to_string(),
181 slug: None,
182 summary: None,
183 path_cover_small: None,
184 path_cover_large: None,
185 url_cover: None,
186 has_manual: false,
187 path_manual: None,
188 url_manual: None,
189 is_unidentified: false,
190 is_identified: true,
191 files: Vec::new(),
192 }
193 }
194
195 #[test]
196 fn group_roms_prefers_base_file_as_primary() {
197 let input = vec![
198 rom(1, "Game A", "Game A [Update].zip"),
199 rom(2, "Game A", "Game A [DLC].zip"),
200 rom(3, "Game A", "Game A.zip"),
201 rom(4, "Game B", "Game B.zip"),
202 ];
203
204 let groups = group_roms_by_name(&input);
205 assert_eq!(groups.len(), 2);
206
207 let game_a = groups.iter().find(|g| g.name == "Game A").expect("group");
208 assert_eq!(game_a.primary.fs_name, "Game A.zip");
209 assert_eq!(game_a.others.len(), 2);
210 }
211}