| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
//! Data structs and markers for day periods rules. |
| 6 |
|
| 7 |
#[cfg(feature = "datagen")] |
| 8 |
use alloc::string::String; |
| 9 |
use icu_time::Hour; |
| 10 |
|
| 11 |
/// Day period rules mapping each hour of the day to an index. |
| 12 |
/// |
| 13 |
/// Lookup assumes that at hour 0, the active period is the *last* index. This is |
| 14 |
/// because night periods often spill over past midnight (e.g., from 21:00 |
| 15 |
/// to 06:00), meaning hour 0 is typically covered by the last index. |
| 16 |
#[derive(Debug, PartialEq, Clone, Copy)] |
| 17 |
pub struct DayPeriodRules { |
| 18 |
/// A 24-bit map (packed into 3 bytes) where bit `h` is set if a transition |
| 19 |
/// to the next index occurs at hour `h`. |
| 20 |
pub transitions: [u8; 3], |
| 21 |
} |
| 22 |
|
| 23 |
impl DayPeriodRules { |
| 24 |
/// Looks up the index for a given hour (0-23). |
| 25 |
pub fn name_offset(&self, hour: Hour) -> usize { |
| 26 |
// Combine transitions bytes into a u32 for easier bit manipulation. |
| 27 |
let transitions = u32::from_le_bytes([ |
| 28 |
self.transitions[0], |
| 29 |
self.transitions[1], |
| 30 |
self.transitions[2], |
| 31 |
0, |
| 32 |
]); |
| 33 |
|
| 34 |
// Shifting left by `31 - hour` moves bits `0..=hour` to the top of the `u32`, |
| 35 |
// shifting out all later transitions. `count_ones()` then counts exactly the |
| 36 |
// transitions that occurred up to, and including, `hour`. |
| 37 |
let num_transitions_up_to_hour = (transitions << (31 - hour.number())).count_ones(); |
| 38 |
|
| 39 |
// This is branch-free as it compiles to a conditional move. |
| 40 |
let periods_before = if num_transitions_up_to_hour == 0 { |
| 41 |
// If we're before the first transition, we're in the last period |
| 42 |
transitions.count_ones() - 1 |
| 43 |
} else { |
| 44 |
num_transitions_up_to_hour - 1 |
| 45 |
}; |
| 46 |
|
| 47 |
periods_before as usize |
| 48 |
} |
| 49 |
|
| 50 |
/// Decodes rules from a string |
| 51 |
pub fn decode_from_str(s: &str) -> Option<Self> { |
| 52 |
let bytes = <&[u8; 4]>::try_from(s.as_bytes()).ok()?; |
| 53 |
let raw = (bytes[0] as u32) << 17 |
| 54 |
| (bytes[1] as u32) << 10 |
| 55 |
| (bytes[2] as u32) << 3 |
| 56 |
| (bytes[3] as u32); |
| 57 |
|
| 58 |
let [b, c, d, _] = u32::to_le_bytes(raw); |
| 59 |
|
| 60 |
Some(Self { |
| 61 |
transitions: [b, c, d], |
| 62 |
}) |
| 63 |
} |
| 64 |
|
| 65 |
/// Encodes rules into a string |
| 66 |
#[cfg(feature = "datagen")] |
| 67 |
pub fn encode_to_string(&self) -> String { |
| 68 |
let [a, b, c] = self.transitions; |
| 69 |
let raw = u32::from_le_bytes([a, b, c, 0]); |
| 70 |
|
| 71 |
let bytes = [ |
| 72 |
(raw >> 17) as u8 & 0b0111_1111, |
| 73 |
(raw >> 10) as u8 & 0b0111_1111, |
| 74 |
(raw >> 3) as u8 & 0b0111_1111, |
| 75 |
raw as u8 & 0b0000_0111, |
| 76 |
]; |
| 77 |
|
| 78 |
#[allow(clippy::unwrap_used)] // all ascii |
| 79 |
String::from(str::from_utf8(&bytes).unwrap()) |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
#[cfg(feature = "datagen")] |
| 84 |
impl DayPeriodRules { |
| 85 |
/// Computes `DayPeriodRules` from a set of periods and names. |
| 86 |
/// |
| 87 |
/// Entries is a map from `(start_hour, end_hour)` to a name. This method returns a |
| 88 |
/// `DayPeriodName` and an iterator of names. The `name_offset` function of the |
| 89 |
/// `DayPeriodName` will return the index of the hour's name in the iterator. |
| 90 |
/// |
| 91 |
/// Returns `None` if entries is empty, and errors if there are overlaps or gaps in |
| 92 |
/// 24-hour coverage. |
| 93 |
pub fn from_periods( |
| 94 |
entries: alloc::collections::BTreeMap<(u8, u8), &str>, |
| 95 |
) -> Result<(Self, impl Iterator<Item = &str>), &'static str> { |
| 96 |
if entries.is_empty() { |
| 97 |
return Err("empty"); |
| 98 |
} |
| 99 |
|
| 100 |
let mut hour_periods = [None; 24]; |
| 101 |
for (id, (&(start, end), _)) in entries.iter().enumerate() { |
| 102 |
let mut h = start % 24; |
| 103 |
#[allow(clippy::indexing_slicing)] // h in 0..=24 |
| 104 |
loop { |
| 105 |
if hour_periods[h as usize].is_some() { |
| 106 |
return Err("overlapping period"); |
| 107 |
} |
| 108 |
hour_periods[h as usize] = Some(id); |
| 109 |
h = (h + 1) % 24; |
| 110 |
if h == end || (h == 0 && end == 24) { |
| 111 |
break; |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
for p in &hour_periods { |
| 117 |
if p.is_none() { |
| 118 |
return Err("gap between periods"); |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
// TODO: change this to use array_try_map |
| 123 |
// <https://github.com/rust-lang/rust/issues/79711> |
| 124 |
#[allow(clippy::unwrap_used)] // just checked |
| 125 |
let hour_periods = hour_periods.map(|p| p.unwrap()); |
| 126 |
|
| 127 |
let mut current_period = entries.len() - 1; |
| 128 |
let mut transitions_u32 = 0u32; |
| 129 |
|
| 130 |
for (h, &actual_period) in hour_periods.iter().enumerate() { |
| 131 |
let expected_period = current_period; |
| 132 |
|
| 133 |
if actual_period != expected_period { |
| 134 |
transitions_u32 |= 1 << h; |
| 135 |
let mut next = current_period + 1; |
| 136 |
current_period = loop { |
| 137 |
next %= 8; |
| 138 |
if next < entries.len() { |
| 139 |
break next; |
| 140 |
} |
| 141 |
next += 1; |
| 142 |
}; |
| 143 |
if actual_period != current_period { |
| 144 |
current_period = actual_period; |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
let bytes = transitions_u32.to_le_bytes(); |
| 150 |
let transitions = [bytes[0], bytes[1], bytes[2]]; |
| 151 |
|
| 152 |
Ok((DayPeriodRules { transitions }, entries.into_values())) |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
#[cfg(test)] |
| 157 |
mod tests { |
| 158 |
use super::*; |
| 159 |
|
| 160 |
#[track_caller] |
| 161 |
fn test_rules(periods: &[((u8, u8), &'static str)]) { |
| 162 |
let (rules, names) = |
| 163 |
DayPeriodRules::from_periods(periods.iter().cloned().collect()).unwrap(); |
| 164 |
|
| 165 |
let names = names.collect::<Vec<_>>(); |
| 166 |
|
| 167 |
assert_eq!( |
| 168 |
DayPeriodRules::decode_from_str(&rules.encode_to_string()), |
| 169 |
Some(rules) |
| 170 |
); |
| 171 |
|
| 172 |
for &((start, end), name) in periods { |
| 173 |
for hour in start..end { |
| 174 |
assert_eq!( |
| 175 |
names[rules.name_offset((hour % 24).try_into().unwrap())], |
| 176 |
name, |
| 177 |
"{hour}" |
| 178 |
); |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
#[test] |
| 184 |
fn test_roundtrip() { |
| 185 |
test_rules(&[((6, 12), "foo"), ((12, 18), "bar"), ((18, 6), "baz")]); |
| 186 |
|
| 187 |
test_rules(&[ |
| 188 |
((6, 12), "foo"), |
| 189 |
((12, 18), "bar"), |
| 190 |
((18, 21), "baz"), |
| 191 |
((21, 6), "qu"), |
| 192 |
]); |
| 193 |
|
| 194 |
test_rules(&[((12, 12), "foo")]); |
| 195 |
|
| 196 |
test_rules(&[ |
| 197 |
((0, 12), "foo"), |
| 198 |
((12, 18), "bar"), |
| 199 |
((18, 21), "baz"), |
| 200 |
((21, 24), "qux"), |
| 201 |
]); |
| 202 |
|
| 203 |
test_rules(&[ |
| 204 |
((0, 5), "foo"), |
| 205 |
((5, 8), "bar"), |
| 206 |
((8, 12), "batz"), |
| 207 |
((12, 13), "qux"), |
| 208 |
((13, 19), "quux"), |
| 209 |
((19, 24), "quuux"), |
| 210 |
]); |
| 211 |
|
| 212 |
test_rules(&[ |
| 213 |
((0, 5), "foo"), |
| 214 |
((5, 10), "bar"), |
| 215 |
((10, 12), "batz"), |
| 216 |
((12, 13), "qux"), |
| 217 |
((13, 19), "quux"), |
| 218 |
((19, 24), "quuux"), |
| 219 |
]); |
| 220 |
} |
| 221 |
|
| 222 |
#[test] |
| 223 |
fn test_empty() { |
| 224 |
assert!(DayPeriodRules::from_periods(Default::default()).is_err()); |
| 225 |
} |
| 226 |
|
| 227 |
#[test] |
| 228 |
fn test_overlap() { |
| 229 |
assert!( |
| 230 |
DayPeriodRules::from_periods( |
| 231 |
[ |
| 232 |
((0, 12), "foo"), |
| 233 |
((12, 19), "bar"), |
| 234 |
// Overlaps |
| 235 |
((18, 21), "baz"), |
| 236 |
((21, 24), "qux"), |
| 237 |
] |
| 238 |
.into_iter() |
| 239 |
.collect(), |
| 240 |
) |
| 241 |
.is_err() |
| 242 |
); |
| 243 |
} |
| 244 |
|
| 245 |
#[test] |
| 246 |
fn test_gap() { |
| 247 |
assert!(DayPeriodRules::from_periods([((0, 12), "foo"),].into_iter().collect()).is_err()); |
| 248 |
} |
| 249 |
} |