#[cfg(feature = "async-graphql")]
use core::num::IntErrorKind;
use core::{convert::Infallible, fmt::Display};
use super::carrier::{Builtin, BytesWire, ScalarWire};
#[cfg(all(test, feature = "async-graphql"))]
use super::roster::Row;
#[cfg(all(test, feature = "async-graphql"))]
mod tests;
struct Digits {
buffer: [u8; Self::WIDTH],
at: usize,
}
impl Digits {
const WIDTH: usize = 40;
fn unsigned(mut value: u128) -> Self {
let mut buffer = [0u8; Self::WIDTH];
let mut at = Self::WIDTH;
loop {
at -= 1;
buffer[at] = b'0' + (value % 10) as u8;
value /= 10;
if value == 0 {
break;
}
}
Self { buffer, at }
}
fn signed(value: i128) -> Self {
let mut digits = Self::unsigned(value.unsigned_abs());
if value.is_negative() {
digits.at -= 1;
digits.buffer[digits.at] = b'-';
}
digits
}
fn as_str(&self) -> &str {
core::str::from_utf8(&self.buffer[self.at..]).expect("digits and a sign are ASCII")
}
}
#[cfg(feature = "async-graphql")]
fn text(value: &async_graphql::Value) -> Option<&str> {
match value {
async_graphql::Value::String(text) => Some(text.as_str()),
_ => None,
}
}
#[cfg(feature = "async-graphql")]
fn refuse(scalar: &str, text: &str, kind: &IntErrorKind, range: &str, ceiling: &str) -> String {
match kind {
IntErrorKind::Empty => format!(
"a `{scalar}` written as a string is decimal text and this one is empty — write the digits, \
as in \"{ceiling}\""
),
IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => {
format!("`{text}` is outside `{scalar}`'s range ({range})")
}
_ => format!(
"`{text}` is not a `{scalar}` — a string operand is DECIMAL TEXT ({range}), and a JSON number \
is read too wherever it is whole and in range"
),
}
}
#[cfg(feature = "async-graphql")]
fn refuse_number(scalar: &str, number: &async_graphql::Number, range: &str) -> String {
format!(
"`{number}` is not a `{scalar}` — a JSON number crosses as a WHOLE value inside the scalar's \
range ({range}), and a value past {SAFE} is written as DECIMAL TEXT instead, which is exact in \
both directions where a double is not"
)
}
#[cfg(feature = "async-graphql")]
pub(crate) const SAFE: u128 = (1 << 53) - 1;
#[cfg(feature = "async-graphql")]
fn safe_unsigned(value: u128) -> Option<async_graphql::Number> {
(value <= SAFE).then(|| {
async_graphql::Number::from(u64::try_from(value).expect("the safe range fits a `u64`"))
})
}
#[cfg(feature = "async-graphql")]
fn safe_signed(value: i128) -> Option<async_graphql::Number> {
(value.unsigned_abs() <= SAFE).then(|| {
async_graphql::Number::from(i64::try_from(value).expect("the safe range fits an `i64`"))
})
}
#[cfg(feature = "async-graphql")]
fn integral(number: &async_graphql::Number) -> Option<i128> {
number
.as_i64()
.map(i128::from)
.or_else(|| number.as_u64().map(i128::from))
}
macro_rules! carrier {
($( #[$gate:meta] )* $name:ident($domain:ty), $doc:literal) => {
carrier!(@ [Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord]
$( #[$gate] )* $name($domain), $doc);
};
($( #[$gate:meta] )* partial $name:ident($domain:ty), $doc:literal) => {
carrier!(@ [Debug, Clone, PartialEq, PartialOrd] $( #[$gate] )* $name($domain), $doc);
};
($( #[$gate:meta] )* bare $name:ident($domain:ty), $doc:literal) => {
carrier!(@ [Debug, Clone] $( #[$gate] )* $name($domain), $doc);
};
(@ [$($derive:ident),+ $(,)?] $( #[$gate:meta] )* $name:ident($domain:ty), $doc:literal) => {
#[doc = $doc]
#[doc = ""]
#[doc = "A WIRE CARRIER: it exists so that the operand's own type does not have to implement a"]
#[doc = "foreign trait it may not. Every filter slot it crosses into holds the domain value."]
#[derive($($derive),+)]
$( #[$gate] )*
pub struct $name($domain);
$( #[$gate] )*
impl $name {
#[inline]
#[must_use]
pub const fn get(&self) -> &$domain {
&self.0
}
#[inline]
#[must_use]
pub fn into_inner(self) -> $domain {
self.0
}
}
$( #[$gate] )*
impl From<$domain> for $name {
#[inline]
fn from(value: $domain) -> Self {
Self(value)
}
}
$( #[$gate] )*
impl From<$name> for $domain {
#[inline]
fn from(carrier: $name) -> Self {
carrier.0
}
}
};
}
carrier!(
U8(u8),
"An unsigned 8-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
U16(u16),
"An unsigned 16-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
U32(u32),
"An unsigned 32-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
U64(u64),
"An unsigned 64-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
U128(u128),
"An unsigned 128-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
I8(i8),
"A signed 8-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
I16(i16),
"A signed 16-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
I32(i32),
"A signed 32-bit integer on the wire — a JSON number, exact in both directions."
);
carrier!(
I64(i64),
"A signed 64-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
I128(i128),
"A signed 128-bit integer on the wire — a JSON number inside the safe range, decimal text beyond it."
);
carrier!(
#[cfg(feature = "half")]
partial F16(half::f16),
"A HALF-precision float on the wire — a JSON number, which a double holds one of exactly."
);
carrier!(
partial F32(f32),
"A single-precision float on the wire — a JSON number, which is what a double holds one of exactly."
);
carrier!(
partial F64(f64),
"A double-precision float on the wire — a JSON number, which IS a double."
);
carrier!(
#[cfg(feature = "rust_decimal")]
F128(rust_decimal::Decimal),
"The widest float row on the wire — DECIMAL TEXT, exact at every magnitude its operand holds."
);
carrier!(
HexBytes(Vec<u8>),
"A byte string on the wire — lowercase hexadecimal, two characters per byte."
);
macro_rules! text_render {
($( $name:ident via $render:path ),+ $(,)?) => {
$(
impl Display for $name {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str($render(self.0.into()).as_str())
}
}
)+
};
}
text_render!(
U64 via Digits::unsigned,
U128 via Digits::unsigned,
I64 via Digits::signed,
I128 via Digits::signed,
);
macro_rules! hex_render {
($( $name:ty ),+ $(,)?) => {
$(
impl Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for byte in &self.0 {
f.write_str(nibbles(*byte).as_str())?;
}
Ok(())
}
}
)+
};
}
hex_render!(HexBytes, U8Vector, SmolBytes);
impl<const N: usize> Display for FixedU8Array<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for byte in &self.0 {
f.write_str(nibbles(*byte).as_str())?;
}
Ok(())
}
}
#[cfg(feature = "async-graphql")]
pub(crate) fn narrowed(wide: f64) -> f32 {
wide as f32
}
#[cfg(all(feature = "half", feature = "async-graphql"))]
pub(crate) fn halved(wide: f64) -> half::f16 {
half::f16::from_f64(wide)
}
const fn capitalised<const N: usize>(name: &str) -> [u8; N] {
let source = name.as_bytes();
assert!(source.len() == N, "the caller passes the name's own length");
let mut raised = [0_u8; N];
let mut at = 0;
while at < N {
raised[at] = source[at];
at += 1;
}
raised[0] = raised[0].to_ascii_uppercase();
raised
}
macro_rules! derived_filter {
($gql:literal) => {{
const DERIVED: &str = concat!($gql, "Filter");
const RAISED: [u8; DERIVED.len()] = capitalised::<{ DERIVED.len() }>(DERIVED);
match ::core::str::from_utf8(&RAISED) {
Ok(name) => name,
Err(_) => panic!("a roster name is ASCII"),
}
}};
}
macro_rules! builtin_reading {
($( $name:ident($domain:ty) : $gql:literal ),+ $(,)?) => {
$(
impl ScalarWire<$domain> for Builtin {
const NAME: &'static str = derived_filter!($gql);
type Carrier = $name;
type Error = Infallible;
#[inline]
fn cross(carrier: $name) -> Result<$domain, Infallible> {
Ok(<$name as Into<$domain>>::into(carrier))
}
#[inline]
fn carry(operand: &$domain) -> $name {
<$name>::from(operand.clone())
}
}
)+
};
}
#[cfg(all(test, feature = "async-graphql"))]
macro_rules! filtered_row {
($name:ident($domain:ty) : $gql:literal) => {
Row {
rust: stringify!($domain),
scalar: $gql,
filter: Some(derived_filter!($gql)),
scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
filter_face: Some(|| {
<crate::ScalarFilter<$domain> as async_graphql::InputType>::type_name().into_owned()
}),
}
};
}
#[cfg(all(
test,
feature = "async-graphql",
any(feature = "half", feature = "rust_decimal")
))]
macro_rules! lone_row {
($name:ident($domain:ty) : $gql:literal) => {
Row {
rust: stringify!($domain),
scalar: $gql,
filter: None,
scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
filter_face: None,
}
};
}
macro_rules! hybrid_integer_scalar {
(rows = $rows:ident; $(
$name:ident($domain:ty) : $gql:literal via $render:path, safe = $safe:path
{ $( $doc:literal )+ }
)+) => {
builtin_reading!($( $name($domain) : $gql ),+);
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];
$(
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let range = || format!("{} … {}", <$domain>::MIN, <$domain>::MAX);
if let Some(digits) = text(&value) {
return match digits.parse() {
Ok(operand) => Ok(Self(operand)),
Err(error) => Err(async_graphql::InputValueError::custom(refuse(
$gql,
digits,
core::num::ParseIntError::kind(&error),
&range(),
&<$domain>::MAX.to_string(),
))),
};
}
if let async_graphql::Value::Number(ref number) = value {
return match integral(number).and_then(|whole| <$domain>::try_from(whole).ok()) {
Some(operand) => Ok(Self(operand)),
None => Err(async_graphql::InputValueError::custom(refuse_number(
$gql, number, &range(),
))),
};
}
Err(async_graphql::InputValueError::expected_type(value))
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
if let Some(digits) = text(value) {
return digits.parse::<$domain>().is_ok();
}
matches!(
value,
async_graphql::Value::Number(number)
if integral(number).is_some_and(|whole| <$domain>::try_from(whole).is_ok())
)
}
fn to_value(&self) -> async_graphql::Value {
match $safe(self.0.into()) {
Some(number) => async_graphql::Value::Number(number),
None => async_graphql::Value::String(
String::from($render(self.0.into()).as_str()),
),
}
}
}
)+
};
}
hybrid_integer_scalar! {
rows = HYBRID_ROWS;
U64(u64) : "u64" via Digits::unsigned, safe = safe_unsigned {
"An unsigned 64-bit integer — `42` as a JSON number, `\"18446744073709551615\"` as decimal text."
""
"**HYBRID, and the boundary is 9007199254740991 — 2^53 − 1.** `serde_json`'s number is a `u64`,"
"an `i64` or an `f64`, and a JavaScript client reads every number as a double, so an integer"
"past that bound arrives with its low bits rounded away and no error anywhere: 2^53 + 1 is not"
"representable and rounds to 2^53. Up to the bound a number is exact and a client can do"
"arithmetic on it directly; past it the value crosses as decimal text, which is exact at every"
"magnitude."
""
"A value SENT in either form is read, at any magnitude the range holds — a string of digits"
"always, a JSON number wherever it is whole and in range — so a client written against either"
"form alone works unchanged. What comes BACK is the number below the bound and the string above"
"it, never both for one value."
""
"A value outside the range is REFUSED and never wrapped or clamped; so are a fraction, a"
"boolean and an empty string. The refusal names the range, that being the one fact a client"
"cannot discover by trying."
}
U128(u128) : "u128" via Digits::unsigned, safe = safe_unsigned {
"An unsigned 128-bit integer — `42` as a JSON number,"
"`\"340282366920938463463374607431768211455\"` as decimal text."
""
"HYBRID at 2^53 − 1, for `u64`'s reason, over a domain most of which no client could hold under"
"any encoding but text."
""
"Both forms are read on the way in and one comes back per value. A value outside the range is"
"REFUSED and never wrapped or clamped, and the refusal names the range."
}
I64(i64) : "i64" via Digits::signed, safe = safe_signed {
"A signed 64-bit integer — `-42` as a JSON number, `\"-9223372036854775808\"` as decimal text."
""
"HYBRID at a MAGNITUDE of 2^53 − 1, for `u64`'s reason: the bound is about how many bits a"
"double carries, so it is symmetric about zero. A leading `-` is part of the value; a leading"
"`+` is accepted in the string form and does not come back."
""
"Both forms are read on the way in and one comes back per value. A value outside the range is"
"REFUSED and never wrapped or clamped, and the refusal names the range."
}
I128(i128) : "i128" via Digits::signed, safe = safe_signed {
"A signed 128-bit integer — `-42` as a JSON number,"
"`\"-170141183460469231731687303715884105728\"` as decimal text."
""
"HYBRID at a MAGNITUDE of 2^53 − 1, for `i64`'s reason. A leading `-` is part of the value; a"
"leading `+` is accepted in the string form and does not come back."
""
"Both forms are read on the way in and one comes back per value. A value outside the range is"
"REFUSED and never wrapped or clamped, and the refusal names the range."
}
}
macro_rules! number_integer_scalar {
(rows = $rows:ident; $(
$name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }
)+) => {
builtin_reading!($( $name($domain) : $gql ),+);
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];
$(
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let async_graphql::Value::Number(ref number) = value else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match integral(number).and_then(|whole| <$domain>::try_from(whole).ok()) {
Some(operand) => Ok(Self(operand)),
None => Err(async_graphql::InputValueError::custom(format!(
"`{number}` is not a `{}` — one crosses as a WHOLE JSON number ({} … {}), and a \
value outside that range is refused rather than wrapped",
$gql,
<$domain>::MIN,
<$domain>::MAX,
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(
value,
async_graphql::Value::Number(number)
if integral(number).is_some_and(|whole| <$domain>::try_from(whole).is_ok())
)
}
#[inline]
fn to_value(&self) -> async_graphql::Value {
async_graphql::Value::Number(async_graphql::Number::from(self.0))
}
}
)+
};
}
number_integer_scalar! {
rows = NUMBER_ROWS;
U8(u8) : "u8" {
"An unsigned 8-bit integer as a JSON number — `0` … `255`."
""
"A NUMBER rather than text: the whole domain fits a double exactly, so there is no 2^53 to be"
"honest about and text would cost a client the arithmetic. What the scalar carries is the"
"WIDTH, which async-graphql's `Int` does not — it spells ten distinct Rust types."
""
"A value outside the range is REFUSED and never wrapped or clamped, and so is a fraction."
}
U16(u16) : "u16" {
"An unsigned 16-bit integer as a JSON number — `0` … `65535`."
""
"A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
"wrapped or clamped, and so is a fraction."
}
U32(u32) : "u32" {
"An unsigned 32-bit integer as a JSON number — `0` … `4294967295`."
""
"A NUMBER rather than text, for `u8`'s reason: `u32::MAX` is 2^32 − 1, twenty-one bits short"
"of the 2^53 where a double starts dropping low bits. A value outside the range is REFUSED and"
"never wrapped or clamped, and so is a fraction."
}
I8(i8) : "i8" {
"A signed 8-bit integer as a JSON number — `-128` … `127`."
""
"A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
"wrapped or clamped, and so is a fraction."
}
I16(i16) : "i16" {
"A signed 16-bit integer as a JSON number — `-32768` … `32767`."
""
"A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
"wrapped or clamped, and so is a fraction."
}
I32(i32) : "i32" {
"A signed 32-bit integer as a JSON number — `-2147483648` … `2147483647`."
""
"A NUMBER rather than text, for `u8`'s reason. A value outside the range is REFUSED and never"
"wrapped or clamped, and so is a fraction."
}
}
macro_rules! number_float_scalar {
(rows = $rows:ident; $(
$name:ident($domain:ty) : $gql:literal,
narrow = $narrow:path, widen = $widen:path
{ $( $doc:literal )+ }
)+) => {
builtin_reading!($( $name($domain) : $gql ),+);
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];
$(
number_float_scalar!(@citizen $name($domain) : $gql,
narrow = $narrow, widen = $widen { $( $doc )+ });
)+
};
(lone rows = $rows:ident under #[$gate:meta]; $(
$name:ident($domain:ty) : $gql:literal,
narrow = $narrow:path, widen = $widen:path
{ $( $doc:literal )+ }
)+) => {
#[cfg(all(test, feature = "async-graphql"))]
#[$gate]
pub(crate) const $rows: &[Row] = &[ $( lone_row!($name($domain) : $gql) ),+ ];
$(
number_float_scalar!(@citizen #[$gate] $name($domain) : $gql,
narrow = $narrow, widen = $widen { $( $doc )+ });
)+
};
(@citizen $( #[$gate:meta] )* $name:ident($domain:ty) : $gql:literal,
narrow = $narrow:path, widen = $widen:path
{ $( $doc:literal )+ }) => {
$( #[doc = $doc] )+
$( #[$gate] )*
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let async_graphql::Value::Number(ref number) = value else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match number.as_f64() {
Some(wide) => Ok(Self($narrow(wide))),
None => Err(async_graphql::InputValueError::custom(format!(
"`{number}` is not a `{}` — one crosses as a JSON number",
$gql,
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(value, async_graphql::Value::Number(number) if number.as_f64().is_some())
}
fn to_value(&self) -> async_graphql::Value {
match async_graphql::Number::from_f64($widen(self.0)) {
Some(number) => async_graphql::Value::Number(number),
None => async_graphql::Value::Null,
}
}
}
};
}
number_float_scalar! {
lone rows = HALF_ROWS under #[cfg(feature = "half")];
F16(half::f16) : "f16", narrow = halved, widen = f64::from {
"A half-precision float as a JSON number — `0.82`, never `\"0.82\"`."
""
"IEEE **binary16** — the format `half::f16` holds, one sign bit, five exponent bits and ten"
"mantissa bits. It is NOT `bfloat16`: the two are different formats at one width, and this"
"scalar is explicitly the IEEE one. A `BF16` scalar would be a second name for the second"
"format, and the word is reserved for it."
""
"A NUMBER and not text, for `f32`'s reason at a narrower width and with more room to spare: a"
"JSON number IS a double to the client that reads it, and every binary16 value widens into one"
"EXACTLY — eleven significant bits against a double's fifty-three — so there is no boundary to"
"be honest about and no hybrid form."
""
"A wire value past `f16::MAX` (65504) narrows to an infinity rather than refusing, which is the"
"behaviour `f32` already carries for the same conversion: the scalar says what width a value is"
"read at and does not add a range this framework would then have to defend."
""
"**Behind the `half` cargo feature**, and both the type and this scalar arrive with it: a build"
"that declares no half-precision value pays for no half-precision crate."
}
}
number_float_scalar! {
rows = FLOAT_ROWS;
F32(f32) : "f32", narrow = narrowed, widen = f64::from {
"A single-precision float as a JSON number — `0.82`, never `\"0.82\"`."
""
"A NUMBER and not text, which is the one place this suite's 2^53 argument does NOT apply: a"
"JSON number IS a double to the client that reads it, and an `f32` widens into one exactly."
"What the scalar buys is the NAME — async-graphql publishes `f32` and `f64` both as `Float`,"
"so two declarations measuring in the two widths were one SDL type a client could not tell"
"apart."
""
"A wire value past `f32::MAX` narrows to an infinity rather than refusing, which is"
"async-graphql's own `Float` behaviour kept deliberately: this scalar changes what a width is"
"called and not what it accepts."
}
F64(f64) : "f64", narrow = core::convert::identity, widen = core::convert::identity {
"A double-precision float as a JSON number — `0.82`, never `\"0.82\"`."
""
"A NUMBER and not text, and here the wire form and the value are the SAME object: a JSON number"
"is a double, and so is this. Nothing is lost in either direction, so the text form the four"
"wide integers take would be a cost with no honesty behind it."
""
"What the scalar buys is the NAME — see `f32`, whose width shared this one's SDL type."
}
}
#[cfg(all(feature = "rust_decimal", feature = "async-graphql"))]
pub(crate) fn widened(wide: f64) -> Option<rust_decimal::Decimal> {
rust_decimal::Decimal::from_f64_retain(wide)
}
#[cfg(feature = "rust_decimal")]
macro_rules! decimal_scalar {
(rows = $rows:ident; $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
if let Some(digits) = text(&value) {
return match <$domain>::from_str_exact(digits) {
Ok(operand) => Ok(Self(operand)),
Err(error) => Err(async_graphql::InputValueError::custom(format!(
"`{digits}` is not an `{}` — a string operand is DECIMAL TEXT inside \
`{}` … `{}`, and this one is refused: {error}",
$gql,
<$domain>::MIN,
<$domain>::MAX,
))),
};
}
if let async_graphql::Value::Number(ref number) = value {
return match number.as_f64().and_then(widened) {
Some(operand) => Ok(Self(operand)),
None => Err(async_graphql::InputValueError::custom(format!(
"`{number}` is not an `{}` — a JSON number crosses inside `{}` … `{}` and cannot be a \
NaN or an infinity, and a value needing more than a double's precision is written as \
DECIMAL TEXT instead, which is exact in both directions",
$gql,
<$domain>::MIN,
<$domain>::MAX,
))),
};
}
Err(async_graphql::InputValueError::expected_type(value))
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
if let Some(digits) = text(value) {
return <$domain>::from_str_exact(digits).is_ok();
}
matches!(
value,
async_graphql::Value::Number(number)
if number.as_f64().and_then(widened).is_some()
)
}
fn to_value(&self) -> async_graphql::Value {
async_graphql::Value::String(self.0.to_string())
}
}
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[lone_row!($name($domain) : $gql)];
};
}
#[cfg(feature = "rust_decimal")]
decimal_scalar! {
rows = DECIMAL_ROWS;
F128(rust_decimal::Decimal) : "f128" {
"The widest float row, as DECIMAL TEXT — `\"0.1\"`, never `0.1`."
""
"**IT IS NOT IEEE binary128, and the backing is TEMPORARY.** `f128` is the name the roster gives"
"the widest float row; Rust's own `f128` is not stable, so the seat is held by"
"`rust_decimal::Decimal` — a 96-bit mantissa under a base-ten scale, roughly 28 significant"
"DECIMAL digits over ±7.9e28, where binary128 is a 113-bit significand over a binary exponent"
"reaching ±1.2e4932. A client should read this scalar as *an exact decimal wider than a double*"
"and not as a binary float of any width. **Behind the `rust_decimal` cargo feature.**"
""
"TEXT in both directions on the way out, where the four wide integers fork at 2^53 − 1. The fork"
"buys a client arithmetic on the values below the bound; there is no such range here, because"
"the operand is base-ten and `0.1` has no double that IS it. So the exact form is the only form"
"returned."
""
"A JSON NUMBER is read on the way in — Postel's half, as at every hybrid width — and what it"
"carries is the DOUBLE's own value. A number needing more precision than a double has already"
"lost it before this crate sees it, so the number leg is exact about the wire value and says"
"nothing about the value a client meant; a client that wants what it meant writes the text."
""
"A string is DECIMAL TEXT and is read EXACTLY: excess precision is refused rather than rounded"
"away, which is what `from_str_exact` buys over the rounding parse beside it. A value outside"
"the range is refused, and so are a NaN and an infinity — a decimal has neither."
}
}
macro_rules! bytes_scalar {
(roster $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
bytes_scalar!($name($domain) : $gql { $( $doc )+ });
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const BYTES_ROWS: &[Row] = &[Row {
rust: stringify!($domain),
scalar: $gql,
filter: Some(derived_filter!($gql)),
scalar_face: || <$name as async_graphql::InputType>::type_name().into_owned(),
filter_face: Some(|| {
<crate::BytesFilter<$domain> as async_graphql::InputType>::type_name().into_owned()
}),
}];
};
($name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let Some(hex) = text(&value) else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match read_hex(hex) {
Some(bytes) => Ok(Self(bytes)),
None => Err(async_graphql::InputValueError::custom(format!(
"`{hex}` is not a byte string — bytes cross as an EVEN number of hex digits, two per \
byte (`\"89504e47\"`), optionally under a `0x` prefix"
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(text(value), Some(hex) if read_hex(hex).is_some())
}
fn to_value(&self) -> async_graphql::Value {
let mut hex = String::with_capacity(self.0.len() * 2);
for byte in &self.0 {
hex.push_str(nibbles(*byte).as_str());
}
async_graphql::Value::String(hex)
}
}
impl BytesWire<$domain> for Builtin {
const NAME: &'static str = derived_filter!($gql);
type Carrier = $name;
type Error = Infallible;
#[inline]
fn cross(carrier: $name) -> Result<$domain, Infallible> {
Ok(<$domain>::from(::std::vec::Vec::from(carrier)))
}
#[inline]
fn carry(operand: &$domain) -> $name {
<$name>::from(<$domain as ::core::convert::AsRef<[u8]>>::as_ref(operand).to_vec())
}
}
};
}
bytes_scalar! {
roster HexBytes(::bytes::Bytes) : "bytes" {
"A byte string as lowercase hexadecimal — `\"89504e470d0a1a0a\"`, two characters per byte."
""
"An EVEN number of hex digits, `0`–`9` and `a`–`f`. Uppercase is accepted and a `0x` prefix is"
"accepted; neither comes back — the rendered form is always lowercase and unprefixed, so"
"`parse(render(b)) == b` holds while `render(parse(t))` is the CANONICAL spelling of `t` rather"
"than `t` itself."
""
"Hex rather than base64, and the reason is the operators this operand is written for. A byte"
"column's filter carries `contains`/`notContains` over byte SUBSTRINGS, and the values a caller"
"has to hand — a checksum, a magic number, a content id — are written in hex everywhere else"
"they appear. Base64 is denser, and its three-byte grouping means no prefix of the encoded text"
"is a prefix of the bytes, so a client would be composing substring operands in a form it cannot"
"read."
""
"**The name is the ROSTER's, and the encoding is this carrier's** — `bytes` is what the"
"framework's DEFAULT blob operand publishes, and that operand is `bytes::Bytes`. Every OTHER"
"byte vocabulary crosses in this same lowercase hex and under a scalar of its OWN name, so a"
"`U8VectorFilter`'s `eq` reads `U8Vector` and never `bytes`. The grammar is one grammar — every"
"skin parses and renders through `read_hex` and `nibbles`, which are written once."
}
}
carrier!(
U8Vector(Vec<u8>),
"A `Vec<u8>` column's bytes — lowercase hexadecimal, two characters per byte."
);
bytes_scalar! {
U8Vector(Vec<u8>) : "U8Vector" {
"A `Vec<u8>` column, as lowercase hexadecimal — two characters per byte."
""
"The grammar is `bytes`': an EVEN number of hex digits, either case, optionally `0x`-prefixed,"
"rendered back lowercase and unprefixed. It is not a second grammar and cannot become one —"
"every byte scalar in this schema is a thin skin over ONE reader and ONE renderer."
""
"**A SCALAR OF ITS OWN, and the name is the point.** Every byte vocabulary crossed under the"
"roster's `bytes` until 2026-08-19, so a schema published `U8VectorFilter { eq: bytes }` — an"
"input object naming one household whose operand named another. A reader had to know that the"
"two words described one wire form to read it as anything but a mistake. The wire form is still"
"one; what each household publishes now is its own name for it."
}
}
carrier!(
SmolBytes(Vec<u8>),
"A `smol_bytes::Bytes` column's bytes — lowercase hexadecimal, two characters per byte."
);
bytes_scalar! {
SmolBytes(::smol_bytes::Bytes) : "SmolBytes" {
"The `smol-bytes` blob vocabulary, as lowercase hexadecimal — two characters per byte."
""
"`bytes`' grammar and `bytes`' reader — see [`U8Vector`] for why the household has a scalar of"
"its own rather than sharing the roster's."
""
"ONE name for the crate's whole immutable byte household: `smol_bytes::Bytes` is the root"
"re-export of `shared::Bytes`, and the compact strategy beside it is an allocation choice rather"
"than a wire form, so it publishes nothing of its own."
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FixedU8Array<const N: usize>(Vec<u8>);
impl<const N: usize> From<Vec<u8>> for FixedU8Array<N> {
#[inline]
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl<const N: usize> From<FixedU8Array<N>> for Vec<u8> {
#[inline]
fn from(carrier: FixedU8Array<N>) -> Self {
carrier.0
}
}
#[cfg(feature = "async-graphql")]
fn fixed_u8_array_name<const N: usize>() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Owned(std::format!("Fixed{N}U8Array"))
}
#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::ScalarType for FixedU8Array<N> {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let Some(hex) = text(&value) else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match read_hex(hex) {
Some(bytes) => Ok(Self(bytes)),
None => Err(async_graphql::InputValueError::custom(format!(
"`{hex}` is not a byte string — bytes cross as an EVEN number of hex digits, two per byte \
(`\"89504e47\"`), optionally under a `0x` prefix"
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(text(value), Some(hex) if read_hex(hex).is_some())
}
fn to_value(&self) -> async_graphql::Value {
let mut hex = String::with_capacity(self.0.len() * 2);
for byte in &self.0 {
hex.push_str(nibbles(*byte).as_str());
}
async_graphql::Value::String(hex)
}
}
#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::InputType for FixedU8Array<N> {
type RawValueType = Self;
fn type_name() -> std::borrow::Cow<'static, str> {
fixed_u8_array_name::<N>()
}
fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
registry.create_input_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
fixed_u8_array_meta::<N>()
})
}
fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
<Self as async_graphql::ScalarType>::parse(value.unwrap_or_default())
}
fn to_value(&self) -> async_graphql::Value {
<Self as async_graphql::ScalarType>::to_value(self)
}
fn as_raw_value(&self) -> Option<&Self::RawValueType> {
Some(self)
}
}
#[cfg(feature = "async-graphql")]
impl<const N: usize> async_graphql::OutputType for FixedU8Array<N> {
fn type_name() -> std::borrow::Cow<'static, str> {
fixed_u8_array_name::<N>()
}
fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
registry.create_output_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
fixed_u8_array_meta::<N>()
})
}
async fn resolve(
&self,
_: &async_graphql::ContextSelectionSet<'_>,
_field: &async_graphql::Positioned<async_graphql::parser::types::Field>,
) -> async_graphql::ServerResult<async_graphql::Value> {
Ok(<Self as async_graphql::ScalarType>::to_value(self))
}
}
#[cfg(feature = "async-graphql")]
fn fixed_u8_array_meta<const N: usize>() -> async_graphql::registry::MetaType {
async_graphql::registry::MetaType::Scalar {
name: fixed_u8_array_name::<N>().into_owned(),
description: Some(std::format!(
"A {N}-byte column, as lowercase hexadecimal — exactly {} characters. A value of any other \
width is refused, naming both numbers, rather than padded or truncated.",
N * 2
)),
is_valid: Some(std::sync::Arc::new(|value| {
<FixedU8Array<N> as async_graphql::ScalarType>::is_valid(value)
})),
visible: None,
inaccessible: false,
tags: Vec::new(),
specified_by_url: None,
directive_invocations: Vec::new(),
requires_scopes: Vec::new(),
}
}
carrier!(
NetIpv4Addr(::std::net::Ipv4Addr),
"An IPv4 address on the wire — the dotted quad, `\"192.0.2.1\"`."
);
carrier!(
NetIpv6Addr(::std::net::Ipv6Addr),
"An IPv6 address on the wire — RFC 5952 canonical text, `\"2001:db8::1\"`."
);
carrier!(
NetIpAddr(::std::net::IpAddr),
"An IP address of EITHER version on the wire — whichever version's own canonical text."
);
carrier!(
NetSocketAddrV4(::std::net::SocketAddrV4),
"An IPv4 address and a port on the wire — `\"192.0.2.1:443\"`."
);
carrier!(
NetSocketAddrV6(::std::net::SocketAddrV6),
"An IPv6 address and a port on the wire — `\"[2001:db8::1]:443\"`, the address bracketed."
);
carrier!(
NetSocketAddr(::std::net::SocketAddr),
"An address and a port of EITHER version on the wire — whichever version's own canonical text."
);
carrier!(
HyphenatedUuid(::uuid::Uuid),
"A UUID on the wire — the canonical lowercase hyphenated text, \
`\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`."
);
macro_rules! parsed_text_scalar {
(rows = $rows:ident; $(
$name:ident($domain:ty) : $gql:literal, grammar = $grammar:literal
{ $( $doc:literal )+ }
)+) => {
builtin_reading!($( $name($domain) : $gql ),+);
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[ $( filtered_row!($name($domain) : $gql) ),+ ];
$(
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let Some(spelling) = text(&value) else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match spelling.parse::<$domain>() {
Ok(operand) => Ok(Self(operand)),
Err(_) => Err(async_graphql::InputValueError::custom(format!(
"`{spelling}` is not `{}` text — one crosses as {}, and a spelling outside that \
grammar is REFUSED and never guessed at",
$gql, $grammar,
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(text(value), Some(spelling) if spelling.parse::<$domain>().is_ok())
}
fn to_value(&self) -> async_graphql::Value {
async_graphql::Value::String(self.0.to_string())
}
}
)+
};
}
parsed_text_scalar! {
rows = NET_ROWS;
NetIpv4Addr(::std::net::Ipv4Addr) : "Ipv4Addr", grammar = "the DOTTED QUAD — four decimal octets \
under three dots, as in `\"192.0.2.1\"`" {
"An IPv4 address as the DOTTED QUAD — `\"192.0.2.1\"`, never a packed integer."
""
"Four decimal octets under three dots, each `0` … `255`. A LEADING ZERO is refused rather than"
"read — `\"01.2.3.4\"` is not an address — which is the standard library's own rule and the right"
"one: a leading zero means octal in some resolvers and decimal in others, so the same text names"
"two hosts."
""
"**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
"`Ipv4AddrFilter`. The four-byte integer an address packs into is a REPRESENTATION and not a"
"spelling — no client writes one, and a `u32` column already publishes that form under its own"
"name."
""
"A value outside the grammar is REFUSED and never guessed at; so is a JSON number, which is a"
"value of the wrong type rather than a badly spelled address."
}
NetIpv6Addr(::std::net::Ipv6Addr) : "Ipv6Addr", grammar = "RFC 4291 TEXT — up to eight \
colon-separated hextets, with at most one `::` run, as in `\"2001:db8::1\"`" {
"An IPv6 address as RFC 5952 CANONICAL text — `\"2001:db8::1\"`."
""
"Every spelling RFC 4291 admits is READ: upper or lower case, leading zeros, a `::` run anywhere,"
"and the embedded-IPv4 tail. What comes BACK is the RFC 5952 canonical form and only that — the"
"longest run of zero hextets compressed to `::`, lowercase, no leading zeros — so"
"`\"2001:0DB8:0000:0000:0000:0000:0000:0001\"` is read and renders as `\"2001:db8::1\"`. An"
"IPv4-mapped address keeps its dotted tail (`\"::ffff:192.0.2.1\"`), which is RFC 5952's own"
"exception."
""
"So `parse(render(a)) == a` holds always, and `render(parse(t))` is the CANONICAL spelling of `t`"
"rather than `t` itself — the same promise the byte households make about hex."
""
"A spelling outside the grammar is REFUSED and never guessed at."
}
NetIpAddr(::std::net::IpAddr) : "IpAddr", grammar = "an IPv4 DOTTED QUAD or an RFC 4291 IPv6 \
text, as in `\"192.0.2.1\"` or `\"2001:db8::1\"`" {
"An IP address of EITHER version — `\"192.0.2.1\"` or `\"2001:db8::1\"`."
""
"**UNTAGGED**: the version is read off the spelling and never written beside it. Both are parsed"
"on the way in, and what comes back is the canonical text of whichever version the value holds —"
"the dotted quad for a v4 and the RFC 5952 form for a v6, exactly as [`Ipv4Addr`](NetIpv4Addr)"
"and [`Ipv6Addr`](NetIpv6Addr) render their own."
""
"A column that must be one version names that version's scalar instead, where the wrong version"
"is refused at the parse rather than stored. This one is the column that holds either."
""
"A spelling that is neither version is REFUSED and never guessed at."
}
NetSocketAddrV4(::std::net::SocketAddrV4) : "SocketAddrV4", grammar = "a DOTTED QUAD under a \
colon and a port, as in `\"192.0.2.1:443\"`" {
"An IPv4 address and a port — `\"192.0.2.1:443\"`."
""
"The address is [`Ipv4Addr`](NetIpv4Addr)'s dotted quad and the port is a decimal `0` … `65535`,"
"separated by a colon. Both halves are part of the value: a spelling with no port is not a socket"
"address and is REFUSED rather than defaulted to zero."
}
NetSocketAddrV6(::std::net::SocketAddrV6) : "SocketAddrV6", grammar = "a BRACKETED IPv6 text \
under a colon and a port, as in `\"[2001:db8::1]:443\"`" {
"An IPv6 address and a port — `\"[2001:db8::1]:443\"`, the address bracketed."
""
"The brackets are what make the port unambiguous: an IPv6 text is full of colons, so the address"
"is delimited before the last one can be read as a separator. The address inside them is"
"[`Ipv6Addr`](NetIpv6Addr)'s, read in every spelling and rendered canonical."
""
"**A SCOPE ID crosses and a FLOWINFO does not**, and that is the operand's own `Display` rather"
"than a choice made here. A non-zero scope is written and read back — `\"[fe80::1%3]:443\"` — and"
"the flow label has no place in the text form at all, so a value carrying one renders without it"
"and comes back as zero. Stated because it is the one row in this family whose round trip is not"
"the identity on every value: a column that has to keep a flow label is not a column this scalar"
"can hold."
}
NetSocketAddr(::std::net::SocketAddr) : "SocketAddr", grammar = "a DOTTED QUAD or a BRACKETED \
IPv6 text under a colon and a port, as in `\"192.0.2.1:443\"` or `\"[2001:db8::1]:443\"`" {
"An address and a port of EITHER version — `\"192.0.2.1:443\"` or `\"[2001:db8::1]:443\"`."
""
"**UNTAGGED**, for [`IpAddr`](NetIpAddr)'s reason and with its shape: both forms are read, and"
"what comes back is the canonical text of whichever version the value holds. The v6 half carries"
"[`SocketAddrV6`](NetSocketAddrV6)'s scope-id note with it."
}
}
parsed_text_scalar! {
rows = UUID_ROWS;
HyphenatedUuid(::uuid::Uuid) : "Uuid", grammar = "the CANONICAL HYPHENATED form — 32 hexadecimal \
digits in 8-4-4-4-12 groups, as in `\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`" {
"A UUID as the CANONICAL LOWERCASE HYPHENATED text —"
"`\"018f3a2b-7c4d-7e1f-9a0b-1c2d3e4f5061\"`, the form RFC 9562 defines and every client library"
"already speaks."
""
"**Every spelling the `uuid` crate parses is READ** — hyphenated, the unhyphenated 32-digit"
"simple form, the braced Microsoft GUID `{…}` and the `urn:uuid:…` URN — in either case. What"
"comes BACK is the lowercase hyphenated form and only that, so a round trip through this scalar"
"CANONICALISES, which is the promise the address family makes about RFC 5952 and the byte"
"households make about hex."
""
"**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
"`UuidFilter`. `Uuid` rather than `UUID` for the register's own reason — `Ipv4Addr` and"
"`SocketAddrV6` are Rust-flavoured Pascal and not acronym shouts, and `UpperCamel` on a name"
"already capital is that name, so one literal spells both."
""
"**NO VERSION IS REQUIRED and none is refused.** A v4, a v7, a nil and a max are all UUIDs and"
"this scalar reads them all: a version check is a fact about where a value CAME FROM, which a"
"grammar cannot state and a constructor can. What ORDER means for a column of them is a storage"
"question — see `column::stored`, where the bytewise order every backend agrees on is recorded,"
"and where a v7's leading timestamp is what makes that order a time order."
""
"The sixteen BYTES are what a column holds; this is what a client writes. A value outside the"
"grammar is REFUSED and never guessed at, and so is a JSON number."
}
}
carrier!(
#[cfg(feature = "regex")]
bare RegexPattern(::regex::Regex),
"A regular expression on the wire — its PATTERN, verbatim, `\"^[a-z]+(?:-[0-9]+)?$\"`."
);
#[cfg(feature = "regex")]
macro_rules! regex_scalar {
(rows = $rows:ident; $name:ident($domain:ty) : $gql:literal { $( $doc:literal )+ }) => {
builtin_reading!($name($domain) : $gql);
$( #[doc = $doc] )+
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = $gql)]
impl async_graphql::ScalarType for $name {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
let Some(pattern) = text(&value) else {
return Err(async_graphql::InputValueError::expected_type(value));
};
match <$domain>::new(pattern) {
Ok(operand) => Ok(Self(operand)),
Err(error) => Err(async_graphql::InputValueError::custom(format!(
"`{pattern}` is not `{}` text — a pattern crosses as the expression itself and is \
COMPILED on the way in, and this one does not compile: {error}",
$gql,
))),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
matches!(text(value), Some(pattern) if <$domain>::new(pattern).is_ok())
}
fn to_value(&self) -> async_graphql::Value {
async_graphql::Value::String(self.0.as_str().to_owned())
}
}
#[cfg(all(test, feature = "async-graphql"))]
pub(crate) const $rows: &[Row] = &[filtered_row!($name($domain) : $gql)];
};
}
#[cfg(feature = "regex")]
regex_scalar! {
rows = REGEX_ROWS;
RegexPattern(::regex::Regex) : "Regex" {
"A regular expression as its PATTERN — `\"^[a-z]+(?:-[0-9]+)?$\"`, the expression itself and"
"never a description of one."
""
"**IT IS COMPILED ON THE WAY IN, and a pattern that does not compile is REFUSED with the"
"engine's own sentence.** The refusal names the offending span and the rule it broke, because"
"that is the only thing a client writing a pattern can act on; nothing is guessed at and no"
"pattern is repaired."
""
"**The dialect is the `regex` crate's**, which is Rust's leading-crate syntax and NOT PCRE: there"
"is no backreference and no lookaround, every pattern runs in time linear in the haystack, and"
"case-insensitivity and multi-line reading are written INSIDE the expression as `(?i)` and"
"`(?m)` rather than beside it as flags. A pattern that needs a backreference is not a pattern"
"this column can hold, and it is refused at the wire rather than stored and failed later."
""
"**A NAMED TYPE and not a roster width**, so the scalar is Pascal and its filter derives from it:"
"`RegexFilter`."
""
"**The round trip is the identity on the TEXT.** What comes back is the pattern that went in,"
"character for character — this scalar canonicalises nothing, unlike [`Uuid`](HyphenatedUuid)"
"and the address family, because a pattern has no canonical spelling: `(?i)a` and `[aA]` accept"
"the same strings and are two different values here, two different rows in a column, and two"
"different answers to `eq`."
""
"**Comparison is over the PATTERN and never over what it MATCHES.** `eq`, the ordering"
"operators and `in` all ask about the expression as text — which pattern is stored — and no"
"operator anywhere asks a stored pattern to match a string. That question belongs to whatever"
"runs the pattern, which is the declaring application and not the store."
""
"A value outside the dialect is REFUSED and never guessed at, and so is a JSON number, which is"
"a value of the wrong type rather than a badly written pattern."
}
}
fn nibbles(byte: u8) -> Digits {
let mut buffer = [0u8; Digits::WIDTH];
buffer[Digits::WIDTH - 2] = HEX[usize::from(byte >> 4)];
buffer[Digits::WIDTH - 1] = HEX[usize::from(byte & 0x0f)];
Digits {
buffer,
at: Digits::WIDTH - 2,
}
}
const HEX: &[u8; 16] = b"0123456789abcdef";
#[cfg(feature = "async-graphql")]
fn read_hex(text: &str) -> Option<Vec<u8>> {
let digits = text
.strip_prefix("0x")
.or_else(|| text.strip_prefix("0X"))
.unwrap_or(text)
.as_bytes();
if !digits.len().is_multiple_of(2) {
return None;
}
let mut bytes = Vec::with_capacity(digits.len() / 2);
for pair in digits.as_chunks::<2>().0 {
bytes.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
}
Some(bytes)
}
#[cfg(feature = "async-graphql")]
const fn nibble(digit: u8) -> Option<u8> {
match digit {
b'0'..=b'9' => Some(digit - b'0'),
b'a'..=b'f' => Some(digit - b'a' + 10),
b'A'..=b'F' => Some(digit - b'A' + 10),
_ => None,
}
}