blob: 686f9ae963c80fcadc7ffd21c9d1f41b66386699 [file] [log] [blame]
Dennis Shen0d1c5622023-12-01 21:04:29 +00001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dennis Shenadc7b732023-12-11 18:59:13 +000017pub mod package_table;
18
19use anyhow::{anyhow, Result};
20use std::collections::{hash_map::DefaultHasher, HashMap, HashSet};
21use std::hash::{Hash, Hasher};
22use std::path::PathBuf;
Dennis Shen0d1c5622023-12-01 21:04:29 +000023
24use crate::commands::OutputFile;
25use crate::protos::{ProtoParsedFlag, ProtoParsedFlags};
Dennis Shenadc7b732023-12-11 18:59:13 +000026use crate::storage::package_table::PackageTable;
27
28pub const FILE_VERSION: u32 = 1;
29
30pub const HASH_PRIMES: [u32; 29] = [
31 7, 13, 29, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241,
32 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611,
33 402653189, 805306457, 1610612741,
34];
35
36/// Get the right hash table size given number of entries in the table. Use a
37/// load factor of 0.5 for performance.
38pub fn get_table_size(entries: u32) -> Result<u32> {
39 HASH_PRIMES
40 .iter()
41 .find(|&&num| num >= 2 * entries)
42 .copied()
43 .ok_or(anyhow!("Number of packages is too large"))
44}
45
46/// Get the corresponding bucket index given the key and number of buckets
47pub fn get_bucket_index<T: Hash>(val: &T, num_buckets: u32) -> u32 {
48 let mut s = DefaultHasher::new();
49 val.hash(&mut s);
50 (s.finish() % num_buckets as u64) as u32
51}
Dennis Shen0d1c5622023-12-01 21:04:29 +000052
53pub struct FlagPackage<'a> {
54 pub package_name: &'a str,
55 pub package_id: u32,
56 pub flag_names: HashSet<&'a str>,
57 pub boolean_flags: Vec<&'a ProtoParsedFlag>,
58 pub boolean_offset: u32,
59}
60
61impl<'a> FlagPackage<'a> {
62 fn new(package_name: &'a str, package_id: u32) -> Self {
63 FlagPackage {
64 package_name,
65 package_id,
66 flag_names: HashSet::new(),
67 boolean_flags: vec![],
68 boolean_offset: 0,
69 }
70 }
71
72 fn insert(&mut self, pf: &'a ProtoParsedFlag) {
73 if self.flag_names.insert(pf.name()) {
74 self.boolean_flags.push(pf);
75 }
76 }
77}
78
79pub fn group_flags_by_package<'a, I>(parsed_flags_vec_iter: I) -> Vec<FlagPackage<'a>>
80where
81 I: Iterator<Item = &'a ProtoParsedFlags>,
82{
83 // group flags by package
84 let mut packages: Vec<FlagPackage<'a>> = Vec::new();
Dennis Shenadc7b732023-12-11 18:59:13 +000085 let mut package_index: HashMap<&str, usize> = HashMap::new();
Dennis Shen0d1c5622023-12-01 21:04:29 +000086 for parsed_flags in parsed_flags_vec_iter {
87 for parsed_flag in parsed_flags.parsed_flag.iter() {
88 let index = *(package_index.entry(parsed_flag.package()).or_insert(packages.len()));
89 if index == packages.len() {
90 packages.push(FlagPackage::new(parsed_flag.package(), index as u32));
91 }
92 packages[index].insert(parsed_flag);
93 }
94 }
95
96 // calculate package flag value start offset, in flag value file, each boolean
97 // is stored as two bytes, the first byte will be the flag value. the second
98 // byte is flag info byte, which is a bitmask to indicate the status of a flag
99 let mut boolean_offset = 0;
100 for p in packages.iter_mut() {
101 p.boolean_offset = boolean_offset;
102 boolean_offset += 2 * p.boolean_flags.len() as u32;
103 }
104
105 packages
106}
107
108pub fn generate_storage_files<'a, I>(
Dennis Shenadc7b732023-12-11 18:59:13 +0000109 container: &str,
Dennis Shen0d1c5622023-12-01 21:04:29 +0000110 parsed_flags_vec_iter: I,
111) -> Result<Vec<OutputFile>>
112where
113 I: Iterator<Item = &'a ProtoParsedFlags>,
114{
Dennis Shenadc7b732023-12-11 18:59:13 +0000115 let packages = group_flags_by_package(parsed_flags_vec_iter);
116
117 // create and serialize package map
118 let package_table = PackageTable::new(container, &packages)?;
119 let package_table_file_path = PathBuf::from("package.map");
120 let package_table_file =
121 OutputFile { contents: package_table.as_bytes(), path: package_table_file_path };
122
123 Ok(vec![package_table_file])
Dennis Shen0d1c5622023-12-01 21:04:29 +0000124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129 use crate::Input;
130
Dennis Shenadc7b732023-12-11 18:59:13 +0000131 /// Read and parse bytes as u32
132 pub fn read_u32_from_bytes(buf: &[u8], head: &mut usize) -> Result<u32> {
133 let val = u32::from_le_bytes(buf[*head..*head + 4].try_into()?);
134 *head += 4;
135 Ok(val)
136 }
137
138 /// Read and parse bytes as string
139 pub fn read_str_from_bytes(buf: &[u8], head: &mut usize) -> Result<String> {
140 let num_bytes = read_u32_from_bytes(buf, head)? as usize;
141 let val = String::from_utf8(buf[*head..*head + num_bytes].to_vec())?;
142 *head += num_bytes;
143 Ok(val)
144 }
145
Dennis Shen0d1c5622023-12-01 21:04:29 +0000146 pub fn parse_all_test_flags() -> Vec<ProtoParsedFlags> {
147 let aconfig_files = [
148 (
149 "com.android.aconfig.storage.test_1",
150 "storage_test_1_part_1.aconfig",
151 include_bytes!("../../tests/storage_test_1_part_1.aconfig").as_slice(),
152 ),
153 (
154 "com.android.aconfig.storage.test_1",
155 "storage_test_1_part_2.aconfig",
156 include_bytes!("../../tests/storage_test_1_part_2.aconfig").as_slice(),
157 ),
158 (
159 "com.android.aconfig.storage.test_2",
160 "storage_test_2.aconfig",
161 include_bytes!("../../tests/storage_test_2.aconfig").as_slice(),
162 ),
Dennis Shen8bab8592023-12-20 17:45:00 +0000163 (
164 "com.android.aconfig.storage.test_4",
165 "storage_test_4.aconfig",
166 include_bytes!("../../tests/storage_test_4.aconfig").as_slice(),
167 ),
Dennis Shen0d1c5622023-12-01 21:04:29 +0000168 ];
169
170 aconfig_files
171 .into_iter()
172 .map(|(pkg, file, content)| {
173 let bytes = crate::commands::parse_flags(
174 pkg,
175 Some("system"),
176 vec![Input {
177 source: format!("tests/{}", file).to_string(),
178 reader: Box::new(content),
179 }],
180 vec![],
181 crate::commands::DEFAULT_FLAG_PERMISSION,
182 )
183 .unwrap();
184 crate::protos::parsed_flags::try_from_binary_proto(&bytes).unwrap()
185 })
186 .collect()
187 }
188
189 #[test]
190 fn test_flag_package() {
191 let caches = parse_all_test_flags();
192 let packages = group_flags_by_package(caches.iter());
193
194 for pkg in packages.iter() {
195 let pkg_name = pkg.package_name;
196 assert_eq!(pkg.flag_names.len(), pkg.boolean_flags.len());
197 for pf in pkg.boolean_flags.iter() {
198 assert!(pkg.flag_names.contains(pf.name()));
199 assert_eq!(pf.package(), pkg_name);
200 }
201 }
202
Dennis Shen8bab8592023-12-20 17:45:00 +0000203 assert_eq!(packages.len(), 3);
Dennis Shen0d1c5622023-12-01 21:04:29 +0000204
205 assert_eq!(packages[0].package_name, "com.android.aconfig.storage.test_1");
206 assert_eq!(packages[0].package_id, 0);
207 assert_eq!(packages[0].flag_names.len(), 5);
208 assert!(packages[0].flag_names.contains("enabled_rw"));
209 assert!(packages[0].flag_names.contains("disabled_rw"));
210 assert!(packages[0].flag_names.contains("enabled_ro"));
211 assert!(packages[0].flag_names.contains("disabled_ro"));
212 assert!(packages[0].flag_names.contains("enabled_fixed_ro"));
213 assert_eq!(packages[0].boolean_offset, 0);
214
215 assert_eq!(packages[1].package_name, "com.android.aconfig.storage.test_2");
216 assert_eq!(packages[1].package_id, 1);
217 assert_eq!(packages[1].flag_names.len(), 3);
218 assert!(packages[1].flag_names.contains("enabled_ro"));
219 assert!(packages[1].flag_names.contains("disabled_ro"));
220 assert!(packages[1].flag_names.contains("enabled_fixed_ro"));
221 assert_eq!(packages[1].boolean_offset, 10);
Dennis Shen8bab8592023-12-20 17:45:00 +0000222
223 assert_eq!(packages[2].package_name, "com.android.aconfig.storage.test_4");
224 assert_eq!(packages[2].package_id, 2);
225 assert_eq!(packages[2].flag_names.len(), 2);
226 assert!(packages[2].flag_names.contains("enabled_ro"));
227 assert!(packages[2].flag_names.contains("enabled_fixed_ro"));
228 assert_eq!(packages[2].boolean_offset, 16);
Dennis Shen0d1c5622023-12-01 21:04:29 +0000229 }
230}