use std::fmt;
use crate::cast::CastError;
use crate::model::PartialSchemaFn;
pub struct Accessor<M> {
name: &'static str,
get: fn(&M) -> Result<serde_json::Value, CastError>,
rust_type: &'static str,
schema: Option<PartialSchemaFn>,
}
impl<M> Accessor<M> {
pub const fn new(
name: &'static str,
get: fn(&M) -> Result<serde_json::Value, CastError>,
rust_type: &'static str,
) -> Self {
Accessor {
name,
get,
rust_type,
schema: None,
}
}
pub const fn with_schema(self, schema: PartialSchemaFn) -> Self {
Accessor {
schema: Some(schema),
..self
}
}
pub const fn name(&self) -> &'static str {
self.name
}
pub const fn rust_type(&self) -> &'static str {
self.rust_type
}
pub const fn schema_override(&self) -> Option<PartialSchemaFn> {
self.schema
}
pub fn value(&self, model: &M) -> Result<serde_json::Value, CastError> {
(self.get)(model)
}
}
impl<M> Clone for Accessor<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M> Copy for Accessor<M> {}
impl<M> fmt::Debug for Accessor<M> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Accessor")
.field("name", &self.name)
.field("rust_type", &self.rust_type)
.finish_non_exhaustive()
}
}
#[doc(hidden)]
pub trait NoAccessors: Sized + 'static {
const __NAVREE_ACCESSORS: &'static [Accessor<Self>] = &[];
}
impl<T: 'static> NoAccessors for T {}
#[doc(hidden)]
pub const fn has_accessor<M>(accessors: &[Accessor<M>], name: &str) -> bool {
let mut index = 0;
while index < accessors.len() {
if same_str(accessors[index].name, name) {
return true;
}
index += 1;
}
false
}
const fn same_str(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
return false;
}
let mut index = 0;
while index < a.len() {
if a[index] != b[index] {
return false;
}
index += 1;
}
true
}
#[cfg(test)]
mod tests {
use super::*;
struct Point {
x: i32,
}
const ACCESSORS: &[Accessor<Point>] = &[Accessor::new(
"doubled",
|point: &Point| Ok(serde_json::json!(point.x * 2)),
"i32",
)];
#[test]
fn accessors_are_found_by_name_at_compile_time() {
const {
assert!(has_accessor(ACCESSORS, "doubled"));
assert!(!has_accessor(ACCESSORS, "double"));
}
assert_eq!(
ACCESSORS[0].value(&Point { x: 21 }).unwrap(),
serde_json::json!(42)
);
assert_eq!(ACCESSORS[0].rust_type(), "i32");
assert_eq!(
format!("{:?}", ACCESSORS[0]),
r#"Accessor { name: "doubled", rust_type: "i32", .. }"#
);
assert!(<Point as NoAccessors>::__NAVREE_ACCESSORS.is_empty());
}
}