identifiers: Update ToOwned implementations to use new types

… and a lot of changes that cascaded from that.
This commit is contained in:
Jonas Platte 2022-04-04 19:58:08 +02:00 committed by Jonas Platte
parent ab94bed1dc
commit d855ec33d6
50 changed files with 336 additions and 307 deletions

View File

@ -9,7 +9,7 @@ mod url;
use js_int::UInt; use js_int::UInt;
use ruma_common::{ use ruma_common::{
serde::{Incoming, StringEnum}, serde::{Incoming, StringEnum},
RoomId, UserId, OwnedRoomId, RoomId, UserId,
}; };
use serde::Serialize; use serde::Serialize;
@ -99,7 +99,7 @@ pub struct RoomEventFilter<'a> {
/// If this list is absent then no rooms are excluded. A matching room will be excluded even if /// If this list is absent then no rooms are excluded. A matching room will be excluded even if
/// it is listed in the 'rooms' filter. /// it is listed in the 'rooms' filter.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")] #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_rooms: &'a [Box<RoomId>], pub not_rooms: &'a [OwnedRoomId],
/// The maximum number of events to return. /// The maximum number of events to return.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -109,7 +109,7 @@ pub struct RoomEventFilter<'a> {
/// ///
/// If this list is absent then all rooms are included. /// If this list is absent then all rooms are included.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub rooms: Option<&'a [Box<RoomId>]>, pub rooms: Option<&'a [OwnedRoomId]>,
/// A list of sender IDs to exclude. /// A list of sender IDs to exclude.
/// ///

View File

@ -91,7 +91,7 @@ pub mod v3 {
json!({ "user_id": "@carl:example.org" }), json!({ "user_id": "@carl:example.org" }),
) )
.unwrap(); .unwrap();
let user_id = user_id!("@carl:example.org").into(); let user_id = user_id!("@carl:example.org").to_owned();
let recipient = IncomingInvitationRecipient::UserId { user_id }; let recipient = IncomingInvitationRecipient::UserId { user_id };
assert_eq!(incoming, recipient); assert_eq!(incoming, recipient);
} }

View File

@ -17,7 +17,7 @@ pub mod v3 {
}, },
room::RoomType, room::RoomType,
serde::{Raw, StringEnum}, serde::{Raw, StringEnum},
RoomId, RoomName, RoomVersionId, UserId, OwnedUserId, RoomId, RoomName, RoomVersionId, UserId,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -161,7 +161,7 @@ pub mod v3 {
/// a `RoomCreateEventContent`. /// a `RoomCreateEventContent`.
pub fn into_event_content( pub fn into_event_content(
self, self,
creator: Box<UserId>, creator: OwnedUserId,
room_version: RoomVersionId, room_version: RoomVersionId,
) -> RoomCreateEventContent { ) -> RoomCreateEventContent {
assign!(RoomCreateEventContent::new(creator), { assign!(RoomCreateEventContent::new(creator), {

View File

@ -9,7 +9,7 @@ pub mod v3 {
api::ruma_api, api::ruma_api,
events::{AnyStateEventContent, StateEventType}, events::{AnyStateEventContent, StateEventType},
serde::{Incoming, Raw}, serde::{Incoming, Raw},
OwnedRoomId, RoomId, RoomId,
}; };
ruma_api! { ruma_api! {
@ -142,6 +142,8 @@ pub mod v3 {
B: AsRef<[u8]>, B: AsRef<[u8]>,
S: AsRef<str>, S: AsRef<str>,
{ {
use ruma_common::OwnedRoomId;
// FIXME: find a way to make this if-else collapse with serde recognizing trailing // FIXME: find a way to make this if-else collapse with serde recognizing trailing
// Option // Option
let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) = let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) =

View File

@ -9,7 +9,7 @@ pub mod v3 {
api::ruma_api, api::ruma_api,
events::{AnyStateEventContent, StateEventContent, StateEventType}, events::{AnyStateEventContent, StateEventContent, StateEventType},
serde::{Incoming, Raw}, serde::{Incoming, Raw},
EventId, OwnedRoomId, RoomId, EventId, RoomId,
}; };
use serde_json::value::to_raw_value as to_raw_json_value; use serde_json::value::to_raw_value as to_raw_json_value;
@ -172,6 +172,8 @@ pub mod v3 {
B: AsRef<[u8]>, B: AsRef<[u8]>,
S: AsRef<str>, S: AsRef<str>,
{ {
use ruma_common::OwnedRoomId;
// FIXME: find a way to make this if-else collapse with serde recognizing trailing // FIXME: find a way to make this if-else collapse with serde recognizing trailing
// Option // Option
let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) = let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) =

View File

@ -8,8 +8,8 @@ use super::{
Redact, Redact,
}; };
use crate::{ use crate::{
serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, OwnedRoomId, RoomId,
TransactionId, UserId, RoomVersionId, TransactionId, UserId,
}; };
event_enum! { event_enum! {
@ -191,7 +191,7 @@ impl AnySyncRoomEvent {
} }
/// Converts `self` to an `AnyRoomEvent` by adding the given a room ID. /// Converts `self` to an `AnyRoomEvent` by adding the given a room ID.
pub fn into_full_event(self, room_id: Box<RoomId>) -> AnyRoomEvent { pub fn into_full_event(self, room_id: OwnedRoomId) -> AnyRoomEvent {
match self { match self {
Self::MessageLike(ev) => AnyRoomEvent::MessageLike(ev.into_full_event(room_id)), Self::MessageLike(ev) => AnyRoomEvent::MessageLike(ev.into_full_event(room_id)),
Self::State(ev) => AnyRoomEvent::State(ev.into_full_event(room_id)), Self::State(ev) => AnyRoomEvent::State(ev.into_full_event(room_id)),

View File

@ -15,7 +15,7 @@ use super::{
EncryptedFile, ImageInfo, JsonWebKey, MediaSource, EncryptedFile, ImageInfo, JsonWebKey, MediaSource,
}, },
}; };
use crate::{serde::Base64, MxcUri}; use crate::{serde::Base64, OwnedMxcUri};
/// The payload for an extensible file message. /// The payload for an extensible file message.
/// ///
@ -52,7 +52,7 @@ impl FileEventContent {
/// file info. /// file info.
pub fn plain( pub fn plain(
message: impl Into<String>, message: impl Into<String>,
url: Box<MxcUri>, url: OwnedMxcUri,
info: Option<Box<FileContentInfo>>, info: Option<Box<FileContentInfo>>,
) -> Self { ) -> Self {
Self { Self {
@ -66,7 +66,7 @@ impl FileEventContent {
/// file info. /// file info.
pub fn plain_message( pub fn plain_message(
message: MessageContent, message: MessageContent,
url: Box<MxcUri>, url: OwnedMxcUri,
info: Option<Box<FileContentInfo>>, info: Option<Box<FileContentInfo>>,
) -> Self { ) -> Self {
Self { message, file: FileContent::plain(url, info), relates_to: None } Self { message, file: FileContent::plain(url, info), relates_to: None }
@ -76,7 +76,7 @@ impl FileEventContent {
/// encryption info and file info. /// encryption info and file info.
pub fn encrypted( pub fn encrypted(
message: impl Into<String>, message: impl Into<String>,
url: Box<MxcUri>, url: OwnedMxcUri,
encryption_info: EncryptedContent, encryption_info: EncryptedContent,
info: Option<Box<FileContentInfo>>, info: Option<Box<FileContentInfo>>,
) -> Self { ) -> Self {
@ -91,7 +91,7 @@ impl FileEventContent {
/// encryption info and file info. /// encryption info and file info.
pub fn encrypted_message( pub fn encrypted_message(
message: MessageContent, message: MessageContent,
url: Box<MxcUri>, url: OwnedMxcUri,
encryption_info: EncryptedContent, encryption_info: EncryptedContent,
info: Option<Box<FileContentInfo>>, info: Option<Box<FileContentInfo>>,
) -> Self { ) -> Self {
@ -120,7 +120,7 @@ impl FileEventContent {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct FileContent { pub struct FileContent {
/// The URL to the file. /// The URL to the file.
pub url: Box<MxcUri>, pub url: OwnedMxcUri,
/// Information about the uploaded file. /// Information about the uploaded file.
#[serde(flatten, skip_serializing_if = "Option::is_none")] #[serde(flatten, skip_serializing_if = "Option::is_none")]
@ -135,13 +135,13 @@ pub struct FileContent {
impl FileContent { impl FileContent {
/// Creates a new non-encrypted `FileContent` with the given url and file info. /// Creates a new non-encrypted `FileContent` with the given url and file info.
pub fn plain(url: Box<MxcUri>, info: Option<Box<FileContentInfo>>) -> Self { pub fn plain(url: OwnedMxcUri, info: Option<Box<FileContentInfo>>) -> Self {
Self { url, info, encryption_info: None } Self { url, info, encryption_info: None }
} }
/// Creates a new encrypted `FileContent` with the given url, encryption info and file info. /// Creates a new encrypted `FileContent` with the given url, encryption info and file info.
pub fn encrypted( pub fn encrypted(
url: Box<MxcUri>, url: OwnedMxcUri,
encryption_info: EncryptedContent, encryption_info: EncryptedContent,
info: Option<Box<FileContentInfo>>, info: Option<Box<FileContentInfo>>,
) -> Self { ) -> Self {
@ -156,7 +156,7 @@ impl FileContent {
) -> Self { ) -> Self {
let (url, encryption_info) = match source { let (url, encryption_info) = match source {
MediaSource::Plain(url) => (url, None), MediaSource::Plain(url) => (url, None),
MediaSource::Encrypted(file) => (file.url.to_owned(), Some(Box::new((&*file).into()))), MediaSource::Encrypted(file) => (file.url.clone(), Some(Box::new((&*file).into()))),
}; };
let info = FileContentInfo::from_room_message_content(info, filename).map(Box::new); let info = FileContentInfo::from_room_message_content(info, filename).map(Box::new);

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::UserId; use crate::OwnedUserId;
/// The content of an `m.ignored_user_list` event. /// The content of an `m.ignored_user_list` event.
/// ///
@ -16,12 +16,12 @@ use crate::UserId;
pub struct IgnoredUserListEventContent { pub struct IgnoredUserListEventContent {
/// A list of users to ignore. /// A list of users to ignore.
#[serde(with = "crate::serde::vec_as_map_of_empty")] #[serde(with = "crate::serde::vec_as_map_of_empty")]
pub ignored_users: Vec<Box<UserId>>, pub ignored_users: Vec<OwnedUserId>,
} }
impl IgnoredUserListEventContent { impl IgnoredUserListEventContent {
/// Creates a new `IgnoredUserListEventContent` from the given user IDs. /// Creates a new `IgnoredUserListEventContent` from the given user IDs.
pub fn new(ignored_users: Vec<Box<UserId>>) -> Self { pub fn new(ignored_users: Vec<OwnedUserId>) -> Self {
Self { ignored_users } Self { ignored_users }
} }
} }

View File

@ -14,7 +14,7 @@ use super::{
ImageInfo, MediaSource, ThumbnailInfo, ImageInfo, MediaSource, ThumbnailInfo,
}, },
}; };
use crate::MxcUri; use crate::OwnedMxcUri;
/// The payload for an extensible image message. /// The payload for an extensible image message.
/// ///
@ -213,7 +213,7 @@ impl ThumbnailContent {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ThumbnailFileContent { pub struct ThumbnailFileContent {
/// The URL to the thumbnail. /// The URL to the thumbnail.
pub url: Box<MxcUri>, pub url: OwnedMxcUri,
/// Information about the uploaded thumbnail. /// Information about the uploaded thumbnail.
#[serde(flatten, skip_serializing_if = "Option::is_none")] #[serde(flatten, skip_serializing_if = "Option::is_none")]
@ -228,14 +228,14 @@ pub struct ThumbnailFileContent {
impl ThumbnailFileContent { impl ThumbnailFileContent {
/// Creates a new non-encrypted `ThumbnailFileContent` with the given url and file info. /// Creates a new non-encrypted `ThumbnailFileContent` with the given url and file info.
pub fn plain(url: Box<MxcUri>, info: Option<Box<ThumbnailFileContentInfo>>) -> Self { pub fn plain(url: OwnedMxcUri, info: Option<Box<ThumbnailFileContentInfo>>) -> Self {
Self { url, info, encryption_info: None } Self { url, info, encryption_info: None }
} }
/// Creates a new encrypted `ThumbnailFileContent` with the given url, encryption info and /// Creates a new encrypted `ThumbnailFileContent` with the given url, encryption info and
/// thumbnail file info. /// thumbnail file info.
pub fn encrypted( pub fn encrypted(
url: Box<MxcUri>, url: OwnedMxcUri,
encryption_info: EncryptedContent, encryption_info: EncryptedContent,
info: Option<Box<ThumbnailFileContentInfo>>, info: Option<Box<ThumbnailFileContentInfo>>,
) -> Self { ) -> Self {

View File

@ -9,7 +9,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{serde::StringEnum, EventId, PrivOwnedStr}; use crate::{serde::StringEnum, OwnedEventId, PrivOwnedStr};
pub mod accept; pub mod accept;
pub mod cancel; pub mod cancel;
@ -124,12 +124,12 @@ impl ShortAuthenticationString {
#[serde(tag = "rel_type", rename = "m.reference")] #[serde(tag = "rel_type", rename = "m.reference")]
pub struct Relation { pub struct Relation {
/// The event ID of a related `m.key.verification.request`. /// The event ID of a related `m.key.verification.request`.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
} }
impl Relation { impl Relation {
/// Creates a new `Relation` with the given event ID. /// Creates a new `Relation` with the given event ID.
pub fn new(event_id: Box<EventId>) -> Self { pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id } Self { event_id }
} }
} }

View File

@ -13,7 +13,8 @@ use super::{
StateUnsigned, ToDeviceEventContent, StateUnsigned, ToDeviceEventContent,
}; };
use crate::{ use crate::{
serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UserId, serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId,
OwnedUserId, RoomId, RoomVersionId, UserId,
}; };
/// A global account data event. /// A global account data event.
@ -37,7 +38,7 @@ pub struct EphemeralRoomEvent<C: EphemeralRoomEventContent> {
pub content: C, pub content: C,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
} }
/// An ephemeral room event without a `room_id`. /// An ephemeral room event without a `room_id`.
@ -57,16 +58,16 @@ pub struct OriginalMessageLikeEvent<C: MessageLikeEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: MessageLikeUnsigned, pub unsigned: MessageLikeUnsigned,
@ -82,10 +83,10 @@ pub struct OriginalSyncMessageLikeEvent<C: MessageLikeEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -104,16 +105,16 @@ pub struct RedactedMessageLikeEvent<C: RedactedMessageLikeEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: RedactedUnsigned, pub unsigned: RedactedUnsigned,
@ -129,10 +130,10 @@ pub struct RedactedSyncMessageLikeEvent<C: RedactedMessageLikeEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -187,16 +188,16 @@ pub struct OriginalStateEvent<C: StateEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// A unique key which defines the overwriting semantics for this piece of room state. /// A unique key which defines the overwriting semantics for this piece of room state.
/// ///
@ -218,10 +219,10 @@ pub struct OriginalSyncStateEvent<C: StateEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -243,7 +244,7 @@ pub struct StrippedStateEvent<C: StateEventContent> {
pub content: C, pub content: C,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// A unique key which defines the overwriting semantics for this piece of room state. /// A unique key which defines the overwriting semantics for this piece of room state.
/// ///
@ -278,16 +279,16 @@ pub struct RedactedStateEvent<C: RedactedStateEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// A unique key which defines the overwriting semantics for this piece of room state. /// A unique key which defines the overwriting semantics for this piece of room state.
/// ///
@ -309,10 +310,10 @@ pub struct RedactedSyncStateEvent<C: RedactedStateEventContent> {
pub content: C, pub content: C,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -370,7 +371,7 @@ pub struct ToDeviceEvent<C: ToDeviceEventContent> {
pub content: C, pub content: C,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
} }
/// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event. /// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event.
@ -380,10 +381,10 @@ pub struct DecryptedOlmV1Event<C: MessageLikeEventContent> {
pub content: C, pub content: C,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// The fully-qualified ID of the intended recipient this event. /// The fully-qualified ID of the intended recipient this event.
pub recipient: Box<UserId>, pub recipient: OwnedUserId,
/// The recipient's ed25519 key. /// The recipient's ed25519 key.
pub recipient_keys: OlmV1Keys, pub recipient_keys: OlmV1Keys,
@ -406,7 +407,7 @@ pub struct DecryptedMegolmV1Event<C: MessageLikeEventContent> {
pub content: C, pub content: C,
/// The ID of the room associated with the event. /// The ID of the room associated with the event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
} }
macro_rules! impl_possibly_redacted_event { macro_rules! impl_possibly_redacted_event {
@ -517,7 +518,7 @@ impl_possibly_redacted_event!(SyncMessageLikeEvent(MessageLikeEventContent, Mess
} }
/// Convert this sync event into a full event (one with a `room_id` field). /// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: Box<RoomId>) -> MessageLikeEvent<C> { pub fn into_full_event(self, room_id: OwnedRoomId) -> MessageLikeEvent<C> {
match self { match self {
Self::Original(ev) => MessageLikeEvent::Original(ev.into_full_event(room_id)), Self::Original(ev) => MessageLikeEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => MessageLikeEvent::Redacted(ev.into_full_event(room_id)), Self::Redacted(ev) => MessageLikeEvent::Redacted(ev.into_full_event(room_id)),
@ -569,7 +570,7 @@ impl_possibly_redacted_event!(SyncStateEvent(StateEventContent, StateEventType)
} }
/// Convert this sync event into a full event (one with a `room_id` field). /// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: Box<RoomId>) -> StateEvent<C> { pub fn into_full_event(self, room_id: OwnedRoomId) -> StateEvent<C> {
match self { match self {
Self::Original(ev) => StateEvent::Original(ev.into_full_event(room_id)), Self::Original(ev) => StateEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => StateEvent::Redacted(ev.into_full_event(room_id)), Self::Redacted(ev) => StateEvent::Redacted(ev.into_full_event(room_id)),

View File

@ -2,7 +2,7 @@
//! //!
//! The differences between the `RoomV1Pdu` schema and the `RoomV3Pdu` schema are that the //! The differences between the `RoomV1Pdu` schema and the `RoomV3Pdu` schema are that the
//! `RoomV1Pdu` takes an `event_id` field (`RoomV3Pdu` does not), and `auth_events` and //! `RoomV1Pdu` takes an `event_id` field (`RoomV3Pdu` does not), and `auth_events` and
//! `prev_events` take `Vec<(Box<EventId>, EventHash)> rather than `Vec<Box<EventId>>` in //! `prev_events` take `Vec<(OwnedEventId, EventHash)> rather than `Vec<OwnedEventId>` in
//! `RoomV3Pdu`. //! `RoomV3Pdu`.
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -15,7 +15,10 @@ use serde::{
use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue}; use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue};
use super::RoomEventType; use super::RoomEventType;
use crate::{EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId, UserId}; use crate::{
MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedServerSigningKeyId, OwnedUserId,
};
/// Enum for PDU schemas /// Enum for PDU schemas
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug, Serialize)]
@ -34,13 +37,13 @@ pub enum Pdu {
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct RoomV1Pdu { pub struct RoomV1Pdu {
/// Event ID for the PDU. /// Event ID for the PDU.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The room this event belongs to. /// The room this event belongs to.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// The user id of the user who sent this event. /// The user id of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver
/// of when this event was created. /// of when this event was created.
@ -61,7 +64,7 @@ pub struct RoomV1Pdu {
/// Event IDs for the most recent events in the room that the homeserver was /// Event IDs for the most recent events in the room that the homeserver was
/// aware of when it created this event. /// aware of when it created this event.
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
pub prev_events: Vec<(Box<EventId>, EventHash)>, pub prev_events: Vec<(OwnedEventId, EventHash)>,
/// The maximum depth of the `prev_events`, plus one. /// The maximum depth of the `prev_events`, plus one.
pub depth: UInt, pub depth: UInt,
@ -69,11 +72,11 @@ pub struct RoomV1Pdu {
/// Event IDs for the authorization events that would allow this event to be /// Event IDs for the authorization events that would allow this event to be
/// in the room. /// in the room.
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
pub auth_events: Vec<(Box<EventId>, EventHash)>, pub auth_events: Vec<(OwnedEventId, EventHash)>,
/// For redaction events, the ID of the event being redacted. /// For redaction events, the ID of the event being redacted.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<Box<EventId>>, pub redacts: Option<OwnedEventId>,
/// Additional data added by the origin server but not covered by the /// Additional data added by the origin server but not covered by the
/// signatures. /// signatures.
@ -84,7 +87,7 @@ pub struct RoomV1Pdu {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, String>>, pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
} }
/// A 'persistent data unit' (event) for room versions 3 and beyond. /// A 'persistent data unit' (event) for room versions 3 and beyond.
@ -92,10 +95,10 @@ pub struct RoomV1Pdu {
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct RoomV3Pdu { pub struct RoomV3Pdu {
/// The room this event belongs to. /// The room this event belongs to.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// The user id of the user who sent this event. /// The user id of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver
/// of when this event was created. /// of when this event was created.
@ -115,18 +118,18 @@ pub struct RoomV3Pdu {
/// Event IDs for the most recent events in the room that the homeserver was /// Event IDs for the most recent events in the room that the homeserver was
/// aware of when it created this event. /// aware of when it created this event.
pub prev_events: Vec<Box<EventId>>, pub prev_events: Vec<OwnedEventId>,
/// The maximum depth of the `prev_events`, plus one. /// The maximum depth of the `prev_events`, plus one.
pub depth: UInt, pub depth: UInt,
/// Event IDs for the authorization events that would allow this event to be /// Event IDs for the authorization events that would allow this event to be
/// in the room. /// in the room.
pub auth_events: Vec<Box<EventId>>, pub auth_events: Vec<OwnedEventId>,
/// For redaction events, the ID of the event being redacted. /// For redaction events, the ID of the event being redacted.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<Box<EventId>>, pub redacts: Option<OwnedEventId>,
/// Additional data added by the origin server but not covered by the /// Additional data added by the origin server but not covered by the
/// signatures. /// signatures.
@ -137,7 +140,7 @@ pub struct RoomV3Pdu {
pub hashes: EventHash, pub hashes: EventHash,
/// Signatures for the PDU. /// Signatures for the PDU.
pub signatures: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, String>>, pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
} }
/// Content hashes of a PDU. /// Content hashes of a PDU.

View File

@ -7,7 +7,7 @@ use ruma_macros::{Event, EventContent};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::{EventKind, StaticEventContent}; use super::{EventKind, StaticEventContent};
use crate::{presence::PresenceState, MxcUri, UserId}; use crate::{presence::PresenceState, OwnedMxcUri, OwnedUserId};
/// Presence event. /// Presence event.
#[derive(Clone, Debug, Event)] #[derive(Clone, Debug, Event)]
@ -17,7 +17,7 @@ pub struct PresenceEvent {
pub content: PresenceEventContent, pub content: PresenceEventContent,
/// Contains the fully-qualified ID of the user who sent this event. /// Contains the fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
} }
/// Informs the room of members presence. /// Informs the room of members presence.
@ -36,7 +36,7 @@ pub struct PresenceEventContent {
feature = "compat", feature = "compat",
serde(default, deserialize_with = "crate::serde::empty_string_as_none") serde(default, deserialize_with = "crate::serde::empty_string_as_none")
)] )]
pub avatar_url: Option<Box<MxcUri>>, pub avatar_url: Option<OwnedMxcUri>,
/// Whether or not the user is currently active. /// Whether or not the user is currently active.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]

View File

@ -10,7 +10,9 @@ use std::{
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{receipt::ReceiptType, EventId, MilliSecondsSinceUnixEpoch, UserId}; use crate::{
receipt::ReceiptType, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedUserId, UserId,
};
/// The content of an `m.receipt` event. /// The content of an `m.receipt` event.
/// ///
@ -21,7 +23,7 @@ use crate::{receipt::ReceiptType, EventId, MilliSecondsSinceUnixEpoch, UserId};
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)] #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
#[ruma_event(type = "m.receipt", kind = EphemeralRoom)] #[ruma_event(type = "m.receipt", kind = EphemeralRoom)]
pub struct ReceiptEventContent(pub BTreeMap<Box<EventId>, Receipts>); pub struct ReceiptEventContent(pub BTreeMap<OwnedEventId, Receipts>);
impl ReceiptEventContent { impl ReceiptEventContent {
/// Get the receipt for the given user ID with the given receipt type, if it exists. /// Get the receipt for the given user ID with the given receipt type, if it exists.
@ -38,7 +40,7 @@ impl ReceiptEventContent {
} }
impl Deref for ReceiptEventContent { impl Deref for ReceiptEventContent {
type Target = BTreeMap<Box<EventId>, Receipts>; type Target = BTreeMap<OwnedEventId, Receipts>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.0 &self.0
@ -57,7 +59,7 @@ pub type Receipts = BTreeMap<ReceiptType, UserReceipts>;
/// A mapping of user ID to receipt. /// A mapping of user ID to receipt.
/// ///
/// The user ID is the entity who sent this receipt. /// The user ID is the entity who sent this receipt.
pub type UserReceipts = BTreeMap<Box<UserId>, Receipt>; pub type UserReceipts = BTreeMap<OwnedUserId, Receipt>;
/// An acknowledgement of an event. /// An acknowledgement of an event.
#[derive(Clone, Debug, Default, Deserialize, Serialize)] #[derive(Clone, Debug, Default, Deserialize, Serialize)]

View File

@ -14,9 +14,11 @@ use super::{
file::FileContentInfo, file::FileContentInfo,
image::{ImageContent, ThumbnailContent, ThumbnailFileContent, ThumbnailFileContentInfo}, image::{ImageContent, ThumbnailContent, ThumbnailFileContent, ThumbnailFileContentInfo},
}; };
#[cfg(feature = "unstable-msc3551")]
use crate::MxcUri;
use crate::{ use crate::{
serde::{base64::UrlSafe, Base64}, serde::{base64::UrlSafe, Base64},
MxcUri, OwnedMxcUri,
}; };
pub mod aliases; pub mod aliases;
@ -46,7 +48,7 @@ pub mod topic;
pub enum MediaSource { pub enum MediaSource {
/// The MXC URI to the unencrypted media file. /// The MXC URI to the unencrypted media file.
#[serde(rename = "url")] #[serde(rename = "url")]
Plain(Box<MxcUri>), Plain(OwnedMxcUri),
/// The encryption info of the encrypted media file. /// The encryption info of the encrypted media file.
#[serde(rename = "file")] #[serde(rename = "file")]
@ -64,7 +66,7 @@ impl<'de> Deserialize<'de> for MediaSource {
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct MediaSourceJsonRepr { pub struct MediaSourceJsonRepr {
url: Option<Box<MxcUri>>, url: Option<OwnedMxcUri>,
file: Option<Box<EncryptedFile>>, file: Option<Box<EncryptedFile>>,
} }
@ -243,7 +245,7 @@ impl ThumbnailInfo {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct EncryptedFile { pub struct EncryptedFile {
/// The URL to the file. /// The URL to the file.
pub url: Box<MxcUri>, pub url: OwnedMxcUri,
/// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object. /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
pub key: JsonWebKey, pub key: JsonWebKey,
@ -279,7 +281,7 @@ impl EncryptedFile {
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct EncryptedFileInit { pub struct EncryptedFileInit {
/// The URL to the file. /// The URL to the file.
pub url: Box<MxcUri>, pub url: OwnedMxcUri,
/// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object. /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
pub key: JsonWebKey, pub key: JsonWebKey,
@ -384,7 +386,7 @@ mod tests {
use serde::Deserialize; use serde::Deserialize;
use serde_json::{from_value as from_json_value, json}; use serde_json::{from_value as from_json_value, json};
use crate::serde::Base64; use crate::{mxc_uri, serde::Base64};
use super::{EncryptedFile, JsonWebKey, MediaSource}; use super::{EncryptedFile, JsonWebKey, MediaSource};
@ -408,7 +410,7 @@ mod tests {
fn encrypted_file() -> EncryptedFile { fn encrypted_file() -> EncryptedFile {
EncryptedFile { EncryptedFile {
url: "mxc://localhost/encrypted_file".into(), url: mxc_uri!("mxc://localhost/encryptedfile").to_owned(),
key: dummy_jwt(), key: dummy_jwt(),
iv: Base64::new(vec![0; 64]), iv: Base64::new(vec![0; 64]),
hashes: BTreeMap::new(), hashes: BTreeMap::new(),

View File

@ -8,7 +8,7 @@ use crate::{
events::{ events::{
EventContent, HasDeserializeFields, RedactContent, RedactedEventContent, StateEventType, EventContent, HasDeserializeFields, RedactContent, RedactedEventContent, StateEventType,
}, },
RoomAliasId, RoomVersionId, OwnedRoomAliasId, RoomVersionId,
}; };
/// The content of an `m.room.aliases` event. /// The content of an `m.room.aliases` event.
@ -19,12 +19,12 @@ use crate::{
#[ruma_event(type = "m.room.aliases", kind = State, custom_redacted)] #[ruma_event(type = "m.room.aliases", kind = State, custom_redacted)]
pub struct RoomAliasesEventContent { pub struct RoomAliasesEventContent {
/// A list of room aliases. /// A list of room aliases.
pub aliases: Vec<Box<RoomAliasId>>, pub aliases: Vec<OwnedRoomAliasId>,
} }
impl RoomAliasesEventContent { impl RoomAliasesEventContent {
/// Create an `RoomAliasesEventContent` from the given aliases. /// Create an `RoomAliasesEventContent` from the given aliases.
pub fn new(aliases: Vec<Box<RoomAliasId>>) -> Self { pub fn new(aliases: Vec<OwnedRoomAliasId>) -> Self {
Self { aliases } Self { aliases }
} }
} }
@ -56,14 +56,14 @@ pub struct RedactedRoomAliasesEventContent {
/// ///
/// According to the Matrix spec version 1 redaction rules allowed this field to be /// According to the Matrix spec version 1 redaction rules allowed this field to be
/// kept after redaction, this was changed in version 6. /// kept after redaction, this was changed in version 6.
pub aliases: Option<Vec<Box<RoomAliasId>>>, pub aliases: Option<Vec<OwnedRoomAliasId>>,
} }
impl RedactedRoomAliasesEventContent { impl RedactedRoomAliasesEventContent {
/// Create a `RedactedAliasesEventContent` with the given aliases. /// Create a `RedactedAliasesEventContent` with the given aliases.
/// ///
/// This is only valid for room version 5 and below. /// This is only valid for room version 5 and below.
pub fn new_v1(aliases: Vec<Box<RoomAliasId>>) -> Self { pub fn new_v1(aliases: Vec<OwnedRoomAliasId>) -> Self {
Self { aliases: Some(aliases) } Self { aliases: Some(aliases) }
} }

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::RoomAliasId; use crate::{OwnedRoomAliasId, RoomAliasId};
/// The content of an `m.room.canonical_alias` event. /// The content of an `m.room.canonical_alias` event.
/// ///
@ -23,7 +23,7 @@ pub struct RoomCanonicalAliasEventContent {
deserialize_with = "crate::serde::empty_string_as_none", deserialize_with = "crate::serde::empty_string_as_none",
skip_serializing_if = "Option::is_none" skip_serializing_if = "Option::is_none"
)] )]
pub alias: Option<Box<RoomAliasId>>, pub alias: Option<OwnedRoomAliasId>,
/// List of alternative aliases to the room. /// List of alternative aliases to the room.
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{room::RoomType, EventId, RoomId, RoomVersionId, UserId}; use crate::{room::RoomType, EventId, OwnedUserId, RoomId, RoomVersionId};
/// The content of an `m.room.create` event. /// The content of an `m.room.create` event.
/// ///
@ -20,7 +20,7 @@ pub struct RoomCreateEventContent {
/// ///
/// This is set by the homeserver. /// This is set by the homeserver.
#[ruma_event(skip_redaction)] #[ruma_event(skip_redaction)]
pub creator: Box<UserId>, pub creator: OwnedUserId,
/// Whether or not this room's data should be transferred to other homeservers. /// Whether or not this room's data should be transferred to other homeservers.
#[serde( #[serde(
@ -49,7 +49,7 @@ pub struct RoomCreateEventContent {
impl RoomCreateEventContent { impl RoomCreateEventContent {
/// Creates a new `RoomCreateEventContent` with the given creator. /// Creates a new `RoomCreateEventContent` with the given creator.
pub fn new(creator: Box<UserId>) -> Self { pub fn new(creator: OwnedUserId) -> Self {
Self { Self {
creator, creator,
federate: true, federate: true,

View File

@ -9,7 +9,9 @@ use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::message::{self, InReplyTo}; use super::message::{self, InReplyTo};
use crate::{DeviceId, EventId}; #[cfg(feature = "unstable-msc2677")]
use crate::EventId;
use crate::{DeviceId, OwnedEventId};
mod relation_serde; mod relation_serde;
@ -138,7 +140,7 @@ impl From<message::Relation> for Relation {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Replacement { pub struct Replacement {
/// The ID of the event being replacing. /// The ID of the event being replacing.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
} }
/// A reference to another event. /// A reference to another event.
@ -146,12 +148,12 @@ pub struct Replacement {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Reference { pub struct Reference {
/// The event we are referencing. /// The event we are referencing.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
} }
impl Reference { impl Reference {
/// Creates a new `Reference` with the given event ID. /// Creates a new `Reference` with the given event ID.
pub fn new(event_id: Box<EventId>) -> Self { pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id } Self { event_id }
} }
} }
@ -182,7 +184,7 @@ impl Annotation {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Thread { pub struct Thread {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// A reply relation. /// A reply relation.
/// ///
@ -203,13 +205,13 @@ pub struct Thread {
impl Thread { impl Thread {
/// Convenience method to create a regular `Thread` with the given event ID and latest /// Convenience method to create a regular `Thread` with the given event ID and latest
/// message-like event ID. /// message-like event ID.
pub fn plain(event_id: Box<EventId>, latest_event_id: Box<EventId>) -> Self { pub fn plain(event_id: OwnedEventId, latest_event_id: OwnedEventId) -> Self {
Self { event_id, in_reply_to: InReplyTo::new(latest_event_id), is_falling_back: false } Self { event_id, in_reply_to: InReplyTo::new(latest_event_id), is_falling_back: false }
} }
/// Convenience method to create a reply `Thread` with the given event ID and replied-to event /// Convenience method to create a reply `Thread` with the given event ID and replied-to event
/// ID. /// ID.
pub fn reply(event_id: Box<EventId>, reply_to_event_id: Box<EventId>) -> Self { pub fn reply(event_id: OwnedEventId, reply_to_event_id: OwnedEventId) -> Self {
Self { event_id, in_reply_to: InReplyTo::new(reply_to_event_id), is_falling_back: true } Self { event_id, in_reply_to: InReplyTo::new(reply_to_event_id), is_falling_back: true }
} }
} }

View File

@ -8,7 +8,7 @@ use super::Replacement;
use super::Thread; use super::Thread;
use super::{InReplyTo, Reference, Relation}; use super::{InReplyTo, Reference, Relation};
#[cfg(feature = "unstable-msc3440")] #[cfg(feature = "unstable-msc3440")]
use crate::EventId; use crate::OwnedEventId;
impl<'de> Deserialize<'de> for Relation { impl<'de> Deserialize<'de> for Relation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
@ -126,7 +126,7 @@ impl RelatesToJsonRepr {
#[cfg(feature = "unstable-msc3440")] #[cfg(feature = "unstable-msc3440")]
struct ThreadStableJsonRepr { struct ThreadStableJsonRepr {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a
/// thread. /// thread.
@ -139,7 +139,7 @@ struct ThreadStableJsonRepr {
#[cfg(feature = "unstable-msc3440")] #[cfg(feature = "unstable-msc3440")]
struct ThreadUnstableJsonRepr { struct ThreadUnstableJsonRepr {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a
/// thread. /// thread.

View File

@ -11,7 +11,7 @@ use serde::{
}; };
use serde_json::{value::RawValue as RawJsonValue, Value as JsonValue}; use serde_json::{value::RawValue as RawJsonValue, Value as JsonValue};
use crate::{serde::from_raw_json_value, PrivOwnedStr, RoomId}; use crate::{serde::from_raw_json_value, OwnedRoomId, PrivOwnedStr};
/// The content of an `m.room.join_rules` event. /// The content of an `m.room.join_rules` event.
/// ///
@ -179,7 +179,7 @@ pub enum AllowRule {
impl AllowRule { impl AllowRule {
/// Constructs an `AllowRule` with membership of the room with the given id as its predicate. /// Constructs an `AllowRule` with membership of the room with the given id as its predicate.
pub fn room_membership(room_id: Box<RoomId>) -> Self { pub fn room_membership(room_id: OwnedRoomId) -> Self {
Self::RoomMembership(RoomMembership::new(room_id)) Self::RoomMembership(RoomMembership::new(room_id))
} }
} }
@ -189,12 +189,12 @@ impl AllowRule {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomMembership { pub struct RoomMembership {
/// The id of the room which being a member of grants permission to join another room. /// The id of the room which being a member of grants permission to join another room.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
} }
impl RoomMembership { impl RoomMembership {
/// Constructs a new room membership rule for the given room id. /// Constructs a new room membership rule for the given room id.
pub fn new(room_id: Box<RoomId>) -> Self { pub fn new(room_id: OwnedRoomId) -> Self {
Self { room_id } Self { room_id }
} }
} }

View File

@ -14,7 +14,8 @@ use crate::{
RedactedEventContent, StateEventType, StrippedStateEvent, RedactedEventContent, StateEventType, StrippedStateEvent,
}, },
serde::StringEnum, serde::StringEnum,
MxcUri, PrivOwnedStr, RoomVersionId, ServerName, ServerSigningKeyId, UserId, MxcUri, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, PrivOwnedStr, RoomVersionId,
UserId,
}; };
/// The content of an `m.room.member` event. /// The content of an `m.room.member` event.
@ -99,7 +100,7 @@ pub struct RoomMemberEventContent {
/// Arbitrarily chosen `UserId` (MxID) of a local user who can send an invite. /// Arbitrarily chosen `UserId` (MxID) of a local user who can send an invite.
#[serde(rename = "join_authorised_via_users_server")] #[serde(rename = "join_authorised_via_users_server")]
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub join_authorized_via_users_server: Option<Box<UserId>>, pub join_authorized_via_users_server: Option<OwnedUserId>,
} }
impl RoomMemberEventContent { impl RoomMemberEventContent {
@ -145,7 +146,7 @@ pub struct RedactedRoomMemberEventContent {
/// This is redacted in room versions 8 and below. It is used for validating /// This is redacted in room versions 8 and below. It is used for validating
/// joins when the join rule is restricted. /// joins when the join rule is restricted.
#[serde(rename = "join_authorised_via_users_server")] #[serde(rename = "join_authorised_via_users_server")]
pub join_authorized_via_users_server: Option<Box<UserId>>, pub join_authorized_via_users_server: Option<OwnedUserId>,
} }
impl RedactedRoomMemberEventContent { impl RedactedRoomMemberEventContent {
@ -251,7 +252,7 @@ pub struct SignedContent {
/// A single signature from the verifying server, in the format specified by the Signing Events /// A single signature from the verifying server, in the format specified by the Signing Events
/// section of the server-server API. /// section of the server-server API.
pub signatures: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, String>>, pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
/// The token property of the containing `third_party_invite` object. /// The token property of the containing `third_party_invite` object.
pub token: String, pub token: String,
@ -261,7 +262,7 @@ impl SignedContent {
/// Creates a new `SignedContent` with the given mxid, signature and token. /// Creates a new `SignedContent` with the given mxid, signature and token.
pub fn new( pub fn new(
mxid: Box<UserId>, mxid: Box<UserId>,
signatures: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, String>>, signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>,
token: String, token: String,
) -> Self { ) -> Self {
Self { mxid, signatures, token } Self { mxid, signatures, token }

View File

@ -29,7 +29,7 @@ use crate::events::{
use crate::{ use crate::{
events::key::verification::VerificationMethod, events::key::verification::VerificationMethod,
serde::{JsonObject, StringEnum}, serde::{JsonObject, StringEnum},
DeviceId, EventId, MxcUri, PrivOwnedStr, UserId, DeviceId, OwnedEventId, OwnedMxcUri, OwnedUserId, PrivOwnedStr,
}; };
#[cfg(feature = "unstable-msc3488")] #[cfg(feature = "unstable-msc3488")]
use crate::{ use crate::{
@ -634,12 +634,12 @@ pub enum Relation {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct InReplyTo { pub struct InReplyTo {
/// The event being replied to. /// The event being replied to.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
} }
impl InReplyTo { impl InReplyTo {
/// Creates a new `InReplyTo` with the given event ID. /// Creates a new `InReplyTo` with the given event ID.
pub fn new(event_id: Box<EventId>) -> Self { pub fn new(event_id: OwnedEventId) -> Self {
Self { event_id } Self { event_id }
} }
} }
@ -650,7 +650,7 @@ impl InReplyTo {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Replacement { pub struct Replacement {
/// The ID of the event being replaced. /// The ID of the event being replaced.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// New content. /// New content.
pub new_content: Box<RoomMessageEventContent>, pub new_content: Box<RoomMessageEventContent>,
@ -659,7 +659,7 @@ pub struct Replacement {
#[cfg(feature = "unstable-msc2676")] #[cfg(feature = "unstable-msc2676")]
impl Replacement { impl Replacement {
/// Creates a new `Replacement` with the given event ID and new content. /// Creates a new `Replacement` with the given event ID and new content.
pub fn new(event_id: Box<EventId>, new_content: Box<RoomMessageEventContent>) -> Self { pub fn new(event_id: OwnedEventId, new_content: Box<RoomMessageEventContent>) -> Self {
Self { event_id, new_content } Self { event_id, new_content }
} }
} }
@ -670,7 +670,7 @@ impl Replacement {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Thread { pub struct Thread {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// A reply relation. /// A reply relation.
/// ///
@ -691,13 +691,13 @@ pub struct Thread {
impl Thread { impl Thread {
/// Convenience method to create a regular `Thread` with the given event ID and latest /// Convenience method to create a regular `Thread` with the given event ID and latest
/// message-like event ID. /// message-like event ID.
pub fn plain(event_id: Box<EventId>, latest_event_id: Box<EventId>) -> Self { pub fn plain(event_id: OwnedEventId, latest_event_id: OwnedEventId) -> Self {
Self { event_id, in_reply_to: InReplyTo::new(latest_event_id), is_falling_back: true } Self { event_id, in_reply_to: InReplyTo::new(latest_event_id), is_falling_back: true }
} }
/// Convenience method to create a reply `Thread` with the given event ID and replied-to event /// Convenience method to create a reply `Thread` with the given event ID and replied-to event
/// ID. /// ID.
pub fn reply(event_id: Box<EventId>, reply_to_event_id: Box<EventId>) -> Self { pub fn reply(event_id: OwnedEventId, reply_to_event_id: OwnedEventId) -> Self {
Self { event_id, in_reply_to: InReplyTo::new(reply_to_event_id), is_falling_back: false } Self { event_id, in_reply_to: InReplyTo::new(reply_to_event_id), is_falling_back: false }
} }
} }
@ -761,7 +761,7 @@ pub struct AudioMessageEventContent {
impl AudioMessageEventContent { impl AudioMessageEventContent {
/// Creates a new non-encrypted `AudioMessageEventContent` with the given body, url and /// Creates a new non-encrypted `AudioMessageEventContent` with the given body, url and
/// optional extra info. /// optional extra info.
pub fn plain(body: String, url: Box<MxcUri>, info: Option<Box<AudioInfo>>) -> Self { pub fn plain(body: String, url: OwnedMxcUri, info: Option<Box<AudioInfo>>) -> Self {
Self { Self {
#[cfg(feature = "unstable-msc3246")] #[cfg(feature = "unstable-msc3246")]
message: Some(MessageContent::plain(body.clone())), message: Some(MessageContent::plain(body.clone())),
@ -1008,7 +1008,7 @@ pub struct FileMessageEventContent {
impl FileMessageEventContent { impl FileMessageEventContent {
/// Creates a new non-encrypted `FileMessageEventContent` with the given body, url and /// Creates a new non-encrypted `FileMessageEventContent` with the given body, url and
/// optional extra info. /// optional extra info.
pub fn plain(body: String, url: Box<MxcUri>, info: Option<Box<FileInfo>>) -> Self { pub fn plain(body: String, url: OwnedMxcUri, info: Option<Box<FileInfo>>) -> Self {
Self { Self {
#[cfg(feature = "unstable-msc3551")] #[cfg(feature = "unstable-msc3551")]
message: Some(MessageContent::plain(body.clone())), message: Some(MessageContent::plain(body.clone())),
@ -1165,7 +1165,7 @@ pub struct ImageMessageEventContent {
impl ImageMessageEventContent { impl ImageMessageEventContent {
/// Creates a new non-encrypted `ImageMessageEventContent` with the given body, url and /// Creates a new non-encrypted `ImageMessageEventContent` with the given body, url and
/// optional extra info. /// optional extra info.
pub fn plain(body: String, url: Box<MxcUri>, info: Option<Box<ImageInfo>>) -> Self { pub fn plain(body: String, url: OwnedMxcUri, info: Option<Box<ImageInfo>>) -> Self {
Self { Self {
#[cfg(feature = "unstable-msc3552")] #[cfg(feature = "unstable-msc3552")]
message: Some(MessageContent::plain(body.clone())), message: Some(MessageContent::plain(body.clone())),
@ -1714,7 +1714,7 @@ pub struct VideoMessageEventContent {
impl VideoMessageEventContent { impl VideoMessageEventContent {
/// Creates a new non-encrypted `VideoMessageEventContent` with the given body, url and /// Creates a new non-encrypted `VideoMessageEventContent` with the given body, url and
/// optional extra info. /// optional extra info.
pub fn plain(body: String, url: Box<MxcUri>, info: Option<Box<VideoInfo>>) -> Self { pub fn plain(body: String, url: OwnedMxcUri, info: Option<Box<VideoInfo>>) -> Self {
Self { Self {
#[cfg(feature = "unstable-msc3553")] #[cfg(feature = "unstable-msc3553")]
message: Some(MessageContent::plain(body.clone())), message: Some(MessageContent::plain(body.clone())),
@ -1913,7 +1913,7 @@ pub struct KeyVerificationRequestEventContent {
/// Users should only respond to verification requests if they are named in this field. Users /// Users should only respond to verification requests if they are named in this field. Users
/// who are not named in this field and who did not send this event should ignore all other /// who are not named in this field and who did not send this event should ignore all other
/// events that have a `m.reference` relationship with this event. /// events that have a `m.reference` relationship with this event.
pub to: Box<UserId>, pub to: OwnedUserId,
} }
impl KeyVerificationRequestEventContent { impl KeyVerificationRequestEventContent {
@ -1923,7 +1923,7 @@ impl KeyVerificationRequestEventContent {
body: String, body: String,
methods: Vec<VerificationMethod>, methods: Vec<VerificationMethod>,
from_device: Box<DeviceId>, from_device: Box<DeviceId>,
to: Box<UserId>, to: OwnedUserId,
) -> Self { ) -> Self {
Self { body, methods, from_device, to } Self { body, methods, from_device, to }
} }

View File

@ -8,7 +8,7 @@ use super::RoomMessageEventContent;
use super::Thread; use super::Thread;
use super::{InReplyTo, Relation}; use super::{InReplyTo, Relation};
#[cfg(any(feature = "unstable-msc2676", feature = "unstable-msc3440"))] #[cfg(any(feature = "unstable-msc2676", feature = "unstable-msc3440"))]
use crate::EventId; use crate::OwnedEventId;
impl<'de> Deserialize<'de> for Relation { impl<'de> Deserialize<'de> for Relation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
@ -165,7 +165,7 @@ enum RelationJsonRepr {
#[derive(Clone, Deserialize, Serialize)] #[derive(Clone, Deserialize, Serialize)]
#[cfg(feature = "unstable-msc2676")] #[cfg(feature = "unstable-msc2676")]
struct ReplacementJsonRepr { struct ReplacementJsonRepr {
event_id: Box<EventId>, event_id: OwnedEventId,
} }
/// A thread relation without the reply fallback, with stable names. /// A thread relation without the reply fallback, with stable names.
@ -173,7 +173,7 @@ struct ReplacementJsonRepr {
#[cfg(feature = "unstable-msc3440")] #[cfg(feature = "unstable-msc3440")]
struct ThreadStableJsonRepr { struct ThreadStableJsonRepr {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
event_id: Box<EventId>, event_id: OwnedEventId,
/// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a
/// thread. /// thread.
@ -186,7 +186,7 @@ struct ThreadStableJsonRepr {
#[cfg(feature = "unstable-msc3440")] #[cfg(feature = "unstable-msc3440")]
struct ThreadUnstableJsonRepr { struct ThreadUnstableJsonRepr {
/// The ID of the root message in the thread. /// The ID of the root message in the thread.
event_id: Box<EventId>, event_id: OwnedEventId,
/// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a
/// thread. /// thread.

View File

@ -45,10 +45,10 @@ mod tests {
let event = OriginalStateEvent { let event = OriginalStateEvent {
content: content.clone(), content: content.clone(),
event_id: EventId::new(server_name), event_id: EventId::new(server_name).into(),
origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_804_485_886_u64.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_804_485_886_u64.try_into().unwrap()),
room_id: RoomId::new(server_name), room_id: RoomId::new(server_name).into(),
sender: UserId::new(server_name), sender: UserId::new(server_name).into(),
state_key: "".into(), state_key: "".into(),
unsigned: StateUnsigned::default(), unsigned: StateUnsigned::default(),
}; };

View File

@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
use crate::{ use crate::{
events::RoomEventType, events::RoomEventType,
power_levels::{default_power_level, NotificationPowerLevels}, power_levels::{default_power_level, NotificationPowerLevels},
UserId, OwnedUserId, UserId,
}; };
/// The content of an `m.room.power_levels` event. /// The content of an `m.room.power_levels` event.
@ -118,7 +118,7 @@ pub struct RoomPowerLevelsEventContent {
)] )]
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
#[ruma_event(skip_redaction)] #[ruma_event(skip_redaction)]
pub users: BTreeMap<Box<UserId>, Int>, pub users: BTreeMap<OwnedUserId, Int>,
/// The default power level for every user in the room. /// The default power level for every user in the room.
/// ///
@ -227,7 +227,7 @@ pub struct RoomPowerLevels {
/// The power levels for specific users. /// The power levels for specific users.
/// ///
/// This is a mapping from `user_id` to power level for that user. /// This is a mapping from `user_id` to power level for that user.
pub users: BTreeMap<Box<UserId>, Int>, pub users: BTreeMap<OwnedUserId, Int>,
/// The default power level for every user in the room. /// The default power level for every user in the room.
pub users_default: Int, pub users_default: Int,

View File

@ -12,7 +12,7 @@ use crate::{
RedactedUnsigned, RedactionDeHelper, RedactedUnsigned, RedactionDeHelper,
}, },
serde::from_raw_json_value, serde::from_raw_json_value,
EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId,
}; };
/// A possibly-redacted redaction event. /// A possibly-redacted redaction event.
@ -47,19 +47,19 @@ pub struct OriginalRoomRedactionEvent {
pub content: RoomRedactionEventContent, pub content: RoomRedactionEventContent,
/// The ID of the event that was redacted. /// The ID of the event that was redacted.
pub redacts: Box<EventId>, pub redacts: OwnedEventId,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: MessageLikeUnsigned, pub unsigned: MessageLikeUnsigned,
@ -92,16 +92,16 @@ pub struct RedactedRoomRedactionEvent {
pub content: RedactedRoomRedactionEventContent, pub content: RedactedRoomRedactionEventContent,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event. /// The ID of the room associated with this event.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: RedactedUnsigned, pub unsigned: RedactedUnsigned,
@ -115,13 +115,13 @@ pub struct OriginalSyncRoomRedactionEvent {
pub content: RoomRedactionEventContent, pub content: RoomRedactionEventContent,
/// The ID of the event that was redacted. /// The ID of the event that was redacted.
pub redacts: Box<EventId>, pub redacts: OwnedEventId,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -156,10 +156,10 @@ pub struct RedactedSyncRoomRedactionEvent {
pub content: RedactedRoomRedactionEventContent, pub content: RedactedRoomRedactionEventContent,
/// The globally unique event identifier for the user who sent the event. /// The globally unique event identifier for the user who sent the event.
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent. /// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
@ -309,7 +309,7 @@ impl SyncRoomRedactionEvent {
} }
/// Convert this sync event into a full event (one with a `room_id` field). /// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event(self, room_id: Box<RoomId>) -> RoomRedactionEvent { pub fn into_full_event(self, room_id: OwnedRoomId) -> RoomRedactionEvent {
match self { match self {
Self::Original(ev) => RoomRedactionEvent::Original(ev.into_full_event(room_id)), Self::Original(ev) => RoomRedactionEvent::Original(ev.into_full_event(room_id)),
Self::Redacted(ev) => RoomRedactionEvent::Redacted(ev.into_full_event(room_id)), Self::Redacted(ev) => RoomRedactionEvent::Redacted(ev.into_full_event(room_id)),

View File

@ -5,7 +5,7 @@ use serde::{
Deserialize, Deserializer, Deserialize, Deserializer,
}; };
use crate::MxcUri; use crate::OwnedMxcUri;
use super::{EncryptedFile, MediaSource}; use super::{EncryptedFile, MediaSource};
@ -33,7 +33,7 @@ where
{ {
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct ThumbnailSourceJsonRepr { pub struct ThumbnailSourceJsonRepr {
thumbnail_url: Option<Box<MxcUri>>, thumbnail_url: Option<OwnedMxcUri>,
thumbnail_file: Option<Box<EncryptedFile>>, thumbnail_file: Option<Box<EncryptedFile>>,
} }

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{EventEncryptionAlgorithm, RoomId}; use crate::{EventEncryptionAlgorithm, OwnedRoomId};
/// The content of an `m.room_key` event. /// The content of an `m.room_key` event.
/// ///
@ -20,7 +20,7 @@ pub struct ToDeviceRoomKeyEventContent {
pub algorithm: EventEncryptionAlgorithm, pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used. /// The room where the key is used.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// The ID of the session that the key is for. /// The ID of the session that the key is for.
pub session_id: String, pub session_id: String,
@ -34,7 +34,7 @@ impl ToDeviceRoomKeyEventContent {
/// and session key. /// and session key.
pub fn new( pub fn new(
algorithm: EventEncryptionAlgorithm, algorithm: EventEncryptionAlgorithm,
room_id: Box<RoomId>, room_id: OwnedRoomId,
session_id: String, session_id: String,
session_key: String, session_key: String,
) -> Self { ) -> Self {

View File

@ -5,7 +5,7 @@
use ruma_macros::{Event, EventContent}; use ruma_macros::{Event, EventContent};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{MilliSecondsSinceUnixEpoch, ServerName, UserId}; use crate::{MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedUserId};
/// The content of an `m.space.child` event. /// The content of an `m.space.child` event.
/// ///
@ -20,7 +20,7 @@ use crate::{MilliSecondsSinceUnixEpoch, ServerName, UserId};
pub struct SpaceChildEventContent { pub struct SpaceChildEventContent {
/// List of candidate servers that can be used to join the room. /// List of candidate servers that can be used to join the room.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub via: Option<Vec<Box<ServerName>>>, pub via: Option<Vec<OwnedServerName>>,
/// Provide a default ordering of siblings in the room list. /// Provide a default ordering of siblings in the room list.
/// ///
@ -60,7 +60,7 @@ pub struct HierarchySpaceChildEvent {
pub content: SpaceChildEventContent, pub content: SpaceChildEventContent,
/// The fully-qualified ID of the user who sent this event. /// The fully-qualified ID of the user who sent this event.
pub sender: Box<UserId>, pub sender: OwnedUserId,
/// The room ID of the child. /// The room ID of the child.
pub state_key: String, pub state_key: String,

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::ServerName; use crate::OwnedServerName;
/// The content of an `m.space.parent` event. /// The content of an `m.space.parent` event.
/// ///
@ -20,7 +20,7 @@ use crate::ServerName;
pub struct SpaceParentEventContent { pub struct SpaceParentEventContent {
/// List of candidate servers that can be used to join the room. /// List of candidate servers that can be used to join the room.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub via: Option<Vec<Box<ServerName>>>, pub via: Option<Vec<OwnedServerName>>,
/// Determines whether this is the main parent for the space. /// Determines whether this is the main parent for the space.
/// ///

View File

@ -11,7 +11,7 @@ use super::{
image::{ImageContent, ThumbnailContent}, image::{ImageContent, ThumbnailContent},
message::MessageContent, message::MessageContent,
}; };
use crate::{events::room::ImageInfo, MxcUri}; use crate::{events::room::ImageInfo, OwnedMxcUri};
/// The content of an `m.sticker` event. /// The content of an `m.sticker` event.
/// ///
@ -35,7 +35,7 @@ pub struct StickerEventContent {
pub info: ImageInfo, pub info: ImageInfo,
/// The URL to the sticker image. /// The URL to the sticker image.
pub url: Box<MxcUri>, pub url: OwnedMxcUri,
/// Extensible-event text representation of the message. /// Extensible-event text representation of the message.
/// ///
@ -91,7 +91,7 @@ pub struct StickerEventContent {
impl StickerEventContent { impl StickerEventContent {
/// Creates a new `StickerEventContent` with the given body, image info and URL. /// Creates a new `StickerEventContent` with the given body, image info and URL.
pub fn new(body: String, info: ImageInfo, url: Box<MxcUri>) -> Self { pub fn new(body: String, info: ImageInfo, url: OwnedMxcUri) -> Self {
Self { Self {
#[cfg(feature = "unstable-msc3552")] #[cfg(feature = "unstable-msc3552")]
message: Some(MessageContent::plain(body.clone())), message: Some(MessageContent::plain(body.clone())),

View File

@ -5,7 +5,7 @@
use ruma_macros::EventContent; use ruma_macros::EventContent;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::UserId; use crate::OwnedUserId;
/// The content of an `m.typing` event. /// The content of an `m.typing` event.
/// ///
@ -15,12 +15,12 @@ use crate::UserId;
#[ruma_event(type = "m.typing", kind = EphemeralRoom)] #[ruma_event(type = "m.typing", kind = EphemeralRoom)]
pub struct TypingEventContent { pub struct TypingEventContent {
/// The list of user IDs typing in this room, if any. /// The list of user IDs typing in this room, if any.
pub user_ids: Vec<Box<UserId>>, pub user_ids: Vec<OwnedUserId>,
} }
impl TypingEventContent { impl TypingEventContent {
/// Creates a new `TypingEventContent` with the given user IDs. /// Creates a new `TypingEventContent` with the given user IDs.
pub fn new(user_ids: Vec<Box<UserId>>) -> Self { pub fn new(user_ids: Vec<OwnedUserId>) -> Self {
Self { user_ids } Self { user_ids }
} }
} }

View File

@ -63,7 +63,7 @@ mod tests {
#[test] #[test]
fn create_device_id_from_box() { fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into(); let box_str: Box<str> = "ijklmnop".into();
let device_id: Box<DeviceId> = DeviceId::from_box(box_str); let device_id: Box<DeviceId> = box_str.into();
assert_eq!(device_id.as_str(), "ijklmnop"); assert_eq!(device_id.as_str(), "ijklmnop");
} }
} }

View File

@ -9,7 +9,7 @@ use ruma_identifiers_validation::{
}; };
use url::Url; use url::Url;
use super::{EventId, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UserId}; use super::{EventId, OwnedServerName, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UserId};
use crate::PrivOwnedStr; use crate::PrivOwnedStr;
const MATRIX_TO_BASE_URL: &str = "https://matrix.to/#/"; const MATRIX_TO_BASE_URL: &str = "https://matrix.to/#/";
@ -239,7 +239,7 @@ impl From<(&RoomAliasId, &EventId)> for MatrixId {
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub struct MatrixToUri { pub struct MatrixToUri {
id: MatrixId, id: MatrixId,
via: Vec<Box<ServerName>>, via: Vec<OwnedServerName>,
} }
impl MatrixToUri { impl MatrixToUri {
@ -253,7 +253,7 @@ impl MatrixToUri {
} }
/// Matrix servers usable to route a `RoomId`. /// Matrix servers usable to route a `RoomId`.
pub fn via(&self) -> &[Box<ServerName>] { pub fn via(&self) -> &[OwnedServerName] {
&self.via &self.via
} }
@ -272,7 +272,7 @@ impl MatrixToUri {
for (key, value) in url.query_pairs() { for (key, value) in url.query_pairs() {
if key.as_ref() == "via" { if key.as_ref() == "via" {
via.push(ServerName::parse(value)?); via.push(value.parse()?);
} else { } else {
return Err(MatrixToError::UnknownArgument.into()); return Err(MatrixToError::UnknownArgument.into());
} }
@ -399,7 +399,7 @@ impl From<Box<str>> for UriAction {
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub struct MatrixUri { pub struct MatrixUri {
id: MatrixId, id: MatrixId,
via: Vec<Box<ServerName>>, via: Vec<OwnedServerName>,
action: Option<UriAction>, action: Option<UriAction>,
} }
@ -414,7 +414,7 @@ impl MatrixUri {
} }
/// Matrix servers usable to route a `RoomId`. /// Matrix servers usable to route a `RoomId`.
pub fn via(&self) -> &[Box<ServerName>] { pub fn via(&self) -> &[OwnedServerName] {
&self.via &self.via
} }
@ -438,7 +438,7 @@ impl MatrixUri {
for (key, value) in url.query_pairs() { for (key, value) in url.query_pairs() {
if key.as_ref() == "via" { if key.as_ref() == "via" {
via.push(ServerName::parse(value)?); via.push(value.parse()?);
} else if key.as_ref() == "action" { } else if key.as_ref() == "action" {
if action.is_some() { if action.is_some() {
return Err(MatrixUriError::TooManyActions.into()); return Err(MatrixUriError::TooManyActions.into());

View File

@ -6,7 +6,7 @@ use serde_json::{to_value as to_json_value, value::Value as JsonValue};
use tracing::{instrument, warn}; use tracing::{instrument, warn};
use wildmatch::WildMatch; use wildmatch::WildMatch;
use crate::{power_levels::NotificationPowerLevels, serde::Raw, RoomId, UserId}; use crate::{power_levels::NotificationPowerLevels, serde::Raw, OwnedRoomId, OwnedUserId, UserId};
mod room_member_count_is; mod room_member_count_is;
@ -114,7 +114,7 @@ impl PushCondition {
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct PushConditionRoomCtx { pub struct PushConditionRoomCtx {
/// The ID of the room. /// The ID of the room.
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
/// The number of members in the room. /// The number of members in the room.
pub member_count: UInt, pub member_count: UInt,
@ -123,7 +123,7 @@ pub struct PushConditionRoomCtx {
pub user_display_name: String, pub user_display_name: String,
/// The power levels of the users of the room. /// The power levels of the users of the room.
pub users_power_levels: BTreeMap<Box<UserId>, Int>, pub users_power_levels: BTreeMap<OwnedUserId, Int>,
/// The default power level of the users of the room. /// The default power level of the users of the room.
pub default_power_level: Int, pub default_power_level: Int,

View File

@ -5,7 +5,7 @@ use ruma_common::{
ruma_api, IncomingRequest as _, MatrixVersion, OutgoingRequest as _, ruma_api, IncomingRequest as _, MatrixVersion, OutgoingRequest as _,
OutgoingRequestAppserviceExt, SendAccessToken, OutgoingRequestAppserviceExt, SendAccessToken,
}, },
user_id, UserId, user_id, OwnedUserId,
}; };
ruma_api! { ruma_api! {
@ -29,7 +29,7 @@ ruma_api! {
#[ruma_api(path)] #[ruma_api(path)]
pub bar: String, pub bar: String,
#[ruma_api(path)] #[ruma_api(path)]
pub user: Box<UserId>, pub user: OwnedUserId,
} }
response: { response: {
@ -119,9 +119,9 @@ fn request_with_user_id_serde() {
} }
mod without_query { mod without_query {
use ruma_common::api::MatrixVersion; use ruma_common::{api::MatrixVersion, OwnedUserId};
use super::{ruma_api, user_id, OutgoingRequestAppserviceExt, SendAccessToken, UserId}; use super::{ruma_api, user_id, OutgoingRequestAppserviceExt, SendAccessToken};
ruma_api! { ruma_api! {
metadata: { metadata: {
@ -140,7 +140,7 @@ mod without_query {
#[ruma_api(path)] #[ruma_api(path)]
pub bar: String, pub bar: String,
#[ruma_api(path)] #[ruma_api(path)]
pub user: Box<UserId>, pub user: OwnedUserId,
} }
response: { response: {

View File

@ -5,7 +5,7 @@ extern crate serde;
use ruma_common::{ use ruma_common::{
events::{StateEventContent, StateUnsigned}, events::{StateEventContent, StateUnsigned},
EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId,
}; };
use ruma_macros::Event; use ruma_macros::Event;
@ -13,10 +13,10 @@ use ruma_macros::Event;
#[derive(Clone, Debug, Event)] #[derive(Clone, Debug, Event)]
pub struct OriginalStateEvent<C: StateEventContent> { pub struct OriginalStateEvent<C: StateEventContent> {
pub content: C, pub content: C,
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
pub sender: Box<UserId>, pub sender: OwnedUserId,
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
pub state_key: String, pub state_key: String,
pub unsigned: StateUnsigned<C>, pub unsigned: StateUnsigned<C>,
} }

View File

@ -49,14 +49,14 @@ mod string {
} }
mod user { mod user {
use ruma_common::{user_id, UserId}; use ruma_common::{user_id, OwnedUserId, UserId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
const CARL: &str = "@carl:example.com"; const CARL: &str = "@carl:example.com";
fn carl() -> Box<UserId> { fn carl() -> &'static UserId {
user_id!("@carl:example.com").to_owned() user_id!("@carl:example.com")
} }
#[derive(Serialize, Deserialize, PartialEq, Debug)] #[derive(Serialize, Deserialize, PartialEq, Debug)]
@ -66,7 +66,7 @@ mod user {
deserialize_with = "ruma_common::serde::empty_string_as_none", deserialize_with = "ruma_common::serde::empty_string_as_none",
serialize_with = "ruma_common::serde::none_as_empty_string" serialize_with = "ruma_common::serde::none_as_empty_string"
)] )]
x: Option<Box<UserId>>, x: Option<OwnedUserId>,
} }
#[test] #[test]
@ -78,7 +78,7 @@ mod user {
#[test] #[test]
fn some_se() { fn some_se() {
let decoded = User { x: Some(carl()) }; let decoded = User { x: Some(carl().to_owned()) };
let encoded = json!({ "x": CARL }); let encoded = json!({ "x": CARL });
assert_eq!(to_json_value(decoded).unwrap(), encoded); assert_eq!(to_json_value(decoded).unwrap(), encoded);
} }
@ -100,7 +100,7 @@ mod user {
#[test] #[test]
fn some_de() { fn some_de() {
let encoded = json!({ "x": CARL }); let encoded = json!({ "x": CARL });
let decoded = User { x: Some(carl()) }; let decoded = User { x: Some(carl().to_owned()) };
assert_eq!(from_json_value::<User>(encoded).unwrap(), decoded); assert_eq!(from_json_value::<User>(encoded).unwrap(), decoded);
} }
} }

View File

@ -1,6 +1,6 @@
use std::{collections::BTreeMap, fmt}; use std::{collections::BTreeMap, fmt};
use ruma_common::EventId; use ruma_common::OwnedEventId;
use serde::{ use serde::{
de::{Deserializer, MapAccess, Visitor}, de::{Deserializer, MapAccess, Visitor},
ser::{SerializeMap, Serializer}, ser::{SerializeMap, Serializer},
@ -14,7 +14,7 @@ struct WrappedError {
} }
pub fn serialize<S>( pub fn serialize<S>(
response: &BTreeMap<Box<EventId>, Result<(), String>>, response: &BTreeMap<OwnedEventId, Result<(), String>>,
serializer: S, serializer: S,
) -> Result<S::Ok, S::Error> ) -> Result<S::Ok, S::Error>
where where
@ -36,14 +36,14 @@ where
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub fn deserialize<'de, D>( pub fn deserialize<'de, D>(
deserializer: D, deserializer: D,
) -> Result<BTreeMap<Box<EventId>, Result<(), String>>, D::Error> ) -> Result<BTreeMap<OwnedEventId, Result<(), String>>, D::Error>
where where
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
struct PduProcessResponseVisitor; struct PduProcessResponseVisitor;
impl<'de> Visitor<'de> for PduProcessResponseVisitor { impl<'de> Visitor<'de> for PduProcessResponseVisitor {
type Value = BTreeMap<Box<EventId>, Result<(), String>>; type Value = BTreeMap<OwnedEventId, Result<(), String>>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("A map of EventIds to a map of optional errors") formatter.write_str("A map of EventIds to a map of optional errors")
@ -55,7 +55,7 @@ where
{ {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry::<Box<EventId>, WrappedError>()? { while let Some((key, value)) = access.next_entry::<OwnedEventId, WrappedError>()? {
let v = match value.error { let v = match value.error {
None => Ok(()), None => Ok(()),
Some(error) => Err(error), Some(error) => Err(error),
@ -73,14 +73,14 @@ where
mod tests { mod tests {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma_common::{event_id, EventId}; use ruma_common::{event_id, OwnedEventId};
use serde_json::{json, value::Serializer as JsonSerializer}; use serde_json::{json, value::Serializer as JsonSerializer};
use super::{deserialize, serialize}; use super::{deserialize, serialize};
#[test] #[test]
fn serialize_error() { fn serialize_error() {
let mut response: BTreeMap<Box<EventId>, Result<(), String>> = BTreeMap::new(); let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new();
response.insert( response.insert(
event_id!("$someevent:matrix.org").to_owned(), event_id!("$someevent:matrix.org").to_owned(),
Err("Some processing error.".into()), Err("Some processing error.".into()),
@ -95,7 +95,7 @@ mod tests {
#[test] #[test]
fn serialize_ok() { fn serialize_ok() {
let mut response: BTreeMap<Box<EventId>, Result<(), String>> = BTreeMap::new(); let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new();
response.insert(event_id!("$someevent:matrix.org").to_owned(), Ok(())); response.insert(event_id!("$someevent:matrix.org").to_owned(), Ok(()));
let serialized = serialize(&response, serde_json::value::Serializer).unwrap(); let serialized = serialize(&response, serde_json::value::Serializer).unwrap();

View File

@ -10,7 +10,8 @@ pub mod v1 {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma_common::{ use ruma_common::{
api::ruma_api, serde::Raw, EventId, MilliSecondsSinceUnixEpoch, ServerName, TransactionId, api::ruma_api, serde::Raw, MilliSecondsSinceUnixEpoch, OwnedEventId, ServerName,
TransactionId,
}; };
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
@ -63,7 +64,7 @@ pub mod v1 {
/// See [MSC3618](https://github.com/matrix-org/matrix-spec-proposals/pull/3618). /// See [MSC3618](https://github.com/matrix-org/matrix-spec-proposals/pull/3618).
#[cfg_attr(feature = "unstable-msc3618", serde(default))] #[cfg_attr(feature = "unstable-msc3618", serde(default))]
#[serde(with = "crate::serde::pdu_process_response")] #[serde(with = "crate::serde::pdu_process_response")]
pub pdus: BTreeMap<Box<EventId>, Result<(), String>>, pub pdus: BTreeMap<OwnedEventId, Result<(), String>>,
} }
} }
@ -82,7 +83,7 @@ pub mod v1 {
impl Response { impl Response {
/// Creates a new `Response` with the given PDUs. /// Creates a new `Response` with the given PDUs.
pub fn new(pdus: BTreeMap<Box<EventId>, Result<(), String>>) -> Self { pub fn new(pdus: BTreeMap<OwnedEventId, Result<(), String>>) -> Self {
Self { pdus } Self { pdus }
} }
} }

View File

@ -463,7 +463,7 @@ fn expand_sync_from_into_full(
/// Convert this sync event into a full event, one with a room_id field. /// Convert this sync event into a full event, one with a room_id field.
pub fn into_full_event( pub fn into_full_event(
self, self,
room_id: ::std::boxed::Box<#ruma_common::RoomId>, room_id: #ruma_common::OwnedRoomId,
) -> #full_struct #ty_gen { ) -> #full_struct #ty_gen {
let Self { #( #fields, )* } = self; let Self { #( #fields, )* } = self;
#full_struct { #full_struct {

View File

@ -270,10 +270,7 @@ fn expand_into_full_event(
#[automatically_derived] #[automatically_derived]
impl #ident { impl #ident {
/// Convert this sync event into a full event (one with a `room_id` field). /// Convert this sync event into a full event (one with a `room_id` field).
pub fn into_full_event( pub fn into_full_event(self, room_id: #ruma_common::OwnedRoomId) -> #full {
self,
room_id: ::std::boxed::Box<#ruma_common::RoomId>,
) -> #full {
match self { match self {
#( #(
#self_variants(event) => { #self_variants(event) => {

View File

@ -25,6 +25,7 @@ impl Parse for IdentifierInput {
pub fn expand_id_zst(input: ItemStruct) -> syn::Result<TokenStream> { pub fn expand_id_zst(input: ItemStruct) -> syn::Result<TokenStream> {
let id = &input.ident; let id = &input.ident;
let owned = format_ident!("Owned{}", id);
let owned_decl = expand_owned_id(&input); let owned_decl = expand_owned_id(&input);
@ -115,10 +116,10 @@ pub fn expand_id_zst(input: ItemStruct) -> syn::Result<TokenStream> {
} }
impl #impl_generics ToOwned for #id #ty_generics { impl #impl_generics ToOwned for #id #ty_generics {
type Owned = Box<#id #ty_generics>; type Owned = #owned #ty_generics;
fn to_owned(&self) -> Self::Owned { fn to_owned(&self) -> Self::Owned {
Self::from_box(self.as_str().into()) #owned::from_ref(self)
} }
} }
@ -241,6 +242,17 @@ fn expand_owned_id(input: &ItemStruct) -> TokenStream {
inner: std::sync::Arc<#id #ty_generics>, inner: std::sync::Arc<#id #ty_generics>,
} }
impl #impl_generics #owned #ty_generics {
fn from_ref(v: &#id #ty_generics) -> Self {
Self {
#[cfg(not(any(ruma_identifiers_storage = "Arc")))]
inner: #id::from_box(v.as_str().into()),
#[cfg(ruma_identifiers_storage = "Arc")]
inner: #id::from_arc(v.as_str().into()),
}
}
}
impl #impl_generics AsRef<#id #ty_generics> for #owned #ty_generics { impl #impl_generics AsRef<#id #ty_generics> for #owned #ty_generics {
fn as_ref(&self) -> &#id #ty_generics { fn as_ref(&self) -> &#id #ty_generics {
&*self.inner &*self.inner

View File

@ -1,4 +1,6 @@
use ruma_common::{serde::Base64DecodeError, EventId, RoomVersionId, ServerName}; use ruma_common::{
serde::Base64DecodeError, EventId, OwnedEventId, OwnedServerName, RoomVersionId,
};
use thiserror::Error; use thiserror::Error;
/// `ruma-signature`'s error type, wraps a number of other error types. /// `ruma-signature`'s error type, wraps a number of other error types.
@ -144,11 +146,11 @@ pub enum JsonType {
pub enum VerificationError { pub enum VerificationError {
/// For when a signature cannot be found for a `target`. /// For when a signature cannot be found for a `target`.
#[error("Could not find signatures for {0:?}")] #[error("Could not find signatures for {0:?}")]
SignatureNotFound(Box<ServerName>), SignatureNotFound(OwnedServerName),
/// For when a public key cannot be found for a `target`. /// For when a public key cannot be found for a `target`.
#[error("Could not find public key for {0:?}")] #[error("Could not find public key for {0:?}")]
PublicKeyNotFound(Box<ServerName>), PublicKeyNotFound(OwnedServerName),
/// For when no public key matches the signature given. /// For when no public key matches the signature given.
#[error("Not signed with any of the given public keys")] #[error("Not signed with any of the given public keys")]
@ -160,12 +162,12 @@ pub enum VerificationError {
} }
impl VerificationError { impl VerificationError {
pub(crate) fn signature_not_found<T: Into<Box<ServerName>>>(target: T) -> Error { pub(crate) fn signature_not_found(target: OwnedServerName) -> Error {
Self::SignatureNotFound(target.into()).into() Self::SignatureNotFound(target).into()
} }
pub(crate) fn public_key_not_found<T: Into<Box<ServerName>>>(target: T) -> Error { pub(crate) fn public_key_not_found(target: OwnedServerName) -> Error {
Self::PublicKeyNotFound(target.into()).into() Self::PublicKeyNotFound(target).into()
} }
} }
@ -184,7 +186,7 @@ pub enum ParseError {
/// For when an event ID, coupled with a specific room version, doesn't have a server name /// For when an event ID, coupled with a specific room version, doesn't have a server name
/// embedded. /// embedded.
#[error("Event Id {0:?} should have a server name for the given room version {1:?}")] #[error("Event Id {0:?} should have a server name for the given room version {1:?}")]
ServerNameFromEventIdByRoomVersion(Box<EventId>, RoomVersionId), ServerNameFromEventIdByRoomVersion(OwnedEventId, RoomVersionId),
/// For when the extracted/"parsed" public key from a PKCS#8 v2 document doesn't match the /// For when the extracted/"parsed" public key from a PKCS#8 v2 document doesn't match the
/// public key derived from it's private key. /// public key derived from it's private key.

View File

@ -10,7 +10,7 @@ use std::{
use base64::{encode_config, STANDARD_NO_PAD, URL_SAFE_NO_PAD}; use base64::{encode_config, STANDARD_NO_PAD, URL_SAFE_NO_PAD};
use ruma_common::{ use ruma_common::{
serde::{base64::Standard, Base64, CanonicalJsonObject, CanonicalJsonValue}, serde::{base64::Standard, Base64, CanonicalJsonObject, CanonicalJsonValue},
EventId, RoomVersionId, ServerName, UserId, EventId, OwnedServerName, RoomVersionId, UserId,
}; };
use serde_json::{from_str as from_json_str, to_string as to_json_string}; use serde_json::{from_str as from_json_str, to_string as to_json_string};
use sha2::{digest::Digest, Sha256}; use sha2::{digest::Digest, Sha256};
@ -803,7 +803,7 @@ fn object_retain_keys(object: &mut CanonicalJsonObject, keys: &[&str]) {
fn servers_to_check_signatures( fn servers_to_check_signatures(
object: &CanonicalJsonObject, object: &CanonicalJsonObject,
version: &RoomVersionId, version: &RoomVersionId,
) -> Result<BTreeSet<Box<ServerName>>, Error> { ) -> Result<BTreeSet<OwnedServerName>, Error> {
let mut servers_to_check = BTreeSet::new(); let mut servers_to_check = BTreeSet::new();
if !is_third_party_invite(object)? { if !is_third_party_invite(object)? {

View File

@ -30,7 +30,8 @@ use ruma_common::{
}, },
RoomEventType, StateEventType, RoomEventType, StateEventType,
}, },
room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UserId, room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, RoomVersionId,
UserId,
}; };
use ruma_state_res::{self as state_res, Error, Event, Result, StateMap}; use ruma_state_res::{self as state_res, Error, Event, Result, StateMap};
use serde_json::{ use serde_json::{
@ -157,7 +158,7 @@ criterion_main!(benches);
// IMPLEMENTATION DETAILS AHEAD // IMPLEMENTATION DETAILS AHEAD
// //
/////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////*/
struct TestStore<E: Event>(HashMap<Box<EventId>, Arc<E>>); struct TestStore<E: Event>(HashMap<OwnedEventId, Arc<E>>);
#[allow(unused)] #[allow(unused)]
impl<E: Event> TestStore<E> { impl<E: Event> TestStore<E> {
@ -230,7 +231,7 @@ impl TestStore<PduEvent> {
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
fn set_up( fn set_up(
&mut self, &mut self,
) -> (StateMap<Box<EventId>>, StateMap<Box<EventId>>, StateMap<Box<EventId>>) { ) -> (StateMap<OwnedEventId>, StateMap<OwnedEventId>, StateMap<OwnedEventId>) {
let create_event = to_pdu_event::<&EventId>( let create_event = to_pdu_event::<&EventId>(
"CREATE", "CREATE",
alice(), alice(),
@ -314,27 +315,27 @@ impl TestStore<PduEvent> {
} }
} }
fn event_id(id: &str) -> Box<EventId> { fn event_id(id: &str) -> OwnedEventId {
if id.contains('$') { if id.contains('$') {
return id.try_into().unwrap(); return id.try_into().unwrap();
} }
format!("${}:foo", id).try_into().unwrap() format!("${}:foo", id).try_into().unwrap()
} }
fn alice() -> Box<UserId> { fn alice() -> &'static UserId {
user_id!("@alice:foo").to_owned() user_id!("@alice:foo")
} }
fn bob() -> Box<UserId> { fn bob() -> &'static UserId {
user_id!("@bob:foo").to_owned() user_id!("@bob:foo")
} }
fn charlie() -> Box<UserId> { fn charlie() -> &'static UserId {
user_id!("@charlie:foo").to_owned() user_id!("@charlie:foo")
} }
fn ella() -> Box<UserId> { fn ella() -> &'static UserId {
user_id!("@ella:foo").to_owned() user_id!("@ella:foo")
} }
fn room_id() -> &'static RoomId { fn room_id() -> &'static RoomId {
@ -351,7 +352,7 @@ fn member_content_join() -> Box<RawJsonValue> {
fn to_pdu_event<S>( fn to_pdu_event<S>(
id: &str, id: &str,
sender: Box<UserId>, sender: &UserId,
ev_type: RoomEventType, ev_type: RoomEventType,
state_key: Option<&str>, state_key: Option<&str>,
content: Box<RawJsonValue>, content: Box<RawJsonValue>,
@ -373,7 +374,7 @@ where
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id().to_owned(), room_id: room_id().to_owned(),
sender, sender: sender.to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,
kind: ev_type, kind: ev_type,
@ -391,7 +392,7 @@ where
// all graphs start with these input events // all graphs start with these input events
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> { fn INITIAL_EVENTS() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![ vec![
to_pdu_event::<&EventId>( to_pdu_event::<&EventId>(
"CREATE", "CREATE",
@ -406,7 +407,7 @@ fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
"IMA", "IMA",
alice(), alice(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(alice().to_string().as_str()), Some(alice().as_str()),
member_content_join(), member_content_join(),
&["CREATE"], &["CREATE"],
&["CREATE"], &["CREATE"],
@ -416,7 +417,7 @@ fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
alice(), alice(),
RoomEventType::RoomPowerLevels, RoomEventType::RoomPowerLevels,
Some(""), Some(""),
to_raw_json_value(&json!({ "users": { alice().to_string(): 100 } })).unwrap(), to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
&["CREATE", "IMA"], &["CREATE", "IMA"],
&["IMA"], &["IMA"],
), ),
@ -473,7 +474,7 @@ fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
// all graphs start with these input events // all graphs start with these input events
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn BAN_STATE_SET() -> HashMap<Box<EventId>, Arc<PduEvent>> { fn BAN_STATE_SET() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![ vec![
to_pdu_event( to_pdu_event(
"PA", "PA",
@ -531,14 +532,14 @@ impl EventTypeExt for &RoomEventType {
mod event { mod event {
use ruma_common::{ use ruma_common::{
events::{pdu::Pdu, RoomEventType}, events::{pdu::Pdu, RoomEventType},
EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId,
}; };
use ruma_state_res::Event; use ruma_state_res::Event;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
impl Event for PduEvent { impl Event for PduEvent {
type Id = Box<EventId>; type Id = OwnedEventId;
fn event_id(&self) -> &Self::Id { fn event_id(&self) -> &Self::Id {
&self.event_id &self.event_id
@ -628,7 +629,7 @@ mod event {
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PduEvent { pub struct PduEvent {
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
#[serde(flatten)] #[serde(flatten)]
pub rest: Pdu, pub rest: Pdu,
} }

View File

@ -1014,9 +1014,9 @@ mod tests {
assert!(valid_membership_change( assert!(valid_membership_change(
&RoomVersion::V6, &RoomVersion::V6,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
@ -1056,9 +1056,9 @@ mod tests {
assert!(!valid_membership_change( assert!(!valid_membership_change(
&RoomVersion::V6, &RoomVersion::V6,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
@ -1098,9 +1098,9 @@ mod tests {
assert!(valid_membership_change( assert!(valid_membership_change(
&RoomVersion::V6, &RoomVersion::V6,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
@ -1140,9 +1140,9 @@ mod tests {
assert!(!valid_membership_change( assert!(!valid_membership_change(
&RoomVersion::V6, &RoomVersion::V6,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
@ -1176,7 +1176,7 @@ mod tests {
); );
let mut member = RoomMemberEventContent::new(MembershipState::Join); let mut member = RoomMemberEventContent::new(MembershipState::Join);
member.join_authorized_via_users_server = Some(alice()); member.join_authorized_via_users_server = Some(alice().to_owned());
let auth_events = events let auth_events = events
.values() .values()
@ -1199,15 +1199,15 @@ mod tests {
assert!(valid_membership_change( assert!(valid_membership_change(
&RoomVersion::V9, &RoomVersion::V9,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".to_owned()), fetch_state(StateEventType::RoomPowerLevels, "".to_owned()),
fetch_state(StateEventType::RoomJoinRules, "".to_owned()), fetch_state(StateEventType::RoomJoinRules, "".to_owned()),
Some(&alice()), Some(alice()),
&MembershipState::Join, &MembershipState::Join,
fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(), fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(),
) )
@ -1215,15 +1215,15 @@ mod tests {
assert!(!valid_membership_change( assert!(!valid_membership_change(
&RoomVersion::V9, &RoomVersion::V9,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,
fetch_state(StateEventType::RoomPowerLevels, "".to_owned()), fetch_state(StateEventType::RoomPowerLevels, "".to_owned()),
fetch_state(StateEventType::RoomJoinRules, "".to_owned()), fetch_state(StateEventType::RoomJoinRules, "".to_owned()),
Some(&ella()), Some(ella()),
&MembershipState::Leave, &MembershipState::Leave,
fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(), fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(),
) )
@ -1266,9 +1266,9 @@ mod tests {
assert!(valid_membership_change( assert!(valid_membership_change(
&RoomVersion::V7, &RoomVersion::V7,
&target_user, target_user,
fetch_state(StateEventType::RoomMember, target_user.to_string()), fetch_state(StateEventType::RoomMember, target_user.to_string()),
&sender, sender,
fetch_state(StateEventType::RoomMember, sender.to_string()), fetch_state(StateEventType::RoomMember, sender.to_string()),
&requester, &requester,
None::<PduEvent>, None::<PduEvent>,

View File

@ -667,7 +667,7 @@ mod tests {
room::join_rules::{JoinRule, RoomJoinRulesEventContent}, room::join_rules::{JoinRule, RoomJoinRulesEventContent},
RoomEventType, StateEventType, RoomEventType, StateEventType,
}, },
EventId, MilliSecondsSinceUnixEpoch, RoomVersionId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomVersionId,
}; };
use serde_json::{json, value::to_raw_value as to_raw_json_value}; use serde_json::{json, value::to_raw_value as to_raw_json_value};
use tracing::debug; use tracing::debug;
@ -692,7 +692,7 @@ mod tests {
.map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.clone())) .map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.clone()))
.collect::<StateMap<_>>(); .collect::<StateMap<_>>();
let auth_chain: HashSet<Box<EventId>> = HashSet::new(); let auth_chain: HashSet<OwnedEventId> = HashSet::new();
let power_events = event_map let power_events = event_map
.values() .values()
@ -1222,7 +1222,7 @@ mod tests {
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn BAN_STATE_SET() -> HashMap<Box<EventId>, Arc<PduEvent>> { fn BAN_STATE_SET() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![ vec![
to_pdu_event( to_pdu_event(
"PA", "PA",
@ -1267,7 +1267,7 @@ mod tests {
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn JOIN_RULE() -> HashMap<Box<EventId>, Arc<PduEvent>> { fn JOIN_RULE() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![ vec![
to_pdu_event( to_pdu_event(
"JR", "JR",

View File

@ -19,7 +19,8 @@ use ruma_common::{
}, },
RoomEventType, RoomEventType,
}, },
room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UserId, room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, RoomVersionId,
UserId,
}; };
use serde_json::{ use serde_json::{
json, json,
@ -35,8 +36,8 @@ static SERVER_TIMESTAMP: AtomicU64 = AtomicU64::new(0);
pub fn do_check( pub fn do_check(
events: &[Arc<PduEvent>], events: &[Arc<PduEvent>],
edges: Vec<Vec<Box<EventId>>>, edges: Vec<Vec<OwnedEventId>>,
expected_state_ids: Vec<Box<EventId>>, expected_state_ids: Vec<OwnedEventId>,
) { ) {
// To activate logging use `RUST_LOG=debug cargo t` // To activate logging use `RUST_LOG=debug cargo t`
@ -76,10 +77,10 @@ pub fn do_check(
} }
} }
// event_id -> OriginalStateEvent // event_id -> PduEvent
let mut event_map: HashMap<Box<EventId>, Arc<PduEvent>> = HashMap::new(); let mut event_map: HashMap<OwnedEventId, Arc<PduEvent>> = HashMap::new();
// event_id -> StateMap<Box<EventId>> // event_id -> StateMap<OwnedEventId>
let mut state_at_event: HashMap<Box<EventId>, StateMap<Box<EventId>>> = HashMap::new(); let mut state_at_event: HashMap<OwnedEventId, StateMap<OwnedEventId>> = HashMap::new();
// Resolve the current state and add it to the state_at_event map then continue // Resolve the current state and add it to the state_at_event map then continue
// on in "time" // on in "time"
@ -93,7 +94,7 @@ pub fn do_check(
let prev_events = graph.get(&node).unwrap(); let prev_events = graph.get(&node).unwrap();
let state_before: StateMap<Box<EventId>> = if prev_events.is_empty() { let state_before: StateMap<OwnedEventId> = if prev_events.is_empty() {
HashMap::new() HashMap::new()
} else if prev_events.len() == 1 { } else if prev_events.len() == 1 {
state_at_event.get(prev_events.iter().next().unwrap()).unwrap().clone() state_at_event.get(prev_events.iter().next().unwrap()).unwrap().clone()
@ -155,7 +156,7 @@ pub fn do_check(
let ev_id = e.event_id(); let ev_id = e.event_id();
let event = to_pdu_event( let event = to_pdu_event(
e.event_id().as_str(), e.event_id().as_str(),
e.sender().to_owned(), e.sender(),
e.event_type().clone(), e.event_type().clone(),
e.state_key(), e.state_key(),
e.content().to_owned(), e.content().to_owned(),
@ -201,13 +202,13 @@ pub fn do_check(
&& **k != ("m.room.message".into(), "dummy".to_owned()) && **k != ("m.room.message".into(), "dummy".to_owned())
}) })
.map(|(k, v)| (k.clone(), v.clone())) .map(|(k, v)| (k.clone(), v.clone()))
.collect::<StateMap<Box<EventId>>>(); .collect::<StateMap<OwnedEventId>>();
assert_eq!(expected_state, end_state); assert_eq!(expected_state, end_state);
} }
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct TestStore<E: Event>(pub HashMap<Box<EventId>, Arc<E>>); pub struct TestStore<E: Event>(pub HashMap<OwnedEventId, Arc<E>>);
impl<E: Event> TestStore<E> { impl<E: Event> TestStore<E> {
pub fn get_event(&self, _: &RoomId, event_id: &EventId) -> Result<Arc<E>> { pub fn get_event(&self, _: &RoomId, event_id: &EventId) -> Result<Arc<E>> {
@ -248,7 +249,7 @@ impl<E: Event> TestStore<E> {
impl TestStore<PduEvent> { impl TestStore<PduEvent> {
pub fn set_up( pub fn set_up(
&mut self, &mut self,
) -> (StateMap<Box<EventId>>, StateMap<Box<EventId>>, StateMap<Box<EventId>>) { ) -> (StateMap<OwnedEventId>, StateMap<OwnedEventId>, StateMap<OwnedEventId>) {
let create_event = to_pdu_event::<&EventId>( let create_event = to_pdu_event::<&EventId>(
"CREATE", "CREATE",
alice(), alice(),
@ -265,7 +266,7 @@ impl TestStore<PduEvent> {
"IMA", "IMA",
alice(), alice(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(alice().to_string().as_str()), Some(alice().as_str()),
member_content_join(), member_content_join(),
&[cre.clone()], &[cre.clone()],
&[cre.clone()], &[cre.clone()],
@ -289,7 +290,7 @@ impl TestStore<PduEvent> {
"IMB", "IMB",
bob(), bob(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(bob().to_string().as_str()), Some(bob().as_str()),
member_content_join(), member_content_join(),
&[cre.clone(), join_rules.event_id().to_owned()], &[cre.clone(), join_rules.event_id().to_owned()],
&[join_rules.event_id().to_owned()], &[join_rules.event_id().to_owned()],
@ -300,7 +301,7 @@ impl TestStore<PduEvent> {
"IMC", "IMC",
charlie(), charlie(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(charlie().to_string().as_str()), Some(charlie().as_str()),
member_content_join(), member_content_join(),
&[cre, join_rules.event_id().to_owned()], &[cre, join_rules.event_id().to_owned()],
&[join_rules.event_id().to_owned()], &[join_rules.event_id().to_owned()],
@ -332,7 +333,7 @@ impl TestStore<PduEvent> {
} }
} }
pub fn event_id(id: &str) -> Box<EventId> { pub fn event_id(id: &str) -> OwnedEventId {
if id.contains('$') { if id.contains('$') {
return id.try_into().unwrap(); return id.try_into().unwrap();
} }
@ -340,24 +341,24 @@ pub fn event_id(id: &str) -> Box<EventId> {
format!("${}:foo", id).try_into().unwrap() format!("${}:foo", id).try_into().unwrap()
} }
pub fn alice() -> Box<UserId> { pub fn alice() -> &'static UserId {
user_id!("@alice:foo").to_owned() user_id!("@alice:foo")
} }
pub fn bob() -> Box<UserId> { pub fn bob() -> &'static UserId {
user_id!("@bob:foo").to_owned() user_id!("@bob:foo")
} }
pub fn charlie() -> Box<UserId> { pub fn charlie() -> &'static UserId {
user_id!("@charlie:foo").to_owned() user_id!("@charlie:foo")
} }
pub fn ella() -> Box<UserId> { pub fn ella() -> &'static UserId {
user_id!("@ella:foo").to_owned() user_id!("@ella:foo")
} }
pub fn zara() -> Box<UserId> { pub fn zara() -> &'static UserId {
user_id!("@zara:foo").to_owned() user_id!("@zara:foo")
} }
pub fn room_id() -> &'static RoomId { pub fn room_id() -> &'static RoomId {
@ -374,7 +375,7 @@ pub fn member_content_join() -> Box<RawJsonValue> {
pub fn to_init_pdu_event( pub fn to_init_pdu_event(
id: &str, id: &str,
sender: Box<UserId>, sender: &UserId,
ev_type: RoomEventType, ev_type: RoomEventType,
state_key: Option<&str>, state_key: Option<&str>,
content: Box<RawJsonValue>, content: Box<RawJsonValue>,
@ -387,7 +388,7 @@ pub fn to_init_pdu_event(
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id().to_owned(), room_id: room_id().to_owned(),
sender, sender: sender.to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,
kind: ev_type, kind: ev_type,
@ -405,7 +406,7 @@ pub fn to_init_pdu_event(
pub fn to_pdu_event<S>( pub fn to_pdu_event<S>(
id: &str, id: &str,
sender: Box<UserId>, sender: &UserId,
ev_type: RoomEventType, ev_type: RoomEventType,
state_key: Option<&str>, state_key: Option<&str>,
content: Box<RawJsonValue>, content: Box<RawJsonValue>,
@ -425,7 +426,7 @@ where
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id().to_owned(), room_id: room_id().to_owned(),
sender, sender: sender.to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,
kind: ev_type, kind: ev_type,
@ -443,7 +444,7 @@ where
// all graphs start with these input events // all graphs start with these input events
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> { pub fn INITIAL_EVENTS() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![ vec![
to_pdu_event::<&EventId>( to_pdu_event::<&EventId>(
"CREATE", "CREATE",
@ -458,7 +459,7 @@ pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
"IMA", "IMA",
alice(), alice(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(alice().to_string().as_str()), Some(alice().as_str()),
member_content_join(), member_content_join(),
&["CREATE"], &["CREATE"],
&["CREATE"], &["CREATE"],
@ -468,7 +469,7 @@ pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
alice(), alice(),
RoomEventType::RoomPowerLevels, RoomEventType::RoomPowerLevels,
Some(""), Some(""),
to_raw_json_value(&json!({ "users": { alice().to_string(): 100 } })).unwrap(), to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(),
&["CREATE", "IMA"], &["CREATE", "IMA"],
&["IMA"], &["IMA"],
), ),
@ -485,7 +486,7 @@ pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
"IMB", "IMB",
bob(), bob(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(bob().to_string().as_str()), Some(bob().as_str()),
member_content_join(), member_content_join(),
&["CREATE", "IJR", "IPOWER"], &["CREATE", "IJR", "IPOWER"],
&["IJR"], &["IJR"],
@ -494,7 +495,7 @@ pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
"IMC", "IMC",
charlie(), charlie(),
RoomEventType::RoomMember, RoomEventType::RoomMember,
Some(charlie().to_string().as_str()), Some(charlie().as_str()),
member_content_join(), member_content_join(),
&["CREATE", "IJR", "IPOWER"], &["CREATE", "IJR", "IPOWER"],
&["IMB"], &["IMB"],
@ -525,7 +526,7 @@ pub fn INITIAL_EVENTS() -> HashMap<Box<EventId>, Arc<PduEvent>> {
// all graphs start with these input events // all graphs start with these input events
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap<Box<EventId>, Arc<PduEvent>> { pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap<OwnedEventId, Arc<PduEvent>> {
vec![to_pdu_event::<&EventId>( vec![to_pdu_event::<&EventId>(
"CREATE", "CREATE",
alice(), alice(),
@ -541,7 +542,7 @@ pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap<Box<EventId>, Arc<PduEvent>> {
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn INITIAL_EDGES() -> Vec<Box<EventId>> { pub fn INITIAL_EDGES() -> Vec<OwnedEventId> {
vec!["START", "IMC", "IMB", "IJR", "IPOWER", "IMA", "CREATE"] vec!["START", "IMC", "IMB", "IJR", "IPOWER", "IMA", "CREATE"]
.into_iter() .into_iter()
.map(event_id) .map(event_id)
@ -551,7 +552,7 @@ pub fn INITIAL_EDGES() -> Vec<Box<EventId>> {
pub mod event { pub mod event {
use ruma_common::{ use ruma_common::{
events::{pdu::Pdu, RoomEventType}, events::{pdu::Pdu, RoomEventType},
EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
@ -559,7 +560,7 @@ pub mod event {
use crate::Event; use crate::Event;
impl Event for PduEvent { impl Event for PduEvent {
type Id = Box<EventId>; type Id = OwnedEventId;
fn event_id(&self) -> &Self::Id { fn event_id(&self) -> &Self::Id {
&self.event_id &self.event_id
@ -650,7 +651,7 @@ pub mod event {
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
pub struct PduEvent { pub struct PduEvent {
pub event_id: Box<EventId>, pub event_id: OwnedEventId,
#[serde(flatten)] #[serde(flatten)]
pub rest: Pdu, pub rest: Pdu,
} }