brinkhaustools/licence/
codec.rsuse std::io::Write;
use std::path::Path;
use serde_json::Value;
const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
pub fn base32_encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(5) * 8);
let mut buffer: u32 = 0;
let mut bits: u32 = 0;
for &byte in data {
buffer = (buffer << 8) | u32::from(byte);
bits += 8;
while bits >= 5 {
bits -= 5;
out.push(CROCKFORD[((buffer >> bits) & 0x1f) as usize] as char);
}
}
if bits > 0 {
out.push(CROCKFORD[((buffer << (5 - bits)) & 0x1f) as usize] as char);
}
out
}
pub fn base32_decode(text: &str) -> Result<Vec<u8>, String> {
let mut out = Vec::with_capacity(text.len() * 5 / 8);
let mut buffer: u32 = 0;
let mut bits: u32 = 0;
for ch in text.chars() {
if ch.is_whitespace() || ch == '-' {
continue;
}
let value = match ch.to_ascii_uppercase() {
'O' => 0,
'I' | 'L' => 1,
c => match CROCKFORD.iter().position(|&a| a as char == c) {
Some(p) => p as u32,
None => return Err(format!("invalid character {ch:?}")),
},
};
buffer = (buffer << 5) | value;
bits += 5;
if bits >= 8 {
bits -= 8;
out.push(((buffer >> bits) & 0xff) as u8);
}
buffer &= (1 << bits) - 1;
}
if bits >= 5 || buffer != 0 {
return Err("block length does not end on a byte boundary".to_string());
}
Ok(out)
}
pub fn wrap(prefix: &str, body: &str, width: usize) -> String {
let mut out = String::from(prefix);
let mut line_len = prefix.len();
for ch in body.chars() {
if line_len == width {
out.push('\n');
line_len = 0;
}
out.push(ch);
line_len += 1;
}
out
}
pub fn hex_encode(data: &[u8]) -> String {
use std::fmt::Write as _;
data.iter().fold(String::with_capacity(data.len() * 2), |mut out, b| {
let _ = write!(out, "{b:02x}");
out
})
}
pub fn hex_decode(text: &str) -> Option<Vec<u8>> {
let text = text.trim();
if text.len() % 2 == 1 {
return None;
}
(0..text.len())
.step_by(2)
.map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok())
.collect()
}
pub fn canonical_json(value: &Value) -> String {
let mut out = String::new();
write_canonical(value, &mut out);
out
}
fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
out.push('{');
for (i, key) in keys.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&Value::String((*key).clone()).to_string());
out.push(':');
write_canonical(&map[key.as_str()], out);
}
out.push('}');
}
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
scalar => out.push_str(&scalar.to_string()),
}
}
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
if !dir.as_os_str().is_empty() {
std::fs::create_dir_all(dir)?;
}
}
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "state".to_string());
let tmp = path.with_file_name(format!(".{file_name}.tmp"));
{
let mut file = std::fs::File::create(&tmp)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
}
file.write_all(data)?;
file.sync_all()?;
}
std::fs::rename(&tmp, path)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base32_roundtrip_all_lengths() {
let data: Vec<u8> = (0..=255u8).collect();
for len in 0..40 {
let encoded = base32_encode(&data[..len]);
assert_eq!(base32_decode(&encoded).unwrap(), &data[..len], "len {len}");
}
}
#[test]
fn base32_ignores_layout_and_maps_lookalikes() {
let encoded = base32_encode(b"licence");
let messy = format!(" {}\n-{}\t", &encoded[..4].to_lowercase(), &encoded[4..]);
assert_eq!(base32_decode(&messy).unwrap(), b"licence");
assert_eq!(base32_decode("O0").unwrap(), base32_decode("00").unwrap());
assert_eq!(base32_decode("L0").unwrap(), vec![0x08]);
assert_eq!(base32_decode("IO").unwrap(), vec![0x08]);
}
#[test]
fn base32_rejects_garbage_and_truncation() {
assert!(base32_decode("U0").is_err());
let encoded = base32_encode(b"abcde12");
assert!(base32_decode(&encoded[..encoded.len() - 1]).is_err());
}
#[test]
fn hex_roundtrip() {
assert_eq!(hex_encode(&[0, 15, 255]), "000fff");
assert_eq!(hex_decode("000FFF").unwrap(), vec![0, 15, 255]);
assert!(hex_decode("abc").is_none());
assert!(hex_decode("zz").is_none());
}
#[test]
fn canonical_json_sorts_nested_keys() {
let v: Value = serde_json::from_str(r#"{"b":1,"a":{"d":[{"z":1,"y":"ä"}],"c":null}}"#)
.unwrap();
assert_eq!(canonical_json(&v), r#"{"a":{"c":null,"d":[{"y":"ä","z":1}]},"b":1}"#);
}
#[test]
fn atomic_write_replaces_content() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub").join("state.json");
write_atomic(&path, b"one").unwrap();
write_atomic(&path, b"two").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"two");
}
}