use std::borrow::Cow;
use std::fmt;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsString(Repr);
#[derive(Clone, PartialEq, Eq, Hash)]
enum Repr {
Text(String),
Units(Box<[u16]>),
}
impl JsString {
pub const fn new() -> JsString {
JsString(Repr::Text(String::new()))
}
pub fn from_utf16(units: &[u16]) -> JsString {
match String::from_utf16(units) {
Ok(text) => JsString(Repr::Text(text)),
Err(_) => JsString(Repr::Units(units.into())),
}
}
pub fn from_utf16_vec(units: Vec<u16>) -> JsString {
match String::from_utf16(&units) {
Ok(text) => JsString(Repr::Text(text)),
Err(_) => JsString(Repr::Units(units.into_boxed_slice())),
}
}
pub fn from_code_unit(unit: u16) -> JsString {
JsString::from_utf16(&[unit])
}
pub fn as_str(&self) -> Option<&str> {
match &self.0 {
Repr::Text(text) => Some(text),
Repr::Units(_) => None,
}
}
pub fn is_well_formed(&self) -> bool {
matches!(self.0, Repr::Text(_))
}
pub fn to_string_lossy(&self) -> Cow<'_, str> {
match &self.0 {
Repr::Text(text) => Cow::Borrowed(text),
Repr::Units(units) => Cow::Owned(String::from_utf16_lossy(units)),
}
}
pub fn into_string_lossy(self) -> String {
match self.0 {
Repr::Text(text) => text,
Repr::Units(units) => String::from_utf16_lossy(&units),
}
}
pub fn into_string(self) -> Result<String, JsString> {
match self.0 {
Repr::Text(text) => Ok(text),
units => Err(JsString(units)),
}
}
pub fn is_empty(&self) -> bool {
match &self.0 {
Repr::Text(text) => text.is_empty(),
Repr::Units(units) => units.is_empty(),
}
}
pub fn len_utf16(&self) -> usize {
match &self.0 {
Repr::Text(text) => text.chars().map(char::len_utf16).sum(),
Repr::Units(units) => units.len(),
}
}
pub fn code_units(&self) -> CodeUnits<'_> {
CodeUnits(match &self.0 {
Repr::Text(text) => CodeUnitsRepr::Text(text.encode_utf16()),
Repr::Units(units) => CodeUnitsRepr::Units(units.iter()),
})
}
pub fn to_utf16(&self) -> Cow<'_, [u16]> {
match &self.0 {
Repr::Text(text) => Cow::Owned(text.encode_utf16().collect()),
Repr::Units(units) => Cow::Borrowed(units),
}
}
pub fn concat(&self, other: &JsString) -> JsString {
let mut out = JsStringBuilder::new();
out.push_js(self);
out.push_js(other);
out.finish()
}
}
impl Default for JsString {
fn default() -> Self {
JsString::new()
}
}
#[derive(Clone)]
pub struct CodeUnits<'a>(CodeUnitsRepr<'a>);
#[derive(Clone)]
enum CodeUnitsRepr<'a> {
Text(std::str::EncodeUtf16<'a>),
Units(std::slice::Iter<'a, u16>),
}
impl Iterator for CodeUnits<'_> {
type Item = u16;
fn next(&mut self) -> Option<u16> {
match &mut self.0 {
CodeUnitsRepr::Text(units) => units.next(),
CodeUnitsRepr::Units(units) => units.next().copied(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match &self.0 {
CodeUnitsRepr::Text(units) => units.size_hint(),
CodeUnitsRepr::Units(units) => units.size_hint(),
}
}
}
impl From<&str> for JsString {
fn from(text: &str) -> Self {
JsString(Repr::Text(text.to_owned()))
}
}
impl From<String> for JsString {
fn from(text: String) -> Self {
JsString(Repr::Text(text))
}
}
impl From<&String> for JsString {
fn from(text: &String) -> Self {
JsString(Repr::Text(text.clone()))
}
}
impl From<Cow<'_, str>> for JsString {
fn from(text: Cow<'_, str>) -> Self {
JsString(Repr::Text(text.into_owned()))
}
}
impl From<char> for JsString {
fn from(c: char) -> Self {
JsString(Repr::Text(c.to_string()))
}
}
impl PartialEq<str> for JsString {
fn eq(&self, other: &str) -> bool {
self.as_str() == Some(other)
}
}
impl PartialEq<&str> for JsString {
fn eq(&self, other: &&str) -> bool {
self.as_str() == Some(*other)
}
}
impl PartialEq<String> for JsString {
fn eq(&self, other: &String) -> bool {
self.as_str() == Some(other.as_str())
}
}
impl PartialEq<JsString> for str {
fn eq(&self, other: &JsString) -> bool {
other == self
}
}
impl PartialEq<JsString> for &str {
fn eq(&self, other: &JsString) -> bool {
other == self
}
}
impl PartialEq<JsString> for String {
fn eq(&self, other: &JsString) -> bool {
other == self
}
}
impl fmt::Display for JsString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_string_lossy())
}
}
impl fmt::Debug for JsString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Repr::Text(text) => fmt::Debug::fmt(text.as_str(), f),
Repr::Units(units) => {
f.write_str("\"")?;
for c in char::decode_utf16(units.iter().copied()) {
match c {
Ok(c) => {
for e in c.escape_debug() {
fmt::Write::write_char(f, e)?;
}
}
Err(e) => write!(f, "\\u{{{:x}}}", e.unpaired_surrogate())?,
}
}
f.write_str("\"")
}
}
}
}
#[derive(Default)]
pub struct JsStringBuilder(Builder);
#[derive(Default)]
enum Builder {
#[default]
Empty,
Text(String),
Units(Vec<u16>),
}
impl JsStringBuilder {
pub fn new() -> Self {
Self::default()
}
fn units(&mut self) -> &mut Vec<u16> {
if !matches!(self.0, Builder::Units(_)) {
let units = match std::mem::take(&mut self.0) {
Builder::Text(text) => text.encode_utf16().collect(),
_ => Vec::new(),
};
self.0 = Builder::Units(units);
}
match &mut self.0 {
Builder::Units(units) => units,
_ => unreachable!("just set"),
}
}
pub fn push_str(&mut self, text: &str) {
match &mut self.0 {
Builder::Empty => self.0 = Builder::Text(text.to_owned()),
Builder::Text(out) => out.push_str(text),
Builder::Units(units) => units.extend(text.encode_utf16()),
}
}
pub fn push(&mut self, c: char) {
match &mut self.0 {
Builder::Empty => self.0 = Builder::Text(c.to_string()),
Builder::Text(out) => out.push(c),
Builder::Units(units) => units.extend(c.encode_utf16(&mut [0; 2]).iter()),
}
}
pub fn push_js(&mut self, s: &JsString) {
match &s.0 {
Repr::Text(text) => self.push_str(text),
Repr::Units(more) => self.units().extend_from_slice(more),
}
}
pub fn push_units(&mut self, more: &[u16]) {
match String::from_utf16(more) {
Ok(text) if !matches!(self.0, Builder::Units(_)) => self.push_str(&text),
_ => self.units().extend_from_slice(more),
}
}
pub fn is_empty(&self) -> bool {
match &self.0 {
Builder::Empty => true,
Builder::Text(text) => text.is_empty(),
Builder::Units(units) => units.is_empty(),
}
}
pub fn finish(self) -> JsString {
match self.0 {
Builder::Empty => JsString::new(),
Builder::Text(text) => JsString(Repr::Text(text)),
Builder::Units(units) => JsString::from_utf16_vec(units),
}
}
pub fn finish_lossy(self) -> String {
match self.0 {
Builder::Empty => String::new(),
Builder::Text(text) => text,
Builder::Units(units) => String::from_utf16_lossy(&units),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const LEAD: u16 = 0xD83D;
const TRAIL: u16 = 0xDE00;
#[test]
fn well_formed_text_is_text() {
let s = JsString::from("a😀");
assert_eq!(s.as_str(), Some("a😀"));
assert!(s.is_well_formed());
assert_eq!(s.len_utf16(), 3);
assert_eq!(s.code_units().collect::<Vec<_>>(), [0x61, LEAD, TRAIL]);
assert_eq!(JsString::from_utf16(&[0x61, LEAD, TRAIL]), s);
assert_eq!(s, "a😀");
assert!(JsString::new().is_empty() && JsString::default().is_empty());
}
#[test]
fn a_lone_surrogate_is_kept() {
let lead = JsString::from_code_unit(LEAD);
let trail = JsString::from_code_unit(TRAIL);
assert_ne!(lead, trail);
assert_ne!(lead, JsString::from("\u{FFFD}"));
assert_ne!(lead, "\u{FFFD}");
assert_eq!(lead.len_utf16(), 1);
assert_eq!(lead.as_str(), None);
assert!(!lead.is_well_formed() && !lead.is_empty());
assert_eq!(lead.to_string_lossy(), "\u{FFFD}");
assert_eq!(lead.to_string(), "\u{FFFD}");
assert_eq!(format!("{lead:?}"), "\"\\u{d83d}\"");
assert_eq!(lead.clone().into_string(), Err(lead.clone()));
assert_eq!(lead.to_utf16().as_ref(), [LEAD]);
}
#[test]
fn halves_that_meet_are_the_character() {
let lead = JsString::from_code_unit(LEAD);
let trail = JsString::from_code_unit(TRAIL);
assert_eq!(lead.concat(&trail), JsString::from("😀"));
assert_eq!(lead.concat(&trail).as_str(), Some("😀"));
assert_eq!(trail.concat(&lead).to_string_lossy(), "\u{FFFD}\u{FFFD}");
let mut b = JsStringBuilder::new();
b.push_str("x");
b.push_js(&lead);
b.push_units(&[TRAIL, 0x79]);
assert_eq!(b.finish(), JsString::from("x😀y"));
let mut b = JsStringBuilder::new();
b.push_js(&lead);
b.push('z');
assert_eq!(b.finish_lossy(), "\u{FFFD}z");
}
}