use std::sync::LazyLock;
static BYTE_TO_UNICODE: LazyLock<[char; 256]> = LazyLock::new(|| {
let mut printable = [false; 256];
for b in 0x21u16..=0x7E {
printable[b as usize] = true; }
for b in 0xA1u16..=0xAC {
printable[b as usize] = true;
}
for b in 0xAEu16..=0xFF {
printable[b as usize] = true;
}
let mut table = ['\u{0}'; 256];
let mut next_extra: u32 = 0;
for b in 0..256usize {
table[b] = if printable[b] {
char::from_u32(b as u32).expect("byte value is always a valid scalar value")
} else {
let c = char::from_u32(256 + next_extra)
.expect("256..(256+256) is well within the Basic Multilingual Plane");
next_extra += 1;
c
};
}
table
});
static UNICODE_TO_BYTE: LazyLock<std::collections::HashMap<char, u8>> = LazyLock::new(|| {
BYTE_TO_UNICODE
.iter()
.enumerate()
.map(|(b, &c)| (c, b as u8))
.collect()
});
pub fn byte_to_unicode(b: u8) -> char {
BYTE_TO_UNICODE[b as usize]
}
pub fn unicode_to_byte(c: char) -> Option<u8> {
UNICODE_TO_BYTE.get(&c).copied()
}
pub fn decode_mapped_token(s: &str) -> Option<Vec<u8>> {
s.chars().map(unicode_to_byte).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn byte_to_unicode_round_trips_every_byte() {
for b in 0u16..=255 {
let b = b as u8;
let c = byte_to_unicode(b);
assert_eq!(
unicode_to_byte(c),
Some(b),
"byte {b:#04x} did not round-trip through char {c:?}"
);
}
}
#[test]
fn mapped_characters_are_pairwise_distinct() {
let mut seen = std::collections::HashSet::new();
for b in 0u16..=255 {
let c = byte_to_unicode(b as u8);
assert!(seen.insert(c), "char {c:?} produced by two different bytes");
}
assert_eq!(seen.len(), 256);
}
#[test]
fn printable_ascii_maps_to_itself() {
assert_eq!(byte_to_unicode(b'A'), 'A');
assert_eq!(byte_to_unicode(b'!'), '!');
assert_eq!(byte_to_unicode(b'~'), '~');
}
#[test]
fn space_maps_to_the_conventional_gpt2_placeholder() {
assert_eq!(byte_to_unicode(b' '), 'Ġ');
}
#[test]
fn decode_mapped_token_round_trips() {
let bytes: Vec<u8> = b" hello\n".to_vec();
let mapped: String = bytes.iter().map(|&b| byte_to_unicode(b)).collect();
assert_eq!(decode_mapped_token(&mapped), Some(bytes));
}
#[test]
fn decode_mapped_token_rejects_foreign_characters() {
assert_eq!(decode_mapped_token("not-byte-level-\u{1F600}"), None);
}
}