use alloc::{borrow::Cow, string::String};
use core::fmt;
use crate::text;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Id<'a> {
Number(i64),
String(Cow<'a, str>),
RawNumber(Cow<'a, str>),
Null,
}
impl Id<'_> {
#[inline]
#[must_use]
pub const fn as_i64(&self) -> Option<i64> {
match self {
Id::Number(n) => Some(*n),
Id::String(_) | Id::RawNumber(_) | Id::Null => None,
}
}
#[inline]
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Id::String(s) => Some(s),
Id::Number(_) | Id::RawNumber(_) | Id::Null => None,
}
}
#[must_use]
pub fn raw_number(text: &str) -> Option<Id<'_>> {
let number = jsonx_lib::Number::from_text(text)?;
Some(match number.as_i64() {
Some(n) => Id::Number(n),
None => Id::RawNumber(Cow::Borrowed(text)),
})
}
#[inline]
#[must_use]
pub const fn is_null(&self) -> bool {
matches!(self, Id::Null)
}
#[must_use]
pub fn into_owned(self) -> Id<'static> {
match self {
Id::Number(n) => Id::Number(n),
Id::String(s) => Id::String(Cow::Owned(s.into_owned())),
Id::RawNumber(s) => Id::RawNumber(Cow::Owned(s.into_owned())),
Id::Null => Id::Null,
}
}
pub(crate) fn write(&self, out: &mut String) {
match self {
Id::Number(n) => text::push_i64(out, *n),
Id::String(s) => jsonx_lib::write_string(out, s),
Id::RawNumber(s) => out.push_str(s),
Id::Null => out.push_str("null"),
}
}
}
impl fmt::Display for Id<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out = String::new();
self.write(&mut out);
f.write_str(&out)
}
}
impl From<i64> for Id<'_> {
#[inline]
fn from(n: i64) -> Self {
Id::Number(n)
}
}
impl From<i32> for Id<'_> {
#[inline]
fn from(n: i32) -> Self {
Id::Number(i64::from(n))
}
}
impl From<u32> for Id<'_> {
#[inline]
fn from(n: u32) -> Self {
Id::Number(i64::from(n))
}
}
impl<'a> From<&'a str> for Id<'a> {
#[inline]
fn from(s: &'a str) -> Self {
Id::String(Cow::Borrowed(s))
}
}
impl From<String> for Id<'_> {
#[inline]
fn from(s: String) -> Self {
Id::String(Cow::Owned(s))
}
}
impl<'a> From<Cow<'a, str>> for Id<'a> {
#[inline]
fn from(s: Cow<'a, str>) -> Self {
Id::String(s)
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use alloc::string::ToString;
use super::*;
#[test]
fn test_display_writes_json() {
assert_eq!(Id::from(i64::MIN).to_string(), "-9223372036854775808");
assert_eq!(Id::from("a\"b").to_string(), r#""a\"b""#);
}
#[test]
fn test_lenient_ids_write_as_sent() {
assert_eq!(
Id::raw_number("-1.5e300")
.map(|id| id.to_string())
.as_deref(),
Some("-1.5e300")
);
assert_eq!(
Id::raw_number("18446744073709551616").map(|id| id.as_i64()),
Some(None)
);
assert_eq!(Id::raw_number("abc"), None);
assert_eq!(Id::raw_number(" 1"), None);
assert_eq!(Id::Null.as_str(), None);
assert_eq!(Id::Null.into_owned(), Id::Null);
}
#[test]
fn test_ids_order_numbers_before_strings() {
assert!(Id::from(5) < Id::from("0"));
assert!(Id::from(-1) < Id::from(0));
}
}