serde: Add Raw::{cast, cast_ref}

This commit is contained in:
Jonas Platte 2022-02-12 01:20:00 +01:00
parent bb99ec72fd
commit 1b4234c505
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67

View File

@ -2,6 +2,7 @@ use std::{
clone::Clone, clone::Clone,
fmt::{self, Debug, Formatter}, fmt::{self, Debug, Formatter},
marker::PhantomData, marker::PhantomData,
mem,
}; };
use serde::{ use serde::{
@ -35,6 +36,7 @@ use crate::cow::MyCowStr;
/// .deserialize() // deserialize to the inner type /// .deserialize() // deserialize to the inner type
/// .unwrap(); // finally get to the AnyRoomEvent /// .unwrap(); // finally get to the AnyRoomEvent
/// ``` /// ```
#[repr(transparent)]
pub struct Raw<T> { pub struct Raw<T> {
json: Box<RawJsonValue>, json: Box<RawJsonValue>,
_ev: PhantomData<T>, _ev: PhantomData<T>,
@ -152,6 +154,20 @@ impl<T> Raw<T> {
{ {
serde_json::from_str(self.json.get()) serde_json::from_str(self.json.get())
} }
/// Turns `Raw<T>` into `Raw<U>` without changing the underlying JSON.
///
/// This is useful for turning raw specific event types into raw event enum types.
pub fn cast<U>(self) -> Raw<U> {
Raw::from_json(self.into_json())
}
/// Turns `&Raw<T>` into `&Raw<U>` without changing the underlying JSON.
///
/// This is useful for turning raw specific event types into raw event enum types.
pub fn cast_ref<U>(&self) -> &Raw<U> {
unsafe { mem::transmute(self) }
}
} }
impl<T> Clone for Raw<T> { impl<T> Clone for Raw<T> {