sync15/clients_engine/
ser.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use crate::error::Result;
6use payload_support::Fit;
7use serde::Serialize;
8
9/// Truncates `list` to fit within `payload_size_max_bytes` when serialized to
10/// JSON.
11pub fn shrink_to_fit<T: Serialize>(list: &mut Vec<T>, payload_size_max_bytes: usize) -> Result<()> {
12    match payload_support::try_fit_items(list, payload_size_max_bytes) {
13        Fit::All => {}
14        Fit::Some(count) => list.truncate(count.get()),
15        Fit::None => list.clear(),
16        Fit::Err(e) => Err(e)?,
17    };
18    Ok(())
19}
20
21#[cfg(test)]
22mod tests {
23    use super::super::record::CommandRecord;
24    use super::*;
25
26    #[test]
27    fn test_shrink_to_fit() {
28        let mut commands = vec![
29            CommandRecord {
30                name: "wipeEngine".into(),
31                args: vec![Some("bookmarks".into())],
32                flow_id: Some("flow".into()),
33            },
34            CommandRecord {
35                name: "resetEngine".into(),
36                args: vec![Some("history".into())],
37                flow_id: Some("flow".into()),
38            },
39            CommandRecord {
40                name: "logout".into(),
41                args: Vec::new(),
42                flow_id: None,
43            },
44        ];
45
46        // 4096 bytes is enough to fit all three commands.
47        shrink_to_fit(&mut commands, 4096).unwrap();
48        assert_eq!(commands.len(), 3);
49
50        // `logout` won't fit within 2168 bytes.
51        shrink_to_fit(&mut commands, 2168).unwrap();
52        assert_eq!(commands.len(), 2);
53
54        // `resetEngine` won't fit within 2084 bytes.
55        shrink_to_fit(&mut commands, 2084).unwrap();
56        assert_eq!(commands.len(), 1);
57
58        // `wipeEngine` won't fit at all.
59        shrink_to_fit(&mut commands, 1024).unwrap();
60        assert!(commands.is_empty());
61    }
62}