use std::fmt;
#[derive(Clone)]
enum Bytes {
Shared(std::rc::Rc<[u8]>),
Owned(std::rc::Rc<Vec<u8>>),
}
impl Bytes {
#[inline(always)]
fn as_slice(&self) -> &[u8] {
match self {
Bytes::Shared(bytes) => bytes,
Bytes::Owned(bytes) => bytes,
}
}
fn allocated(&self) -> usize {
match self {
Bytes::Shared(bytes) => bytes.len(),
Bytes::Owned(bytes) => bytes.capacity(),
}
}
}
impl std::ops::Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.as_slice()
}
}
#[derive(Clone)]
pub struct Wtf8 {
bytes: Bytes,
valid: bool,
}
impl Wtf8 {
pub fn new(text: impl Into<String>) -> Wtf8 {
Wtf8 {
bytes: Bytes::Owned(std::rc::Rc::new(text.into().into_bytes())),
valid: true,
}
}
pub fn from_rc_str(text: &str) -> Wtf8 {
Wtf8 {
bytes: Bytes::Shared(std::rc::Rc::from(text.as_bytes())),
valid: true,
}
}
pub fn from_parts(bytes: Vec<u8>, valid: bool) -> Wtf8 {
Wtf8 {
bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
valid,
}
}
pub fn allocated_bytes(&self) -> usize {
self.bytes.allocated()
}
pub fn is_valid(&self) -> bool {
self.valid
}
pub fn from_code_points(points: &[u32]) -> Wtf8 {
let mut units = Vec::with_capacity(points.len());
for &point in points {
if point > 0xFFFF {
let value = point - 0x10000;
units.push(0xD800 + (value >> 10) as u16);
units.push(0xDC00 + (value & 0x3FF) as u16);
} else {
units.push(point as u16);
}
}
Wtf8::from_units(&units)
}
pub fn from_wtf8_bytes(bytes: &[u8]) -> Option<Wtf8> {
let mut units: Vec<u16> = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
let first = bytes[at];
let (length, payload_mask, min) = match first {
0x00..=0x7f => (1, 0x7f, 0),
0xc2..=0xdf => (2, 0x1f, 0x80),
0xe0..=0xef => (3, 0x0f, 0x800),
0xf0..=0xf4 => (4, 0x07, 0x10000),
_ => return None,
};
let end = at.checked_add(length)?;
if end > bytes.len() {
return None;
}
let mut code = u32::from(first) & payload_mask;
for &byte in &bytes[at + 1..end] {
if byte & 0xc0 != 0x80 {
return None;
}
code = (code << 6) | u32::from(byte & 0x3f);
}
if code < min {
return None;
}
if code > 0xffff {
let value = code - 0x10000;
units.push(0xd800 + (value >> 10) as u16);
units.push(0xdc00 + (value & 0x3ff) as u16);
} else {
units.push(code as u16);
}
at = end;
}
Some(Wtf8::from_units(&units))
}
pub fn from_units(units: &[u16]) -> Wtf8 {
let mut bytes = Vec::with_capacity(units.len());
let mut valid = true;
let mut index = 0;
while index < units.len() {
let unit = units[index];
match units.get(index + 1) {
Some(&low) if is_high(unit) && is_low(low) => {
push_code_point(&mut bytes, combine(unit, low));
index += 2;
}
_ if is_surrogate(unit) => {
valid = false;
push_surrogate(&mut bytes, unit);
index += 1;
}
_ => {
push_code_point(&mut bytes, unit as u32);
index += 1;
}
}
}
Wtf8 {
bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
valid,
}
}
pub fn as_str(&self) -> Option<&str> {
if self.valid {
Some(unsafe { std::str::from_utf8_unchecked(self.bytes.as_slice()) })
} else {
None
}
}
pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
match self.as_str() {
Some(text) => std::borrow::Cow::Borrowed(text),
None => String::from_utf8_lossy(self.bytes.as_slice()),
}
}
pub fn as_bytes(&self) -> &[u8] {
self.bytes.as_slice()
}
pub fn to_units(&self) -> Vec<u16> {
let mut units = Vec::with_capacity(self.utf16_len());
self.push_units(&mut units);
units
}
pub fn utf16_len(&self) -> usize {
self.bytes
.iter()
.filter(|byte| (**byte & 0xC0) != 0x80)
.map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
.sum()
}
pub fn code_unit_at(&self, index: usize) -> Option<u16> {
let mut position = 0;
let mut at = 0;
while at < self.bytes.len() {
let (units, count, width) = self.sequence_at(at);
if position + count > index {
return Some(units[index - position]);
}
position += count;
at += width;
}
None
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
self.code_unit_at(index)
.map(|unit| Wtf8::from_units(&[unit]))
}
pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
let units = self.to_units();
let start = start.min(units.len());
let end = end.clamp(start, units.len());
Wtf8::from_units(&units[start..end])
}
pub fn code_points(&self) -> Vec<Wtf8> {
let mut out = Vec::new();
let mut at = 0;
while at < self.bytes.as_slice().len() {
let (_, _, width) = self.sequence_at(at);
let mut bytes = Vec::with_capacity(width);
bytes.extend_from_slice(&self.bytes.as_slice()[at..at + width]);
let valid = std::str::from_utf8(&bytes).is_ok();
out.push(Wtf8 {
valid,
bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
});
at += width;
}
out
}
pub fn concat(&self, other: &Wtf8) -> Wtf8 {
let bridges = ends_with_high_surrogate(self.bytes.as_slice())
&& starts_with_low_surrogate(other.bytes.as_slice());
if !bridges {
let mut bytes =
Vec::with_capacity(self.bytes.as_slice().len() + other.bytes.as_slice().len());
bytes.extend_from_slice(self.bytes.as_slice());
bytes.extend_from_slice(other.bytes.as_slice());
return Wtf8 {
bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
valid: self.valid && other.valid,
};
}
let mut units = self.to_units();
units.extend(other.to_units());
Wtf8::from_units(&units)
}
pub fn append_in_place(&mut self, other: &Wtf8) -> Option<usize> {
let Bytes::Owned(owned) = &mut self.bytes else {
return None;
};
if ends_with_high_surrogate(owned.as_slice())
&& starts_with_low_surrogate(other.bytes.as_slice())
{
return None;
}
let buffer = std::rc::Rc::get_mut(owned)?;
let before = buffer.capacity();
buffer.extend_from_slice(other.bytes.as_slice());
self.valid = self.valid && other.valid;
Some(buffer.capacity() - before)
}
fn push_units(&self, out: &mut Vec<u16>) {
let mut at = 0;
while at < self.bytes.len() {
let (units, count, width) = self.sequence_at(at);
out.extend_from_slice(&units[..count]);
at += width;
}
}
pub fn code_point_values(&self) -> Vec<u32> {
self.code_points()
.into_iter()
.map(|point| match point.as_str() {
Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
})
.collect()
}
fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
let byte = self.bytes.as_slice()[at];
let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
if byte < 0x80 {
([byte as u16, 0], 1, 1)
} else if byte >> 5 == 0b110 {
(
[
(((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
0,
],
1,
2,
)
} else if byte >> 4 == 0b1110 {
(
[
((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
as u16,
0,
],
1,
3,
)
} else {
let code = (byte as u32 & 0x07) << 18
| ((byte_at(1) & 0x3F) << 12)
| ((byte_at(2) & 0x3F) << 6)
| (byte_at(3) & 0x3F);
let code = code.wrapping_sub(0x10000);
(
[
0xD800u16.wrapping_add((code >> 10) as u16),
0xDC00u16.wrapping_add((code & 0x3FF) as u16),
],
2,
4,
)
}
}
}
fn is_surrogate(unit: u16) -> bool {
(0xD800..0xE000).contains(&unit)
}
fn is_high(unit: u16) -> bool {
(0xD800..0xDC00).contains(&unit)
}
fn is_low(unit: u16) -> bool {
(0xDC00..0xE000).contains(&unit)
}
fn combine(high: u16, low: u16) -> u32 {
0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
}
fn push_code_point(out: &mut Vec<u8>, code: u32) {
if code < 0x80 {
out.push(code as u8);
} else if code < 0x800 {
out.push(0xC0 | (code >> 6) as u8);
out.push(0x80 | (code & 0x3F) as u8);
} else if code < 0x10000 {
out.push(0xE0 | (code >> 12) as u8);
out.push(0x80 | ((code >> 6) & 0x3F) as u8);
out.push(0x80 | (code & 0x3F) as u8);
} else {
out.push(0xF0 | (code >> 18) as u8);
out.push(0x80 | ((code >> 12) & 0x3F) as u8);
out.push(0x80 | ((code >> 6) & 0x3F) as u8);
out.push(0x80 | (code & 0x3F) as u8);
}
}
fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
out.push(0xE0 | (unit >> 12) as u8);
out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
out.push(0x80 | (unit & 0x3F) as u8);
}
fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
let len = bytes.len();
len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
}
fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
}
impl PartialEq for Wtf8 {
fn eq(&self, other: &Self) -> bool {
self.bytes.as_slice() == other.bytes.as_slice()
}
}
impl Eq for Wtf8 {}
impl fmt::Debug for Wtf8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.to_string_lossy())
}
}
impl PartialEq<str> for Wtf8 {
fn eq(&self, other: &str) -> bool {
self.as_str() == Some(other)
}
}
impl PartialEq<&str> for Wtf8 {
fn eq(&self, other: &&str) -> bool {
self.as_str() == Some(*other)
}
}
impl Default for Wtf8 {
fn default() -> Wtf8 {
Wtf8::new("")
}
}
impl std::hash::Hash for Wtf8 {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.bytes.as_slice().hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wtf8_bytes_round_trip() {
for text in ["", "plain ascii", "\u{1F600} astral", "Привет"] {
let string = Wtf8::new(text);
let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("valid WTF-8");
assert_eq!(decoded, string);
}
}
#[test]
fn wtf8_bytes_keep_a_lone_surrogate() {
let string = Wtf8::from_units(&[0xD800]);
assert_eq!(string.to_units(), vec![0xD800]);
let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("WTF-8 accepts it");
assert_eq!(decoded, string);
assert!(!decoded.is_valid());
}
#[test]
fn wtf8_bytes_canonicalise_a_pair() {
let mut split = Vec::new();
split.extend_from_slice(&[0xED, 0xA0, 0xBD]); split.extend_from_slice(&[0xED, 0xB8, 0x80]); let decoded = Wtf8::from_wtf8_bytes(&split).expect("valid WTF-8");
assert_eq!(decoded.to_units(), vec![0xD83D, 0xDE00]);
assert_eq!(decoded, Wtf8::new("\u{1F600}"));
}
#[test]
fn invalid_utf8_is_refused() {
assert!(Wtf8::from_wtf8_bytes(&[0xC3]).is_none());
assert!(Wtf8::from_wtf8_bytes(&[0x80]).is_none());
assert!(Wtf8::from_wtf8_bytes(&[0xC1, 0x81]).is_none());
assert!(Wtf8::from_wtf8_bytes(&[0xF8, 0x80, 0x80, 0x80, 0x80]).is_none());
}
}