Debian Codegraph @

third_party/rust/payload-support/src/lib.rs

raw
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
5 use serde::Serialize;
6 use std::{
7 io::{self, Write},
8 num::NonZeroUsize,
9 };
10
11 /// A quantity of items that can fit into a payload, accounting for
12 /// serialization, encryption, and Base64-encoding overhead.
13 pub enum Fit {
14 /// All items can fit into the payload.
15 All,
16
17 /// Some, but not all, items can fit into the payload without
18 /// exceeding the maximum payload size.
19 Some(NonZeroUsize),
20
21 /// The maximum payload size is too small to hold any items.
22 None,
23
24 /// The serialized size of the items couldn't be determined because of
25 /// a serialization error.
26 Err(serde_json::Error),
27 }
28
29 impl Fit {
30 /// If `self` is [`Fit::Some`], returns the number of items that can fit
31 /// into the payload without exceeding its maximum size. Otherwise,
32 /// returns `None`.
33 #[inline]
34 pub fn as_some(&self) -> Option<NonZeroUsize> {
35 match self {
36 Fit::Some(count) => Some(*count),
37 _ => None,
38 }
39 }
40 }
41
42 /// A writer that counts the number of bytes it's asked to write, and discards
43 /// the data. Used to compute the serialized size of an item.
44 #[derive(Clone, Copy, Default)]
45 struct ByteCountWriter(usize);
46
47 impl ByteCountWriter {
48 #[inline]
49 pub fn count(self) -> usize {
50 self.0
51 }
52 }
53
54 impl Write for ByteCountWriter {
55 #[inline]
56 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
57 self.0 += buf.len();
58 Ok(buf.len())
59 }
60
61 #[inline]
62 fn flush(&mut self) -> io::Result<()> {
63 Ok(())
64 }
65 }
66
67 /// Returns the size of the given value, in bytes, when serialized to JSON.
68 pub fn compute_serialized_size<T: Serialize + ?Sized>(value: &T) -> serde_json::Result<usize> {
69 let mut w = ByteCountWriter::default();
70 serde_json::to_writer(&mut w, value)?;
71 Ok(w.count())
72 }
73
74 /// Calculates the maximum number of items that can fit within
75 /// `max_payload_size` when serialized to JSON.
76 pub fn try_fit_items<T: Serialize>(items: &[T], max_payload_size: usize) -> Fit {
77 let size = match compute_serialized_size(&items) {
78 Ok(size) => size,
79 Err(e) => return Fit::Err(e),
80 };
81 // See bug 535326 comment 8 for an explanation of the estimation
82 let max_serialized_size = match ((max_payload_size / 4) * 3).checked_sub(1500) {
83 Some(max_serialized_size) => max_serialized_size,
84 None => return Fit::None,
85 };
86 if size > max_serialized_size {
87 // Estimate a little more than the direct fraction to maximize packing
88 let mut cutoff = (items.len() * max_serialized_size - 1) / size + 1;
89 // Keep dropping off the last entry until the data fits.
90 while cutoff > 0 {
91 let size = match compute_serialized_size(&items[..cutoff]) {
92 Ok(size) => size,
93 Err(e) => return Fit::Err(e),
94 };
95 if size <= max_serialized_size {
96 break;
97 }
98 cutoff -= 1;
99 }
100 match NonZeroUsize::new(cutoff) {
101 Some(count) => Fit::Some(count),
102 None => Fit::None,
103 }
104 } else {
105 Fit::All
106 }
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use super::*;
112
113 use serde_derive::Serialize;
114
115 #[derive(Serialize)]
116 struct CommandRecord {
117 #[serde(rename = "command")]
118 name: &'static str,
119 #[serde(default)]
120 args: &'static [Option<&'static str>],
121 #[serde(default, rename = "flowID", skip_serializing_if = "Option::is_none")]
122 flow_id: Option<&'static str>,
123 }
124
125 const COMMANDS: &[CommandRecord] = &[
126 CommandRecord {
127 name: "wipeEngine",
128 args: &[Some("bookmarks")],
129 flow_id: Some("flow"),
130 },
131 CommandRecord {
132 name: "resetEngine",
133 args: &[Some("history")],
134 flow_id: Some("flow"),
135 },
136 CommandRecord {
137 name: "logout",
138 args: &[],
139 flow_id: None,
140 },
141 ];
142
143 #[test]
144 fn test_compute_serialized_size() {
145 assert_eq!(compute_serialized_size(&1).unwrap(), 1);
146 assert_eq!(compute_serialized_size(&"hi").unwrap(), 4);
147 assert_eq!(
148 compute_serialized_size(&["hi", "hello", "bye"]).unwrap(),
149 20
150 );
151
152 let sizes = COMMANDS
153 .iter()
154 .map(|c| compute_serialized_size(c).unwrap())
155 .collect::<Vec<_>>();
156 assert_eq!(sizes, &[61, 60, 30]);
157 }
158
159 #[test]
160 fn test_try_fit_items() {
161 // 4096 bytes is enough to fit all three commands.
162 assert!(matches!(try_fit_items(COMMANDS, 4096), Fit::All));
163
164 // `logout` won't fit within 2168 bytes.
165 assert_eq!(try_fit_items(COMMANDS, 2168).as_some().unwrap().get(), 2);
166
167 // `resetEngine` won't fit within 2084 bytes.
168 assert_eq!(try_fit_items(COMMANDS, 2084).as_some().unwrap().get(), 1);
169
170 // `wipeEngine` won't fit at all.
171 assert!(matches!(try_fit_items(COMMANDS, 1024), Fit::None));
172 }
173 }