capsule_core/sidecar/label.rs
1//! User labels (SSoT: [Organization — Labels]).
2//!
3//! A label is a Unicode string, NFC-normalized and trimmed, 1–256 bytes, case-preserving. It
4//! carries no hierarchy and no type. The same rule holds at every level a label attaches to —
5//! asset (`tags_user`), image region, stack and album — so one normalizer owns it.
6//!
7//! [Organization — Labels]: https://docs/design/organization/#labels
8
9use thiserror::Error;
10use unicode_normalization::UnicodeNormalization;
11
12/// The largest label, in UTF-8 bytes after normalization.
13pub const MAX_LABEL_BYTES: usize = 256;
14
15/// Why a label was refused.
16#[derive(Debug, Clone, PartialEq, Eq, Error)]
17pub enum LabelError {
18 /// Nothing is left once the label is trimmed.
19 #[error("label is empty")]
20 Empty,
21 /// The normalized label is longer than [`MAX_LABEL_BYTES`].
22 #[error("label is {0} bytes; the limit is {MAX_LABEL_BYTES}")]
23 TooLong(usize),
24}
25
26/// Normalize `raw` into a storable label: NFC, then trimmed of surrounding whitespace, then
27/// checked against the 1–[`MAX_LABEL_BYTES`] byte bound. Case is preserved.
28///
29/// # Errors
30///
31/// [`LabelError::Empty`] when only whitespace remains, [`LabelError::TooLong`] past the bound.
32pub fn normalize_label(raw: &str) -> Result<String, LabelError> {
33 let nfc: String = raw.nfc().collect();
34 let trimmed = nfc.trim();
35 if trimmed.is_empty() {
36 return Err(LabelError::Empty);
37 }
38 if trimmed.len() > MAX_LABEL_BYTES {
39 return Err(LabelError::TooLong(trimmed.len()));
40 }
41 Ok(trimmed.to_string())
42}
43
44#[cfg(test)]
45mod tests;