Skip to content

Commit 21ac731

Browse files
committed
fix: add custom serde serialization for workbook cells
Use a custom serde module to serialize/deserialize HashMap<CellAddress, Cell> as a flat Vec of {row, col, cell}.
1 parent 0791674 commit 21ac731

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

src/model/workbook.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub struct Workbook {
3333
pub name: String,
3434
pub columns: usize,
3535
pub rows: usize,
36+
#[serde(with = "cell_map")]
3637
pub cells: HashMap<CellAddress, Cell>,
3738
}
3839

@@ -191,3 +192,53 @@ impl Workbook {
191192
self.recalc();
192193
}
193194
}
195+
196+
mod cell_map {
197+
use super::{Cell, CellAddress};
198+
use serde::{Deserialize, Deserializer, Serialize, Serializer};
199+
use std::collections::HashMap;
200+
201+
#[derive(Serialize, Deserialize)]
202+
struct StoredCell {
203+
row: usize,
204+
col: usize,
205+
cell: Cell,
206+
}
207+
208+
pub fn serialize<S>(
209+
cells: &HashMap<CellAddress, Cell>,
210+
serializer: S,
211+
) -> Result<S::Ok, S::Error>
212+
where
213+
S: Serializer,
214+
{
215+
let stored: Vec<StoredCell> = cells
216+
.iter()
217+
.map(|(addr, cell)| StoredCell {
218+
row: addr.row,
219+
col: addr.col,
220+
cell: cell.clone(),
221+
})
222+
.collect();
223+
stored.serialize(serializer)
224+
}
225+
226+
pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<CellAddress, Cell>, D::Error>
227+
where
228+
D: Deserializer<'de>,
229+
{
230+
let stored = Vec::<StoredCell>::deserialize(deserializer)?;
231+
Ok(stored
232+
.into_iter()
233+
.map(|entry| {
234+
(
235+
CellAddress {
236+
row: entry.row,
237+
col: entry.col,
238+
},
239+
entry.cell,
240+
)
241+
})
242+
.collect())
243+
}
244+
}

0 commit comments

Comments
 (0)