use std::{collections::BTreeMap, fmt::Debug, ops::Deref};
use downcast_rs::{DowncastSync, impl_downcast};
use crate::{
Ref,
schema::{Document, ShapeId},
};
pub trait SmithyTrait: DowncastSync {
fn id(&self) -> &ShapeId;
#[allow(clippy::borrowed_box)]
fn value(&self) -> &Box<dyn Document>;
}
impl_downcast!(sync SmithyTrait);
pub trait StaticTraitId: SmithyTrait {
fn trait_id() -> &'static ShapeId;
}
#[derive(Clone)]
#[repr(transparent)]
pub struct TraitRef(Ref<dyn SmithyTrait>);
impl PartialEq for TraitRef {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id() && (self.value() == other.value())
}
}
impl Deref for TraitRef {
type Target = dyn SmithyTrait;
#[inline]
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl From<Ref<dyn SmithyTrait>> for TraitRef {
#[inline]
fn from(value: Ref<dyn SmithyTrait>) -> Self {
Self(value)
}
}
impl<T: SmithyTrait> From<T> for TraitRef {
#[inline]
fn from(value: T) -> Self {
Self(Ref::new(value))
}
}
impl Debug for TraitRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
Debug::fmt(&self.0, f)
}
}
#[derive(Debug, Clone)]
pub struct DynamicTrait {
id: ShapeId,
value: Box<dyn Document>,
}
impl DynamicTrait {
pub fn from<I: Into<ShapeId>, D: Into<Box<dyn Document>>>(id: I, value: D) -> TraitRef {
Self {
id: id.into(),
value: value.into(),
}
.into()
}
}
impl SmithyTrait for DynamicTrait {
fn id(&self) -> &ShapeId {
&self.id
}
fn value(&self) -> &Box<dyn Document> {
&self.value
}
}
#[derive(Clone, PartialEq)]
pub(crate) struct TraitMap {
map: BTreeMap<ShapeId, TraitRef>,
}
impl Eq for TraitMap {}
impl Debug for TraitMap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
let mut l = f.debug_list();
for v in self.map.values() {
l.entry(v);
}
l.finish()
}
}
impl TraitMap {
pub fn new() -> TraitMap {
TraitMap {
map: BTreeMap::new(),
}
}
#[must_use]
#[inline]
pub fn contains(&self, id: &ShapeId) -> bool {
self.map.contains_key(id)
}
#[must_use]
#[inline]
pub fn contains_type<T: StaticTraitId>(&self) -> bool {
self.contains(T::trait_id())
}
#[must_use]
#[inline]
pub fn get(&self, id: &ShapeId) -> Option<&TraitRef> {
self.map.get(id)
}
#[must_use]
#[inline]
pub fn get_as<T: SmithyTrait + StaticTraitId>(&self) -> Option<&T> {
self.get(T::trait_id())
.and_then(|dyn_trait| dyn_trait.downcast_ref::<T>())
}
pub fn extend(&mut self, trait_map: &TraitMap) {
self.map.extend(trait_map.map.clone());
}
pub(crate) fn of(traits: Vec<TraitRef>) -> Self {
let mut map: TraitMap = TraitMap::new();
for smithy_trait in traits {
map.map.insert(smithy_trait.id().clone(), smithy_trait);
}
map
}
}
#[cfg(test)]
mod tests {
use std::any::{Any, TypeId};
use super::*;
use crate::{
schema::prelude::{HttpErrorTrait, JsonNameTrait},
traits,
};
#[test]
fn basic_map_functionality() {
let dyn_id: ShapeId = "smithy.api#Dynamic".into();
let map = TraitMap::of(traits![
JsonNameTrait::new("a"),
DynamicTrait::from(dyn_id.clone(), "b")
]);
assert!(map.contains(&dyn_id));
assert!(map.contains(JsonNameTrait::trait_id()));
assert!(map.contains_type::<JsonNameTrait>());
}
#[test]
fn map_extension() {
let mut map_a = TraitMap::of(traits![JsonNameTrait::new("a")]);
let map_b = TraitMap::of(traits![HttpErrorTrait::new(404)]);
map_a.extend(&map_b);
assert!(map_a.contains(HttpErrorTrait::trait_id()));
assert!(map_a.contains_type::<HttpErrorTrait>());
assert!(map_a.contains_type::<JsonNameTrait>());
}
#[test]
fn trait_conversion_to_type() {
let map = TraitMap::of(traits![HttpErrorTrait::new(404)]);
let Some(cast_value) = map.get_as::<HttpErrorTrait>() else {
panic!("Could not find expected trait!!!")
};
assert_eq!(cast_value.code(), 404);
assert_eq!(cast_value.type_id(), TypeId::of::<HttpErrorTrait>());
}
#[test]
fn from_trait_vec() {
let vec = traits![HttpErrorTrait::new(404), JsonNameTrait::new("a")];
let map = TraitMap::of(vec);
assert!(map.contains_type::<HttpErrorTrait>());
assert!(map.contains_type::<JsonNameTrait>());
}
}