Skip to main content

fakecloud_core/
embedded.rs

1//! Reference data vendored into a crate as gzip-compressed JSON.
2//!
3//! Large AWS datasets (the managed IAM policies, the Service Quotas defaults)
4//! are embedded with `include_bytes!` as `.json.gz` to keep the binary small,
5//! and decoded once on first use.
6
7use std::io::Read;
8
9use serde::de::DeserializeOwned;
10
11/// Gunzip and parse embedded JSON. The data ships with the binary, so a
12/// failure is a build defect: it panics with `what` in the message.
13pub fn decode_gz_json<T: DeserializeOwned>(bytes: &[u8], what: &str) -> T {
14    let mut json = String::new();
15    flate2::read::GzDecoder::new(bytes)
16        .read_to_string(&mut json)
17        .unwrap_or_else(|e| panic!("embedded {what} is not valid gzip: {e}"));
18    serde_json::from_str(&json).unwrap_or_else(|e| panic!("embedded {what} is not valid JSON: {e}"))
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use std::io::Write;
25
26    fn gz(data: &[u8]) -> Vec<u8> {
27        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
28        enc.write_all(data).unwrap();
29        enc.finish().unwrap()
30    }
31
32    #[test]
33    fn decodes_gzipped_json() {
34        let v: Vec<u32> = decode_gz_json(&gz(b"[1,2,3]"), "test data");
35        assert_eq!(v, [1, 2, 3]);
36    }
37
38    #[test]
39    #[should_panic(expected = "embedded test data is not valid gzip")]
40    fn rejects_non_gzip() {
41        let _: Vec<u32> = decode_gz_json(b"[1]", "test data");
42    }
43
44    #[test]
45    #[should_panic(expected = "embedded test data is not valid JSON")]
46    fn rejects_bad_json() {
47        let _: Vec<u32> = decode_gz_json(&gz(b"[1,"), "test data");
48    }
49}