diff --git a/crates/ruma-client-api/src/filter.rs b/crates/ruma-client-api/src/filter.rs index ea36201d..0eefcbfe 100644 --- a/crates/ruma-client-api/src/filter.rs +++ b/crates/ruma-client-api/src/filter.rs @@ -9,7 +9,7 @@ mod url; use js_int::UInt; use ruma_common::{ serde::{Incoming, StringEnum}, - RoomId, UserId, + OwnedRoomId, RoomId, UserId, }; 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 /// it is listed in the 'rooms' filter. #[serde(default, skip_serializing_if = "<[_]>::is_empty")] - pub not_rooms: &'a [Box], + pub not_rooms: &'a [OwnedRoomId], /// The maximum number of events to return. #[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. #[serde(skip_serializing_if = "Option::is_none")] - pub rooms: Option<&'a [Box]>, + pub rooms: Option<&'a [OwnedRoomId]>, /// A list of sender IDs to exclude. /// diff --git a/crates/ruma-client-api/src/membership/invite_user.rs b/crates/ruma-client-api/src/membership/invite_user.rs index 532653f5..7bb41b75 100644 --- a/crates/ruma-client-api/src/membership/invite_user.rs +++ b/crates/ruma-client-api/src/membership/invite_user.rs @@ -91,7 +91,7 @@ pub mod v3 { json!({ "user_id": "@carl:example.org" }), ) .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 }; assert_eq!(incoming, recipient); } diff --git a/crates/ruma-client-api/src/room/create_room.rs b/crates/ruma-client-api/src/room/create_room.rs index f332037e..f87d0ded 100644 --- a/crates/ruma-client-api/src/room/create_room.rs +++ b/crates/ruma-client-api/src/room/create_room.rs @@ -17,7 +17,7 @@ pub mod v3 { }, room::RoomType, serde::{Raw, StringEnum}, - RoomId, RoomName, RoomVersionId, UserId, + OwnedUserId, RoomId, RoomName, RoomVersionId, UserId, }; use serde::{Deserialize, Serialize}; @@ -161,7 +161,7 @@ pub mod v3 { /// a `RoomCreateEventContent`. pub fn into_event_content( self, - creator: Box, + creator: OwnedUserId, room_version: RoomVersionId, ) -> RoomCreateEventContent { assign!(RoomCreateEventContent::new(creator), { diff --git a/crates/ruma-client-api/src/state/get_state_events_for_key.rs b/crates/ruma-client-api/src/state/get_state_events_for_key.rs index 5e375271..24d48c77 100644 --- a/crates/ruma-client-api/src/state/get_state_events_for_key.rs +++ b/crates/ruma-client-api/src/state/get_state_events_for_key.rs @@ -9,7 +9,7 @@ pub mod v3 { api::ruma_api, events::{AnyStateEventContent, StateEventType}, serde::{Incoming, Raw}, - OwnedRoomId, RoomId, + RoomId, }; ruma_api! { @@ -142,6 +142,8 @@ pub mod v3 { B: AsRef<[u8]>, S: AsRef, { + use ruma_common::OwnedRoomId; + // FIXME: find a way to make this if-else collapse with serde recognizing trailing // Option let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) = diff --git a/crates/ruma-client-api/src/state/send_state_event.rs b/crates/ruma-client-api/src/state/send_state_event.rs index 35b87ff4..64260b5b 100644 --- a/crates/ruma-client-api/src/state/send_state_event.rs +++ b/crates/ruma-client-api/src/state/send_state_event.rs @@ -9,7 +9,7 @@ pub mod v3 { api::ruma_api, events::{AnyStateEventContent, StateEventContent, StateEventType}, serde::{Incoming, Raw}, - EventId, OwnedRoomId, RoomId, + EventId, RoomId, }; use serde_json::value::to_raw_value as to_raw_json_value; @@ -172,6 +172,8 @@ pub mod v3 { B: AsRef<[u8]>, S: AsRef, { + use ruma_common::OwnedRoomId; + // FIXME: find a way to make this if-else collapse with serde recognizing trailing // Option let (room_id, event_type, state_key): (OwnedRoomId, StateEventType, String) = diff --git a/crates/ruma-common/src/events/enums.rs b/crates/ruma-common/src/events/enums.rs index a1997caf..aebfc0ba 100644 --- a/crates/ruma-common/src/events/enums.rs +++ b/crates/ruma-common/src/events/enums.rs @@ -8,8 +8,8 @@ use super::{ Redact, }; use crate::{ - serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, - TransactionId, UserId, + serde::from_raw_json_value, EventId, MilliSecondsSinceUnixEpoch, OwnedRoomId, RoomId, + RoomVersionId, TransactionId, UserId, }; event_enum! { @@ -191,7 +191,7 @@ impl AnySyncRoomEvent { } /// Converts `self` to an `AnyRoomEvent` by adding the given a room ID. - pub fn into_full_event(self, room_id: Box) -> AnyRoomEvent { + pub fn into_full_event(self, room_id: OwnedRoomId) -> AnyRoomEvent { match self { Self::MessageLike(ev) => AnyRoomEvent::MessageLike(ev.into_full_event(room_id)), Self::State(ev) => AnyRoomEvent::State(ev.into_full_event(room_id)), diff --git a/crates/ruma-common/src/events/file.rs b/crates/ruma-common/src/events/file.rs index 43ddc904..d03e19d9 100644 --- a/crates/ruma-common/src/events/file.rs +++ b/crates/ruma-common/src/events/file.rs @@ -15,7 +15,7 @@ use super::{ EncryptedFile, ImageInfo, JsonWebKey, MediaSource, }, }; -use crate::{serde::Base64, MxcUri}; +use crate::{serde::Base64, OwnedMxcUri}; /// The payload for an extensible file message. /// @@ -52,7 +52,7 @@ impl FileEventContent { /// file info. pub fn plain( message: impl Into, - url: Box, + url: OwnedMxcUri, info: Option>, ) -> Self { Self { @@ -66,7 +66,7 @@ impl FileEventContent { /// file info. pub fn plain_message( message: MessageContent, - url: Box, + url: OwnedMxcUri, info: Option>, ) -> Self { Self { message, file: FileContent::plain(url, info), relates_to: None } @@ -76,7 +76,7 @@ impl FileEventContent { /// encryption info and file info. pub fn encrypted( message: impl Into, - url: Box, + url: OwnedMxcUri, encryption_info: EncryptedContent, info: Option>, ) -> Self { @@ -91,7 +91,7 @@ impl FileEventContent { /// encryption info and file info. pub fn encrypted_message( message: MessageContent, - url: Box, + url: OwnedMxcUri, encryption_info: EncryptedContent, info: Option>, ) -> Self { @@ -120,7 +120,7 @@ impl FileEventContent { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct FileContent { /// The URL to the file. - pub url: Box, + pub url: OwnedMxcUri, /// Information about the uploaded file. #[serde(flatten, skip_serializing_if = "Option::is_none")] @@ -135,13 +135,13 @@ pub struct FileContent { impl FileContent { /// Creates a new non-encrypted `FileContent` with the given url and file info. - pub fn plain(url: Box, info: Option>) -> Self { + pub fn plain(url: OwnedMxcUri, info: Option>) -> Self { Self { url, info, encryption_info: None } } /// Creates a new encrypted `FileContent` with the given url, encryption info and file info. pub fn encrypted( - url: Box, + url: OwnedMxcUri, encryption_info: EncryptedContent, info: Option>, ) -> Self { @@ -156,7 +156,7 @@ impl FileContent { ) -> Self { let (url, encryption_info) = match source { 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); diff --git a/crates/ruma-common/src/events/ignored_user_list.rs b/crates/ruma-common/src/events/ignored_user_list.rs index d79a9652..945b8ec4 100644 --- a/crates/ruma-common/src/events/ignored_user_list.rs +++ b/crates/ruma-common/src/events/ignored_user_list.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; -use crate::UserId; +use crate::OwnedUserId; /// The content of an `m.ignored_user_list` event. /// @@ -16,12 +16,12 @@ use crate::UserId; pub struct IgnoredUserListEventContent { /// A list of users to ignore. #[serde(with = "crate::serde::vec_as_map_of_empty")] - pub ignored_users: Vec>, + pub ignored_users: Vec, } impl IgnoredUserListEventContent { /// Creates a new `IgnoredUserListEventContent` from the given user IDs. - pub fn new(ignored_users: Vec>) -> Self { + pub fn new(ignored_users: Vec) -> Self { Self { ignored_users } } } diff --git a/crates/ruma-common/src/events/image.rs b/crates/ruma-common/src/events/image.rs index 4d41296b..078006e6 100644 --- a/crates/ruma-common/src/events/image.rs +++ b/crates/ruma-common/src/events/image.rs @@ -14,7 +14,7 @@ use super::{ ImageInfo, MediaSource, ThumbnailInfo, }, }; -use crate::MxcUri; +use crate::OwnedMxcUri; /// The payload for an extensible image message. /// @@ -213,7 +213,7 @@ impl ThumbnailContent { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct ThumbnailFileContent { /// The URL to the thumbnail. - pub url: Box, + pub url: OwnedMxcUri, /// Information about the uploaded thumbnail. #[serde(flatten, skip_serializing_if = "Option::is_none")] @@ -228,14 +228,14 @@ pub struct ThumbnailFileContent { impl ThumbnailFileContent { /// Creates a new non-encrypted `ThumbnailFileContent` with the given url and file info. - pub fn plain(url: Box, info: Option>) -> Self { + pub fn plain(url: OwnedMxcUri, info: Option>) -> Self { Self { url, info, encryption_info: None } } /// Creates a new encrypted `ThumbnailFileContent` with the given url, encryption info and /// thumbnail file info. pub fn encrypted( - url: Box, + url: OwnedMxcUri, encryption_info: EncryptedContent, info: Option>, ) -> Self { diff --git a/crates/ruma-common/src/events/key/verification.rs b/crates/ruma-common/src/events/key/verification.rs index 115dbc4f..06810f6f 100644 --- a/crates/ruma-common/src/events/key/verification.rs +++ b/crates/ruma-common/src/events/key/verification.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; -use crate::{serde::StringEnum, EventId, PrivOwnedStr}; +use crate::{serde::StringEnum, OwnedEventId, PrivOwnedStr}; pub mod accept; pub mod cancel; @@ -124,12 +124,12 @@ impl ShortAuthenticationString { #[serde(tag = "rel_type", rename = "m.reference")] pub struct Relation { /// The event ID of a related `m.key.verification.request`. - pub event_id: Box, + pub event_id: OwnedEventId, } impl Relation { /// Creates a new `Relation` with the given event ID. - pub fn new(event_id: Box) -> Self { + pub fn new(event_id: OwnedEventId) -> Self { Self { event_id } } } diff --git a/crates/ruma-common/src/events/kinds.rs b/crates/ruma-common/src/events/kinds.rs index ac6fc849..a47bb36e 100644 --- a/crates/ruma-common/src/events/kinds.rs +++ b/crates/ruma-common/src/events/kinds.rs @@ -13,7 +13,8 @@ use super::{ StateUnsigned, ToDeviceEventContent, }; 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. @@ -37,7 +38,7 @@ pub struct EphemeralRoomEvent { pub content: C, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, } /// An ephemeral room event without a `room_id`. @@ -57,16 +58,16 @@ pub struct OriginalMessageLikeEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// Additional key-value pairs not signed by the homeserver. pub unsigned: MessageLikeUnsigned, @@ -82,10 +83,10 @@ pub struct OriginalSyncMessageLikeEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, @@ -104,16 +105,16 @@ pub struct RedactedMessageLikeEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// Additional key-value pairs not signed by the homeserver. pub unsigned: RedactedUnsigned, @@ -129,10 +130,10 @@ pub struct RedactedSyncMessageLikeEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, @@ -187,16 +188,16 @@ pub struct OriginalStateEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// A unique key which defines the overwriting semantics for this piece of room state. /// @@ -218,10 +219,10 @@ pub struct OriginalSyncStateEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, @@ -243,7 +244,7 @@ pub struct StrippedStateEvent { pub content: C, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// A unique key which defines the overwriting semantics for this piece of room state. /// @@ -278,16 +279,16 @@ pub struct RedactedStateEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// A unique key which defines the overwriting semantics for this piece of room state. /// @@ -309,10 +310,10 @@ pub struct RedactedSyncStateEvent { pub content: C, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, @@ -370,7 +371,7 @@ pub struct ToDeviceEvent { pub content: C, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, } /// The decrypted payload of an `m.olm.v1.curve25519-aes-sha2` event. @@ -380,10 +381,10 @@ pub struct DecryptedOlmV1Event { pub content: C, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// The fully-qualified ID of the intended recipient this event. - pub recipient: Box, + pub recipient: OwnedUserId, /// The recipient's ed25519 key. pub recipient_keys: OlmV1Keys, @@ -406,7 +407,7 @@ pub struct DecryptedMegolmV1Event { pub content: C, /// The ID of the room associated with the event. - pub room_id: Box, + pub room_id: OwnedRoomId, } 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). - pub fn into_full_event(self, room_id: Box) -> MessageLikeEvent { + pub fn into_full_event(self, room_id: OwnedRoomId) -> MessageLikeEvent { match self { Self::Original(ev) => MessageLikeEvent::Original(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). - pub fn into_full_event(self, room_id: Box) -> StateEvent { + pub fn into_full_event(self, room_id: OwnedRoomId) -> StateEvent { match self { Self::Original(ev) => StateEvent::Original(ev.into_full_event(room_id)), Self::Redacted(ev) => StateEvent::Redacted(ev.into_full_event(room_id)), diff --git a/crates/ruma-common/src/events/pdu.rs b/crates/ruma-common/src/events/pdu.rs index faa9766f..a4eac001 100644 --- a/crates/ruma-common/src/events/pdu.rs +++ b/crates/ruma-common/src/events/pdu.rs @@ -2,7 +2,7 @@ //! //! 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 -//! `prev_events` take `Vec<(Box, EventHash)> rather than `Vec>` in +//! `prev_events` take `Vec<(OwnedEventId, EventHash)> rather than `Vec` in //! `RoomV3Pdu`. use std::collections::BTreeMap; @@ -15,7 +15,10 @@ use serde::{ use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue}; use super::RoomEventType; -use crate::{EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId, UserId}; +use crate::{ + MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedServerName, + OwnedServerSigningKeyId, OwnedUserId, +}; /// Enum for PDU schemas #[derive(Clone, Debug, Serialize)] @@ -34,13 +37,13 @@ pub enum Pdu { #[allow(clippy::exhaustive_structs)] pub struct RoomV1Pdu { /// Event ID for the PDU. - pub event_id: Box, + pub event_id: OwnedEventId, /// The room this event belongs to. - pub room_id: Box, + pub room_id: OwnedRoomId, /// The user id of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver /// 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 /// aware of when it created this event. #[serde(skip_serializing_if = "Vec::is_empty")] - pub prev_events: Vec<(Box, EventHash)>, + pub prev_events: Vec<(OwnedEventId, EventHash)>, /// The maximum depth of the `prev_events`, plus one. pub depth: UInt, @@ -69,11 +72,11 @@ pub struct RoomV1Pdu { /// Event IDs for the authorization events that would allow this event to be /// in the room. #[serde(skip_serializing_if = "Vec::is_empty")] - pub auth_events: Vec<(Box, EventHash)>, + pub auth_events: Vec<(OwnedEventId, EventHash)>, /// For redaction events, the ID of the event being redacted. #[serde(skip_serializing_if = "Option::is_none")] - pub redacts: Option>, + pub redacts: Option, /// Additional data added by the origin server but not covered by the /// signatures. @@ -84,7 +87,7 @@ pub struct RoomV1Pdu { pub hashes: EventHash, /// Signatures for the PDU. - pub signatures: BTreeMap, BTreeMap, String>>, + pub signatures: BTreeMap>, } /// A 'persistent data unit' (event) for room versions 3 and beyond. @@ -92,10 +95,10 @@ pub struct RoomV1Pdu { #[allow(clippy::exhaustive_structs)] pub struct RoomV3Pdu { /// The room this event belongs to. - pub room_id: Box, + pub room_id: OwnedRoomId, /// The user id of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver /// 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 /// aware of when it created this event. - pub prev_events: Vec>, + pub prev_events: Vec, /// The maximum depth of the `prev_events`, plus one. pub depth: UInt, /// Event IDs for the authorization events that would allow this event to be /// in the room. - pub auth_events: Vec>, + pub auth_events: Vec, /// For redaction events, the ID of the event being redacted. #[serde(skip_serializing_if = "Option::is_none")] - pub redacts: Option>, + pub redacts: Option, /// Additional data added by the origin server but not covered by the /// signatures. @@ -137,7 +140,7 @@ pub struct RoomV3Pdu { pub hashes: EventHash, /// Signatures for the PDU. - pub signatures: BTreeMap, BTreeMap, String>>, + pub signatures: BTreeMap>, } /// Content hashes of a PDU. diff --git a/crates/ruma-common/src/events/presence.rs b/crates/ruma-common/src/events/presence.rs index 926eef82..81217e73 100644 --- a/crates/ruma-common/src/events/presence.rs +++ b/crates/ruma-common/src/events/presence.rs @@ -7,7 +7,7 @@ use ruma_macros::{Event, EventContent}; use serde::{Deserialize, Serialize}; use super::{EventKind, StaticEventContent}; -use crate::{presence::PresenceState, MxcUri, UserId}; +use crate::{presence::PresenceState, OwnedMxcUri, OwnedUserId}; /// Presence event. #[derive(Clone, Debug, Event)] @@ -17,7 +17,7 @@ pub struct PresenceEvent { pub content: PresenceEventContent, /// Contains the fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, } /// Informs the room of members presence. @@ -36,7 +36,7 @@ pub struct PresenceEventContent { feature = "compat", serde(default, deserialize_with = "crate::serde::empty_string_as_none") )] - pub avatar_url: Option>, + pub avatar_url: Option, /// Whether or not the user is currently active. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/ruma-common/src/events/receipt.rs b/crates/ruma-common/src/events/receipt.rs index 9011a6f6..2a2f8045 100644 --- a/crates/ruma-common/src/events/receipt.rs +++ b/crates/ruma-common/src/events/receipt.rs @@ -10,7 +10,9 @@ use std::{ use ruma_macros::EventContent; 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. /// @@ -21,7 +23,7 @@ use crate::{receipt::ReceiptType, EventId, MilliSecondsSinceUnixEpoch, UserId}; #[derive(Clone, Debug, Deserialize, Serialize, EventContent)] #[allow(clippy::exhaustive_structs)] #[ruma_event(type = "m.receipt", kind = EphemeralRoom)] -pub struct ReceiptEventContent(pub BTreeMap, Receipts>); +pub struct ReceiptEventContent(pub BTreeMap); impl ReceiptEventContent { /// 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 { - type Target = BTreeMap, Receipts>; + type Target = BTreeMap; fn deref(&self) -> &Self::Target { &self.0 @@ -57,7 +59,7 @@ pub type Receipts = BTreeMap; /// A mapping of user ID to receipt. /// /// The user ID is the entity who sent this receipt. -pub type UserReceipts = BTreeMap, Receipt>; +pub type UserReceipts = BTreeMap; /// An acknowledgement of an event. #[derive(Clone, Debug, Default, Deserialize, Serialize)] diff --git a/crates/ruma-common/src/events/room.rs b/crates/ruma-common/src/events/room.rs index 0d0217ca..5677eade 100644 --- a/crates/ruma-common/src/events/room.rs +++ b/crates/ruma-common/src/events/room.rs @@ -14,9 +14,11 @@ use super::{ file::FileContentInfo, image::{ImageContent, ThumbnailContent, ThumbnailFileContent, ThumbnailFileContentInfo}, }; +#[cfg(feature = "unstable-msc3551")] +use crate::MxcUri; use crate::{ serde::{base64::UrlSafe, Base64}, - MxcUri, + OwnedMxcUri, }; pub mod aliases; @@ -46,7 +48,7 @@ pub mod topic; pub enum MediaSource { /// The MXC URI to the unencrypted media file. #[serde(rename = "url")] - Plain(Box), + Plain(OwnedMxcUri), /// The encryption info of the encrypted media file. #[serde(rename = "file")] @@ -64,7 +66,7 @@ impl<'de> Deserialize<'de> for MediaSource { { #[derive(Deserialize)] pub struct MediaSourceJsonRepr { - url: Option>, + url: Option, file: Option>, } @@ -243,7 +245,7 @@ impl ThumbnailInfo { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct EncryptedFile { /// The URL to the file. - pub url: Box, + pub url: OwnedMxcUri, /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object. pub key: JsonWebKey, @@ -279,7 +281,7 @@ impl EncryptedFile { #[allow(clippy::exhaustive_structs)] pub struct EncryptedFileInit { /// The URL to the file. - pub url: Box, + pub url: OwnedMxcUri, /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object. pub key: JsonWebKey, @@ -384,7 +386,7 @@ mod tests { use serde::Deserialize; 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}; @@ -408,7 +410,7 @@ mod tests { fn encrypted_file() -> EncryptedFile { EncryptedFile { - url: "mxc://localhost/encrypted_file".into(), + url: mxc_uri!("mxc://localhost/encryptedfile").to_owned(), key: dummy_jwt(), iv: Base64::new(vec![0; 64]), hashes: BTreeMap::new(), diff --git a/crates/ruma-common/src/events/room/aliases.rs b/crates/ruma-common/src/events/room/aliases.rs index 3b287e15..cb31571d 100644 --- a/crates/ruma-common/src/events/room/aliases.rs +++ b/crates/ruma-common/src/events/room/aliases.rs @@ -8,7 +8,7 @@ use crate::{ events::{ EventContent, HasDeserializeFields, RedactContent, RedactedEventContent, StateEventType, }, - RoomAliasId, RoomVersionId, + OwnedRoomAliasId, RoomVersionId, }; /// The content of an `m.room.aliases` event. @@ -19,12 +19,12 @@ use crate::{ #[ruma_event(type = "m.room.aliases", kind = State, custom_redacted)] pub struct RoomAliasesEventContent { /// A list of room aliases. - pub aliases: Vec>, + pub aliases: Vec, } impl RoomAliasesEventContent { /// Create an `RoomAliasesEventContent` from the given aliases. - pub fn new(aliases: Vec>) -> Self { + pub fn new(aliases: Vec) -> Self { Self { aliases } } } @@ -56,14 +56,14 @@ pub struct RedactedRoomAliasesEventContent { /// /// According to the Matrix spec version 1 redaction rules allowed this field to be /// kept after redaction, this was changed in version 6. - pub aliases: Option>>, + pub aliases: Option>, } impl RedactedRoomAliasesEventContent { /// Create a `RedactedAliasesEventContent` with the given aliases. /// /// This is only valid for room version 5 and below. - pub fn new_v1(aliases: Vec>) -> Self { + pub fn new_v1(aliases: Vec) -> Self { Self { aliases: Some(aliases) } } diff --git a/crates/ruma-common/src/events/room/canonical_alias.rs b/crates/ruma-common/src/events/room/canonical_alias.rs index 8d8c6cac..fb81c533 100644 --- a/crates/ruma-common/src/events/room/canonical_alias.rs +++ b/crates/ruma-common/src/events/room/canonical_alias.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; -use crate::RoomAliasId; +use crate::{OwnedRoomAliasId, RoomAliasId}; /// The content of an `m.room.canonical_alias` event. /// @@ -23,7 +23,7 @@ pub struct RoomCanonicalAliasEventContent { deserialize_with = "crate::serde::empty_string_as_none", skip_serializing_if = "Option::is_none" )] - pub alias: Option>, + pub alias: Option, /// List of alternative aliases to the room. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/ruma-common/src/events/room/create.rs b/crates/ruma-common/src/events/room/create.rs index 22f32cd0..6201b9bd 100644 --- a/crates/ruma-common/src/events/room/create.rs +++ b/crates/ruma-common/src/events/room/create.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; 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. /// @@ -20,7 +20,7 @@ pub struct RoomCreateEventContent { /// /// This is set by the homeserver. #[ruma_event(skip_redaction)] - pub creator: Box, + pub creator: OwnedUserId, /// Whether or not this room's data should be transferred to other homeservers. #[serde( @@ -49,7 +49,7 @@ pub struct RoomCreateEventContent { impl RoomCreateEventContent { /// Creates a new `RoomCreateEventContent` with the given creator. - pub fn new(creator: Box) -> Self { + pub fn new(creator: OwnedUserId) -> Self { Self { creator, federate: true, diff --git a/crates/ruma-common/src/events/room/encrypted.rs b/crates/ruma-common/src/events/room/encrypted.rs index f575b6ec..549507de 100644 --- a/crates/ruma-common/src/events/room/encrypted.rs +++ b/crates/ruma-common/src/events/room/encrypted.rs @@ -9,7 +9,9 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; use super::message::{self, InReplyTo}; -use crate::{DeviceId, EventId}; +#[cfg(feature = "unstable-msc2677")] +use crate::EventId; +use crate::{DeviceId, OwnedEventId}; mod relation_serde; @@ -138,7 +140,7 @@ impl From for Relation { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Replacement { /// The ID of the event being replacing. - pub event_id: Box, + pub event_id: OwnedEventId, } /// A reference to another event. @@ -146,12 +148,12 @@ pub struct Replacement { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Reference { /// The event we are referencing. - pub event_id: Box, + pub event_id: OwnedEventId, } impl Reference { /// Creates a new `Reference` with the given event ID. - pub fn new(event_id: Box) -> Self { + pub fn new(event_id: OwnedEventId) -> Self { Self { event_id } } } @@ -182,7 +184,7 @@ impl Annotation { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Thread { /// The ID of the root message in the thread. - pub event_id: Box, + pub event_id: OwnedEventId, /// A reply relation. /// @@ -203,13 +205,13 @@ pub struct Thread { impl Thread { /// Convenience method to create a regular `Thread` with the given event ID and latest /// message-like event ID. - pub fn plain(event_id: Box, latest_event_id: Box) -> 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 } } /// Convenience method to create a reply `Thread` with the given event ID and replied-to event /// ID. - pub fn reply(event_id: Box, reply_to_event_id: Box) -> 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 } } } diff --git a/crates/ruma-common/src/events/room/encrypted/relation_serde.rs b/crates/ruma-common/src/events/room/encrypted/relation_serde.rs index d40b86f9..e12287ef 100644 --- a/crates/ruma-common/src/events/room/encrypted/relation_serde.rs +++ b/crates/ruma-common/src/events/room/encrypted/relation_serde.rs @@ -8,7 +8,7 @@ use super::Replacement; use super::Thread; use super::{InReplyTo, Reference, Relation}; #[cfg(feature = "unstable-msc3440")] -use crate::EventId; +use crate::OwnedEventId; impl<'de> Deserialize<'de> for Relation { fn deserialize(deserializer: D) -> Result @@ -126,7 +126,7 @@ impl RelatesToJsonRepr { #[cfg(feature = "unstable-msc3440")] struct ThreadStableJsonRepr { /// The ID of the root message in the thread. - pub event_id: Box, + pub event_id: OwnedEventId, /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// thread. @@ -139,7 +139,7 @@ struct ThreadStableJsonRepr { #[cfg(feature = "unstable-msc3440")] struct ThreadUnstableJsonRepr { /// The ID of the root message in the thread. - pub event_id: Box, + pub event_id: OwnedEventId, /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// thread. diff --git a/crates/ruma-common/src/events/room/join_rules.rs b/crates/ruma-common/src/events/room/join_rules.rs index 0801639f..f2c5f0bb 100644 --- a/crates/ruma-common/src/events/room/join_rules.rs +++ b/crates/ruma-common/src/events/room/join_rules.rs @@ -11,7 +11,7 @@ use serde::{ }; 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. /// @@ -179,7 +179,7 @@ pub enum AllowRule { impl AllowRule { /// Constructs an `AllowRule` with membership of the room with the given id as its predicate. - pub fn room_membership(room_id: Box) -> Self { + pub fn room_membership(room_id: OwnedRoomId) -> Self { Self::RoomMembership(RoomMembership::new(room_id)) } } @@ -189,12 +189,12 @@ impl AllowRule { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct RoomMembership { /// The id of the room which being a member of grants permission to join another room. - pub room_id: Box, + pub room_id: OwnedRoomId, } impl RoomMembership { /// Constructs a new room membership rule for the given room id. - pub fn new(room_id: Box) -> Self { + pub fn new(room_id: OwnedRoomId) -> Self { Self { room_id } } } diff --git a/crates/ruma-common/src/events/room/member.rs b/crates/ruma-common/src/events/room/member.rs index 351c0c19..d6453247 100644 --- a/crates/ruma-common/src/events/room/member.rs +++ b/crates/ruma-common/src/events/room/member.rs @@ -14,7 +14,8 @@ use crate::{ RedactedEventContent, StateEventType, StrippedStateEvent, }, serde::StringEnum, - MxcUri, PrivOwnedStr, RoomVersionId, ServerName, ServerSigningKeyId, UserId, + MxcUri, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, PrivOwnedStr, RoomVersionId, + UserId, }; /// 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. #[serde(rename = "join_authorised_via_users_server")] #[serde(skip_serializing_if = "Option::is_none")] - pub join_authorized_via_users_server: Option>, + pub join_authorized_via_users_server: Option, } impl RoomMemberEventContent { @@ -145,7 +146,7 @@ pub struct RedactedRoomMemberEventContent { /// This is redacted in room versions 8 and below. It is used for validating /// joins when the join rule is restricted. #[serde(rename = "join_authorised_via_users_server")] - pub join_authorized_via_users_server: Option>, + pub join_authorized_via_users_server: Option, } impl RedactedRoomMemberEventContent { @@ -251,7 +252,7 @@ pub struct SignedContent { /// A single signature from the verifying server, in the format specified by the Signing Events /// section of the server-server API. - pub signatures: BTreeMap, BTreeMap, String>>, + pub signatures: BTreeMap>, /// The token property of the containing `third_party_invite` object. pub token: String, @@ -261,7 +262,7 @@ impl SignedContent { /// Creates a new `SignedContent` with the given mxid, signature and token. pub fn new( mxid: Box, - signatures: BTreeMap, BTreeMap, String>>, + signatures: BTreeMap>, token: String, ) -> Self { Self { mxid, signatures, token } diff --git a/crates/ruma-common/src/events/room/message.rs b/crates/ruma-common/src/events/room/message.rs index cb346cfb..381e5f3e 100644 --- a/crates/ruma-common/src/events/room/message.rs +++ b/crates/ruma-common/src/events/room/message.rs @@ -29,7 +29,7 @@ use crate::events::{ use crate::{ events::key::verification::VerificationMethod, serde::{JsonObject, StringEnum}, - DeviceId, EventId, MxcUri, PrivOwnedStr, UserId, + DeviceId, OwnedEventId, OwnedMxcUri, OwnedUserId, PrivOwnedStr, }; #[cfg(feature = "unstable-msc3488")] use crate::{ @@ -634,12 +634,12 @@ pub enum Relation { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct InReplyTo { /// The event being replied to. - pub event_id: Box, + pub event_id: OwnedEventId, } impl InReplyTo { /// Creates a new `InReplyTo` with the given event ID. - pub fn new(event_id: Box) -> Self { + pub fn new(event_id: OwnedEventId) -> Self { Self { event_id } } } @@ -650,7 +650,7 @@ impl InReplyTo { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Replacement { /// The ID of the event being replaced. - pub event_id: Box, + pub event_id: OwnedEventId, /// New content. pub new_content: Box, @@ -659,7 +659,7 @@ pub struct Replacement { #[cfg(feature = "unstable-msc2676")] impl Replacement { /// Creates a new `Replacement` with the given event ID and new content. - pub fn new(event_id: Box, new_content: Box) -> Self { + pub fn new(event_id: OwnedEventId, new_content: Box) -> Self { Self { event_id, new_content } } } @@ -670,7 +670,7 @@ impl Replacement { #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct Thread { /// The ID of the root message in the thread. - pub event_id: Box, + pub event_id: OwnedEventId, /// A reply relation. /// @@ -691,13 +691,13 @@ pub struct Thread { impl Thread { /// Convenience method to create a regular `Thread` with the given event ID and latest /// message-like event ID. - pub fn plain(event_id: Box, latest_event_id: Box) -> 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 } } /// Convenience method to create a reply `Thread` with the given event ID and replied-to event /// ID. - pub fn reply(event_id: Box, reply_to_event_id: Box) -> 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 } } } @@ -761,7 +761,7 @@ pub struct AudioMessageEventContent { impl AudioMessageEventContent { /// Creates a new non-encrypted `AudioMessageEventContent` with the given body, url and /// optional extra info. - pub fn plain(body: String, url: Box, info: Option>) -> Self { + pub fn plain(body: String, url: OwnedMxcUri, info: Option>) -> Self { Self { #[cfg(feature = "unstable-msc3246")] message: Some(MessageContent::plain(body.clone())), @@ -1008,7 +1008,7 @@ pub struct FileMessageEventContent { impl FileMessageEventContent { /// Creates a new non-encrypted `FileMessageEventContent` with the given body, url and /// optional extra info. - pub fn plain(body: String, url: Box, info: Option>) -> Self { + pub fn plain(body: String, url: OwnedMxcUri, info: Option>) -> Self { Self { #[cfg(feature = "unstable-msc3551")] message: Some(MessageContent::plain(body.clone())), @@ -1165,7 +1165,7 @@ pub struct ImageMessageEventContent { impl ImageMessageEventContent { /// Creates a new non-encrypted `ImageMessageEventContent` with the given body, url and /// optional extra info. - pub fn plain(body: String, url: Box, info: Option>) -> Self { + pub fn plain(body: String, url: OwnedMxcUri, info: Option>) -> Self { Self { #[cfg(feature = "unstable-msc3552")] message: Some(MessageContent::plain(body.clone())), @@ -1714,7 +1714,7 @@ pub struct VideoMessageEventContent { impl VideoMessageEventContent { /// Creates a new non-encrypted `VideoMessageEventContent` with the given body, url and /// optional extra info. - pub fn plain(body: String, url: Box, info: Option>) -> Self { + pub fn plain(body: String, url: OwnedMxcUri, info: Option>) -> Self { Self { #[cfg(feature = "unstable-msc3553")] 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 /// 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. - pub to: Box, + pub to: OwnedUserId, } impl KeyVerificationRequestEventContent { @@ -1923,7 +1923,7 @@ impl KeyVerificationRequestEventContent { body: String, methods: Vec, from_device: Box, - to: Box, + to: OwnedUserId, ) -> Self { Self { body, methods, from_device, to } } diff --git a/crates/ruma-common/src/events/room/message/relation_serde.rs b/crates/ruma-common/src/events/room/message/relation_serde.rs index 60285e0f..c68d4b67 100644 --- a/crates/ruma-common/src/events/room/message/relation_serde.rs +++ b/crates/ruma-common/src/events/room/message/relation_serde.rs @@ -8,7 +8,7 @@ use super::RoomMessageEventContent; use super::Thread; use super::{InReplyTo, Relation}; #[cfg(any(feature = "unstable-msc2676", feature = "unstable-msc3440"))] -use crate::EventId; +use crate::OwnedEventId; impl<'de> Deserialize<'de> for Relation { fn deserialize(deserializer: D) -> Result @@ -165,7 +165,7 @@ enum RelationJsonRepr { #[derive(Clone, Deserialize, Serialize)] #[cfg(feature = "unstable-msc2676")] struct ReplacementJsonRepr { - event_id: Box, + event_id: OwnedEventId, } /// A thread relation without the reply fallback, with stable names. @@ -173,7 +173,7 @@ struct ReplacementJsonRepr { #[cfg(feature = "unstable-msc3440")] struct ThreadStableJsonRepr { /// The ID of the root message in the thread. - event_id: Box, + event_id: OwnedEventId, /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// thread. @@ -186,7 +186,7 @@ struct ThreadStableJsonRepr { #[cfg(feature = "unstable-msc3440")] struct ThreadUnstableJsonRepr { /// The ID of the root message in the thread. - event_id: Box, + event_id: OwnedEventId, /// Whether the `m.in_reply_to` field is a fallback for older clients or a real reply in a /// thread. diff --git a/crates/ruma-common/src/events/room/pinned_events.rs b/crates/ruma-common/src/events/room/pinned_events.rs index de1038aa..ed00bed3 100644 --- a/crates/ruma-common/src/events/room/pinned_events.rs +++ b/crates/ruma-common/src/events/room/pinned_events.rs @@ -45,10 +45,10 @@ mod tests { let event = OriginalStateEvent { 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()), - room_id: RoomId::new(server_name), - sender: UserId::new(server_name), + room_id: RoomId::new(server_name).into(), + sender: UserId::new(server_name).into(), state_key: "".into(), unsigned: StateUnsigned::default(), }; diff --git a/crates/ruma-common/src/events/room/power_levels.rs b/crates/ruma-common/src/events/room/power_levels.rs index 59bf6ced..21e4d539 100644 --- a/crates/ruma-common/src/events/room/power_levels.rs +++ b/crates/ruma-common/src/events/room/power_levels.rs @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize}; use crate::{ events::RoomEventType, power_levels::{default_power_level, NotificationPowerLevels}, - UserId, + OwnedUserId, UserId, }; /// The content of an `m.room.power_levels` event. @@ -118,7 +118,7 @@ pub struct RoomPowerLevelsEventContent { )] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[ruma_event(skip_redaction)] - pub users: BTreeMap, Int>, + pub users: BTreeMap, /// The default power level for every user in the room. /// @@ -227,7 +227,7 @@ pub struct RoomPowerLevels { /// The power levels for specific users. /// /// This is a mapping from `user_id` to power level for that user. - pub users: BTreeMap, Int>, + pub users: BTreeMap, /// The default power level for every user in the room. pub users_default: Int, diff --git a/crates/ruma-common/src/events/room/redaction.rs b/crates/ruma-common/src/events/room/redaction.rs index 2cfe9f1e..bff6326c 100644 --- a/crates/ruma-common/src/events/room/redaction.rs +++ b/crates/ruma-common/src/events/room/redaction.rs @@ -12,7 +12,7 @@ use crate::{ RedactedUnsigned, RedactionDeHelper, }, serde::from_raw_json_value, - EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, + EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, UserId, }; /// A possibly-redacted redaction event. @@ -47,19 +47,19 @@ pub struct OriginalRoomRedactionEvent { pub content: RoomRedactionEventContent, /// The ID of the event that was redacted. - pub redacts: Box, + pub redacts: OwnedEventId, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// Additional key-value pairs not signed by the homeserver. pub unsigned: MessageLikeUnsigned, @@ -92,16 +92,16 @@ pub struct RedactedRoomRedactionEvent { pub content: RedactedRoomRedactionEventContent, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. - pub room_id: Box, + pub room_id: OwnedRoomId, /// Additional key-value pairs not signed by the homeserver. pub unsigned: RedactedUnsigned, @@ -115,13 +115,13 @@ pub struct OriginalSyncRoomRedactionEvent { pub content: RoomRedactionEventContent, /// The ID of the event that was redacted. - pub redacts: Box, + pub redacts: OwnedEventId, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, @@ -156,10 +156,10 @@ pub struct RedactedSyncRoomRedactionEvent { pub content: RedactedRoomRedactionEventContent, /// The globally unique event identifier for the user who sent the event. - pub event_id: Box, + pub event_id: OwnedEventId, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. 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). - pub fn into_full_event(self, room_id: Box) -> RoomRedactionEvent { + pub fn into_full_event(self, room_id: OwnedRoomId) -> RoomRedactionEvent { match self { Self::Original(ev) => RoomRedactionEvent::Original(ev.into_full_event(room_id)), Self::Redacted(ev) => RoomRedactionEvent::Redacted(ev.into_full_event(room_id)), diff --git a/crates/ruma-common/src/events/room/thumbnail_source_serde.rs b/crates/ruma-common/src/events/room/thumbnail_source_serde.rs index 94ca45ad..6ae53f86 100644 --- a/crates/ruma-common/src/events/room/thumbnail_source_serde.rs +++ b/crates/ruma-common/src/events/room/thumbnail_source_serde.rs @@ -5,7 +5,7 @@ use serde::{ Deserialize, Deserializer, }; -use crate::MxcUri; +use crate::OwnedMxcUri; use super::{EncryptedFile, MediaSource}; @@ -33,7 +33,7 @@ where { #[derive(Deserialize)] pub struct ThumbnailSourceJsonRepr { - thumbnail_url: Option>, + thumbnail_url: Option, thumbnail_file: Option>, } diff --git a/crates/ruma-common/src/events/room_key.rs b/crates/ruma-common/src/events/room_key.rs index b0f4e63b..7c1248e0 100644 --- a/crates/ruma-common/src/events/room_key.rs +++ b/crates/ruma-common/src/events/room_key.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; -use crate::{EventEncryptionAlgorithm, RoomId}; +use crate::{EventEncryptionAlgorithm, OwnedRoomId}; /// The content of an `m.room_key` event. /// @@ -20,7 +20,7 @@ pub struct ToDeviceRoomKeyEventContent { pub algorithm: EventEncryptionAlgorithm, /// The room where the key is used. - pub room_id: Box, + pub room_id: OwnedRoomId, /// The ID of the session that the key is for. pub session_id: String, @@ -34,7 +34,7 @@ impl ToDeviceRoomKeyEventContent { /// and session key. pub fn new( algorithm: EventEncryptionAlgorithm, - room_id: Box, + room_id: OwnedRoomId, session_id: String, session_key: String, ) -> Self { diff --git a/crates/ruma-common/src/events/space/child.rs b/crates/ruma-common/src/events/space/child.rs index 72351291..ad23a7e2 100644 --- a/crates/ruma-common/src/events/space/child.rs +++ b/crates/ruma-common/src/events/space/child.rs @@ -5,7 +5,7 @@ use ruma_macros::{Event, EventContent}; use serde::{Deserialize, Serialize}; -use crate::{MilliSecondsSinceUnixEpoch, ServerName, UserId}; +use crate::{MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedUserId}; /// The content of an `m.space.child` event. /// @@ -20,7 +20,7 @@ use crate::{MilliSecondsSinceUnixEpoch, ServerName, UserId}; pub struct SpaceChildEventContent { /// List of candidate servers that can be used to join the room. #[serde(skip_serializing_if = "Option::is_none")] - pub via: Option>>, + pub via: Option>, /// Provide a default ordering of siblings in the room list. /// @@ -60,7 +60,7 @@ pub struct HierarchySpaceChildEvent { pub content: SpaceChildEventContent, /// The fully-qualified ID of the user who sent this event. - pub sender: Box, + pub sender: OwnedUserId, /// The room ID of the child. pub state_key: String, diff --git a/crates/ruma-common/src/events/space/parent.rs b/crates/ruma-common/src/events/space/parent.rs index 35ac1ce6..bfc03e8f 100644 --- a/crates/ruma-common/src/events/space/parent.rs +++ b/crates/ruma-common/src/events/space/parent.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; -use crate::ServerName; +use crate::OwnedServerName; /// The content of an `m.space.parent` event. /// @@ -20,7 +20,7 @@ use crate::ServerName; pub struct SpaceParentEventContent { /// List of candidate servers that can be used to join the room. #[serde(skip_serializing_if = "Option::is_none")] - pub via: Option>>, + pub via: Option>, /// Determines whether this is the main parent for the space. /// diff --git a/crates/ruma-common/src/events/sticker.rs b/crates/ruma-common/src/events/sticker.rs index 45a5f187..959e8c49 100644 --- a/crates/ruma-common/src/events/sticker.rs +++ b/crates/ruma-common/src/events/sticker.rs @@ -11,7 +11,7 @@ use super::{ image::{ImageContent, ThumbnailContent}, message::MessageContent, }; -use crate::{events::room::ImageInfo, MxcUri}; +use crate::{events::room::ImageInfo, OwnedMxcUri}; /// The content of an `m.sticker` event. /// @@ -35,7 +35,7 @@ pub struct StickerEventContent { pub info: ImageInfo, /// The URL to the sticker image. - pub url: Box, + pub url: OwnedMxcUri, /// Extensible-event text representation of the message. /// @@ -91,7 +91,7 @@ pub struct StickerEventContent { impl StickerEventContent { /// Creates a new `StickerEventContent` with the given body, image info and URL. - pub fn new(body: String, info: ImageInfo, url: Box) -> Self { + pub fn new(body: String, info: ImageInfo, url: OwnedMxcUri) -> Self { Self { #[cfg(feature = "unstable-msc3552")] message: Some(MessageContent::plain(body.clone())), diff --git a/crates/ruma-common/src/events/typing.rs b/crates/ruma-common/src/events/typing.rs index d6cf3b03..afa3f340 100644 --- a/crates/ruma-common/src/events/typing.rs +++ b/crates/ruma-common/src/events/typing.rs @@ -5,7 +5,7 @@ use ruma_macros::EventContent; use serde::{Deserialize, Serialize}; -use crate::UserId; +use crate::OwnedUserId; /// The content of an `m.typing` event. /// @@ -15,12 +15,12 @@ use crate::UserId; #[ruma_event(type = "m.typing", kind = EphemeralRoom)] pub struct TypingEventContent { /// The list of user IDs typing in this room, if any. - pub user_ids: Vec>, + pub user_ids: Vec, } impl TypingEventContent { /// Creates a new `TypingEventContent` with the given user IDs. - pub fn new(user_ids: Vec>) -> Self { + pub fn new(user_ids: Vec) -> Self { Self { user_ids } } } diff --git a/crates/ruma-common/src/identifiers/device_id.rs b/crates/ruma-common/src/identifiers/device_id.rs index b792de5e..4c275e68 100644 --- a/crates/ruma-common/src/identifiers/device_id.rs +++ b/crates/ruma-common/src/identifiers/device_id.rs @@ -63,7 +63,7 @@ mod tests { #[test] fn create_device_id_from_box() { let box_str: Box = "ijklmnop".into(); - let device_id: Box = DeviceId::from_box(box_str); + let device_id: Box = box_str.into(); assert_eq!(device_id.as_str(), "ijklmnop"); } } diff --git a/crates/ruma-common/src/identifiers/matrix_uri.rs b/crates/ruma-common/src/identifiers/matrix_uri.rs index 7c0cdf43..b18a21f9 100644 --- a/crates/ruma-common/src/identifiers/matrix_uri.rs +++ b/crates/ruma-common/src/identifiers/matrix_uri.rs @@ -9,7 +9,7 @@ use ruma_identifiers_validation::{ }; use url::Url; -use super::{EventId, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UserId}; +use super::{EventId, OwnedServerName, RoomAliasId, RoomId, RoomOrAliasId, ServerName, UserId}; use crate::PrivOwnedStr; const MATRIX_TO_BASE_URL: &str = "https://matrix.to/#/"; @@ -239,7 +239,7 @@ impl From<(&RoomAliasId, &EventId)> for MatrixId { #[derive(Debug, PartialEq, Eq)] pub struct MatrixToUri { id: MatrixId, - via: Vec>, + via: Vec, } impl MatrixToUri { @@ -253,7 +253,7 @@ impl MatrixToUri { } /// Matrix servers usable to route a `RoomId`. - pub fn via(&self) -> &[Box] { + pub fn via(&self) -> &[OwnedServerName] { &self.via } @@ -272,7 +272,7 @@ impl MatrixToUri { for (key, value) in url.query_pairs() { if key.as_ref() == "via" { - via.push(ServerName::parse(value)?); + via.push(value.parse()?); } else { return Err(MatrixToError::UnknownArgument.into()); } @@ -399,7 +399,7 @@ impl From> for UriAction { #[derive(Debug, PartialEq, Eq)] pub struct MatrixUri { id: MatrixId, - via: Vec>, + via: Vec, action: Option, } @@ -414,7 +414,7 @@ impl MatrixUri { } /// Matrix servers usable to route a `RoomId`. - pub fn via(&self) -> &[Box] { + pub fn via(&self) -> &[OwnedServerName] { &self.via } @@ -438,7 +438,7 @@ impl MatrixUri { for (key, value) in url.query_pairs() { if key.as_ref() == "via" { - via.push(ServerName::parse(value)?); + via.push(value.parse()?); } else if key.as_ref() == "action" { if action.is_some() { return Err(MatrixUriError::TooManyActions.into()); diff --git a/crates/ruma-common/src/push/condition.rs b/crates/ruma-common/src/push/condition.rs index 29ce560b..0789dd94 100644 --- a/crates/ruma-common/src/push/condition.rs +++ b/crates/ruma-common/src/push/condition.rs @@ -6,7 +6,7 @@ use serde_json::{to_value as to_json_value, value::Value as JsonValue}; use tracing::{instrument, warn}; 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; @@ -114,7 +114,7 @@ impl PushCondition { #[allow(clippy::exhaustive_structs)] pub struct PushConditionRoomCtx { /// The ID of the room. - pub room_id: Box, + pub room_id: OwnedRoomId, /// The number of members in the room. pub member_count: UInt, @@ -123,7 +123,7 @@ pub struct PushConditionRoomCtx { pub user_display_name: String, /// The power levels of the users of the room. - pub users_power_levels: BTreeMap, Int>, + pub users_power_levels: BTreeMap, /// The default power level of the users of the room. pub default_power_level: Int, diff --git a/crates/ruma-common/tests/api/conversions.rs b/crates/ruma-common/tests/api/conversions.rs index 704003d7..f92e7693 100644 --- a/crates/ruma-common/tests/api/conversions.rs +++ b/crates/ruma-common/tests/api/conversions.rs @@ -5,7 +5,7 @@ use ruma_common::{ ruma_api, IncomingRequest as _, MatrixVersion, OutgoingRequest as _, OutgoingRequestAppserviceExt, SendAccessToken, }, - user_id, UserId, + user_id, OwnedUserId, }; ruma_api! { @@ -29,7 +29,7 @@ ruma_api! { #[ruma_api(path)] pub bar: String, #[ruma_api(path)] - pub user: Box, + pub user: OwnedUserId, } response: { @@ -119,9 +119,9 @@ fn request_with_user_id_serde() { } 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! { metadata: { @@ -140,7 +140,7 @@ mod without_query { #[ruma_api(path)] pub bar: String, #[ruma_api(path)] - pub user: Box, + pub user: OwnedUserId, } response: { diff --git a/crates/ruma-common/tests/events/ui/04-event-sanity-check.rs b/crates/ruma-common/tests/events/ui/04-event-sanity-check.rs index 693e1ba9..9fd874e2 100644 --- a/crates/ruma-common/tests/events/ui/04-event-sanity-check.rs +++ b/crates/ruma-common/tests/events/ui/04-event-sanity-check.rs @@ -5,7 +5,7 @@ extern crate serde; use ruma_common::{ events::{StateEventContent, StateUnsigned}, - EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, + MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, }; use ruma_macros::Event; @@ -13,10 +13,10 @@ use ruma_macros::Event; #[derive(Clone, Debug, Event)] pub struct OriginalStateEvent { pub content: C, - pub event_id: Box, - pub sender: Box, + pub event_id: OwnedEventId, + pub sender: OwnedUserId, pub origin_server_ts: MilliSecondsSinceUnixEpoch, - pub room_id: Box, + pub room_id: OwnedRoomId, pub state_key: String, pub unsigned: StateUnsigned, } diff --git a/crates/ruma-common/tests/serde/empty_strings.rs b/crates/ruma-common/tests/serde/empty_strings.rs index c5bb4c0c..cc0d8c9f 100644 --- a/crates/ruma-common/tests/serde/empty_strings.rs +++ b/crates/ruma-common/tests/serde/empty_strings.rs @@ -49,14 +49,14 @@ mod string { } mod user { - use ruma_common::{user_id, UserId}; + use ruma_common::{user_id, OwnedUserId, UserId}; use serde::{Deserialize, Serialize}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; const CARL: &str = "@carl:example.com"; - fn carl() -> Box { - user_id!("@carl:example.com").to_owned() + fn carl() -> &'static UserId { + user_id!("@carl:example.com") } #[derive(Serialize, Deserialize, PartialEq, Debug)] @@ -66,7 +66,7 @@ mod user { deserialize_with = "ruma_common::serde::empty_string_as_none", serialize_with = "ruma_common::serde::none_as_empty_string" )] - x: Option>, + x: Option, } #[test] @@ -78,7 +78,7 @@ mod user { #[test] fn some_se() { - let decoded = User { x: Some(carl()) }; + let decoded = User { x: Some(carl().to_owned()) }; let encoded = json!({ "x": CARL }); assert_eq!(to_json_value(decoded).unwrap(), encoded); } @@ -100,7 +100,7 @@ mod user { #[test] fn some_de() { let encoded = json!({ "x": CARL }); - let decoded = User { x: Some(carl()) }; + let decoded = User { x: Some(carl().to_owned()) }; assert_eq!(from_json_value::(encoded).unwrap(), decoded); } } diff --git a/crates/ruma-federation-api/src/serde/pdu_process_response.rs b/crates/ruma-federation-api/src/serde/pdu_process_response.rs index 28a1509e..aae470bb 100644 --- a/crates/ruma-federation-api/src/serde/pdu_process_response.rs +++ b/crates/ruma-federation-api/src/serde/pdu_process_response.rs @@ -1,6 +1,6 @@ use std::{collections::BTreeMap, fmt}; -use ruma_common::EventId; +use ruma_common::OwnedEventId; use serde::{ de::{Deserializer, MapAccess, Visitor}, ser::{SerializeMap, Serializer}, @@ -14,7 +14,7 @@ struct WrappedError { } pub fn serialize( - response: &BTreeMap, Result<(), String>>, + response: &BTreeMap>, serializer: S, ) -> Result where @@ -36,14 +36,14 @@ where #[allow(clippy::type_complexity)] pub fn deserialize<'de, D>( deserializer: D, -) -> Result, Result<(), String>>, D::Error> +) -> Result>, D::Error> where D: Deserializer<'de>, { struct PduProcessResponseVisitor; impl<'de> Visitor<'de> for PduProcessResponseVisitor { - type Value = BTreeMap, Result<(), String>>; + type Value = BTreeMap>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("A map of EventIds to a map of optional errors") @@ -55,7 +55,7 @@ where { let mut map = BTreeMap::new(); - while let Some((key, value)) = access.next_entry::, WrappedError>()? { + while let Some((key, value)) = access.next_entry::()? { let v = match value.error { None => Ok(()), Some(error) => Err(error), @@ -73,14 +73,14 @@ where mod tests { 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 super::{deserialize, serialize}; #[test] fn serialize_error() { - let mut response: BTreeMap, Result<(), String>> = BTreeMap::new(); + let mut response: BTreeMap> = BTreeMap::new(); response.insert( event_id!("$someevent:matrix.org").to_owned(), Err("Some processing error.".into()), @@ -95,7 +95,7 @@ mod tests { #[test] fn serialize_ok() { - let mut response: BTreeMap, Result<(), String>> = BTreeMap::new(); + let mut response: BTreeMap> = BTreeMap::new(); response.insert(event_id!("$someevent:matrix.org").to_owned(), Ok(())); let serialized = serialize(&response, serde_json::value::Serializer).unwrap(); diff --git a/crates/ruma-federation-api/src/transactions/send_transaction_message.rs b/crates/ruma-federation-api/src/transactions/send_transaction_message.rs index 48d9a9da..46e617be 100644 --- a/crates/ruma-federation-api/src/transactions/send_transaction_message.rs +++ b/crates/ruma-federation-api/src/transactions/send_transaction_message.rs @@ -10,7 +10,8 @@ pub mod v1 { use std::collections::BTreeMap; 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; @@ -63,7 +64,7 @@ pub mod v1 { /// See [MSC3618](https://github.com/matrix-org/matrix-spec-proposals/pull/3618). #[cfg_attr(feature = "unstable-msc3618", serde(default))] #[serde(with = "crate::serde::pdu_process_response")] - pub pdus: BTreeMap, Result<(), String>>, + pub pdus: BTreeMap>, } } @@ -82,7 +83,7 @@ pub mod v1 { impl Response { /// Creates a new `Response` with the given PDUs. - pub fn new(pdus: BTreeMap, Result<(), String>>) -> Self { + pub fn new(pdus: BTreeMap>) -> Self { Self { pdus } } } diff --git a/crates/ruma-macros/src/events/event.rs b/crates/ruma-macros/src/events/event.rs index 6c3add34..5952c994 100644 --- a/crates/ruma-macros/src/events/event.rs +++ b/crates/ruma-macros/src/events/event.rs @@ -463,7 +463,7 @@ fn expand_sync_from_into_full( /// Convert this sync event into a full event, one with a room_id field. pub fn into_full_event( self, - room_id: ::std::boxed::Box<#ruma_common::RoomId>, + room_id: #ruma_common::OwnedRoomId, ) -> #full_struct #ty_gen { let Self { #( #fields, )* } = self; #full_struct { diff --git a/crates/ruma-macros/src/events/event_enum.rs b/crates/ruma-macros/src/events/event_enum.rs index ac6e1f0c..49010209 100644 --- a/crates/ruma-macros/src/events/event_enum.rs +++ b/crates/ruma-macros/src/events/event_enum.rs @@ -270,10 +270,7 @@ fn expand_into_full_event( #[automatically_derived] impl #ident { /// Convert this sync event into a full event (one with a `room_id` field). - pub fn into_full_event( - self, - room_id: ::std::boxed::Box<#ruma_common::RoomId>, - ) -> #full { + pub fn into_full_event(self, room_id: #ruma_common::OwnedRoomId) -> #full { match self { #( #self_variants(event) => { diff --git a/crates/ruma-macros/src/identifiers.rs b/crates/ruma-macros/src/identifiers.rs index fd30c009..290810bc 100644 --- a/crates/ruma-macros/src/identifiers.rs +++ b/crates/ruma-macros/src/identifiers.rs @@ -25,6 +25,7 @@ impl Parse for IdentifierInput { pub fn expand_id_zst(input: ItemStruct) -> syn::Result { let id = &input.ident; + let owned = format_ident!("Owned{}", id); let owned_decl = expand_owned_id(&input); @@ -115,10 +116,10 @@ pub fn expand_id_zst(input: ItemStruct) -> syn::Result { } 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 { - 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>, } + 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 { fn as_ref(&self) -> &#id #ty_generics { &*self.inner diff --git a/crates/ruma-signatures/src/error.rs b/crates/ruma-signatures/src/error.rs index f71f9b02..808a8ae2 100644 --- a/crates/ruma-signatures/src/error.rs +++ b/crates/ruma-signatures/src/error.rs @@ -1,4 +1,6 @@ -use ruma_common::{serde::Base64DecodeError, EventId, RoomVersionId, ServerName}; +use ruma_common::{ + serde::Base64DecodeError, EventId, OwnedEventId, OwnedServerName, RoomVersionId, +}; use thiserror::Error; /// `ruma-signature`'s error type, wraps a number of other error types. @@ -144,11 +146,11 @@ pub enum JsonType { pub enum VerificationError { /// For when a signature cannot be found for a `target`. #[error("Could not find signatures for {0:?}")] - SignatureNotFound(Box), + SignatureNotFound(OwnedServerName), /// For when a public key cannot be found for a `target`. #[error("Could not find public key for {0:?}")] - PublicKeyNotFound(Box), + PublicKeyNotFound(OwnedServerName), /// For when no public key matches the signature given. #[error("Not signed with any of the given public keys")] @@ -160,12 +162,12 @@ pub enum VerificationError { } impl VerificationError { - pub(crate) fn signature_not_found>>(target: T) -> Error { - Self::SignatureNotFound(target.into()).into() + pub(crate) fn signature_not_found(target: OwnedServerName) -> Error { + Self::SignatureNotFound(target).into() } - pub(crate) fn public_key_not_found>>(target: T) -> Error { - Self::PublicKeyNotFound(target.into()).into() + pub(crate) fn public_key_not_found(target: OwnedServerName) -> Error { + 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 /// embedded. #[error("Event Id {0:?} should have a server name for the given room version {1:?}")] - ServerNameFromEventIdByRoomVersion(Box, RoomVersionId), + ServerNameFromEventIdByRoomVersion(OwnedEventId, RoomVersionId), /// 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. diff --git a/crates/ruma-signatures/src/functions.rs b/crates/ruma-signatures/src/functions.rs index 34df4923..7b6ae0ea 100644 --- a/crates/ruma-signatures/src/functions.rs +++ b/crates/ruma-signatures/src/functions.rs @@ -10,7 +10,7 @@ use std::{ use base64::{encode_config, STANDARD_NO_PAD, URL_SAFE_NO_PAD}; use ruma_common::{ 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 sha2::{digest::Digest, Sha256}; @@ -803,7 +803,7 @@ fn object_retain_keys(object: &mut CanonicalJsonObject, keys: &[&str]) { fn servers_to_check_signatures( object: &CanonicalJsonObject, version: &RoomVersionId, -) -> Result>, Error> { +) -> Result, Error> { let mut servers_to_check = BTreeSet::new(); if !is_third_party_invite(object)? { diff --git a/crates/ruma-state-res/benches/state_res_bench.rs b/crates/ruma-state-res/benches/state_res_bench.rs index 47110b0a..6e268b26 100644 --- a/crates/ruma-state-res/benches/state_res_bench.rs +++ b/crates/ruma-state-res/benches/state_res_bench.rs @@ -30,7 +30,8 @@ use ruma_common::{ }, 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 serde_json::{ @@ -157,7 +158,7 @@ criterion_main!(benches); // IMPLEMENTATION DETAILS AHEAD // /////////////////////////////////////////////////////////////////////*/ -struct TestStore(HashMap, Arc>); +struct TestStore(HashMap>); #[allow(unused)] impl TestStore { @@ -230,7 +231,7 @@ impl TestStore { #[allow(clippy::type_complexity)] fn set_up( &mut self, - ) -> (StateMap>, StateMap>, StateMap>) { + ) -> (StateMap, StateMap, StateMap) { let create_event = to_pdu_event::<&EventId>( "CREATE", alice(), @@ -314,27 +315,27 @@ impl TestStore { } } -fn event_id(id: &str) -> Box { +fn event_id(id: &str) -> OwnedEventId { if id.contains('$') { return id.try_into().unwrap(); } format!("${}:foo", id).try_into().unwrap() } -fn alice() -> Box { - user_id!("@alice:foo").to_owned() +fn alice() -> &'static UserId { + user_id!("@alice:foo") } -fn bob() -> Box { - user_id!("@bob:foo").to_owned() +fn bob() -> &'static UserId { + user_id!("@bob:foo") } -fn charlie() -> Box { - user_id!("@charlie:foo").to_owned() +fn charlie() -> &'static UserId { + user_id!("@charlie:foo") } -fn ella() -> Box { - user_id!("@ella:foo").to_owned() +fn ella() -> &'static UserId { + user_id!("@ella:foo") } fn room_id() -> &'static RoomId { @@ -351,7 +352,7 @@ fn member_content_join() -> Box { fn to_pdu_event( id: &str, - sender: Box, + sender: &UserId, ev_type: RoomEventType, state_key: Option<&str>, content: Box, @@ -373,7 +374,7 @@ where event_id: id.try_into().unwrap(), rest: Pdu::RoomV3Pdu(RoomV3Pdu { room_id: room_id().to_owned(), - sender, + sender: sender.to_owned(), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), state_key, kind: ev_type, @@ -391,7 +392,7 @@ where // all graphs start with these input events #[allow(non_snake_case)] -fn INITIAL_EVENTS() -> HashMap, Arc> { +fn INITIAL_EVENTS() -> HashMap> { vec![ to_pdu_event::<&EventId>( "CREATE", @@ -406,7 +407,7 @@ fn INITIAL_EVENTS() -> HashMap, Arc> { "IMA", alice(), RoomEventType::RoomMember, - Some(alice().to_string().as_str()), + Some(alice().as_str()), member_content_join(), &["CREATE"], &["CREATE"], @@ -416,7 +417,7 @@ fn INITIAL_EVENTS() -> HashMap, Arc> { alice(), RoomEventType::RoomPowerLevels, Some(""), - to_raw_json_value(&json!({ "users": { alice().to_string(): 100 } })).unwrap(), + to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(), &["CREATE", "IMA"], &["IMA"], ), @@ -473,7 +474,7 @@ fn INITIAL_EVENTS() -> HashMap, Arc> { // all graphs start with these input events #[allow(non_snake_case)] -fn BAN_STATE_SET() -> HashMap, Arc> { +fn BAN_STATE_SET() -> HashMap> { vec![ to_pdu_event( "PA", @@ -531,14 +532,14 @@ impl EventTypeExt for &RoomEventType { mod event { use ruma_common::{ events::{pdu::Pdu, RoomEventType}, - EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, + MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId, }; use ruma_state_res::Event; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue as RawJsonValue; impl Event for PduEvent { - type Id = Box; + type Id = OwnedEventId; fn event_id(&self) -> &Self::Id { &self.event_id @@ -628,7 +629,7 @@ mod event { #[derive(Clone, Debug, Deserialize, Serialize)] pub struct PduEvent { - pub event_id: Box, + pub event_id: OwnedEventId, #[serde(flatten)] pub rest: Pdu, } diff --git a/crates/ruma-state-res/src/event_auth.rs b/crates/ruma-state-res/src/event_auth.rs index aa581d12..de19d813 100644 --- a/crates/ruma-state-res/src/event_auth.rs +++ b/crates/ruma-state-res/src/event_auth.rs @@ -1014,9 +1014,9 @@ mod tests { assert!(valid_membership_change( &RoomVersion::V6, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, @@ -1056,9 +1056,9 @@ mod tests { assert!(!valid_membership_change( &RoomVersion::V6, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, @@ -1098,9 +1098,9 @@ mod tests { assert!(valid_membership_change( &RoomVersion::V6, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, @@ -1140,9 +1140,9 @@ mod tests { assert!(!valid_membership_change( &RoomVersion::V6, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, @@ -1176,7 +1176,7 @@ mod tests { ); 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 .values() @@ -1199,15 +1199,15 @@ mod tests { assert!(valid_membership_change( &RoomVersion::V9, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, fetch_state(StateEventType::RoomPowerLevels, "".to_owned()), fetch_state(StateEventType::RoomJoinRules, "".to_owned()), - Some(&alice()), + Some(alice()), &MembershipState::Join, fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(), ) @@ -1215,15 +1215,15 @@ mod tests { assert!(!valid_membership_change( &RoomVersion::V9, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, fetch_state(StateEventType::RoomPowerLevels, "".to_owned()), fetch_state(StateEventType::RoomJoinRules, "".to_owned()), - Some(&ella()), + Some(ella()), &MembershipState::Leave, fetch_state(StateEventType::RoomCreate, "".to_owned()).unwrap(), ) @@ -1266,9 +1266,9 @@ mod tests { assert!(valid_membership_change( &RoomVersion::V7, - &target_user, + target_user, fetch_state(StateEventType::RoomMember, target_user.to_string()), - &sender, + sender, fetch_state(StateEventType::RoomMember, sender.to_string()), &requester, None::, diff --git a/crates/ruma-state-res/src/lib.rs b/crates/ruma-state-res/src/lib.rs index 72162897..876daa90 100644 --- a/crates/ruma-state-res/src/lib.rs +++ b/crates/ruma-state-res/src/lib.rs @@ -667,7 +667,7 @@ mod tests { room::join_rules::{JoinRule, RoomJoinRulesEventContent}, RoomEventType, StateEventType, }, - EventId, MilliSecondsSinceUnixEpoch, RoomVersionId, + MilliSecondsSinceUnixEpoch, OwnedEventId, RoomVersionId, }; use serde_json::{json, value::to_raw_value as to_raw_json_value}; use tracing::debug; @@ -692,7 +692,7 @@ mod tests { .map(|ev| (ev.event_type().with_state_key(ev.state_key().unwrap()), ev.clone())) .collect::>(); - let auth_chain: HashSet> = HashSet::new(); + let auth_chain: HashSet = HashSet::new(); let power_events = event_map .values() @@ -1222,7 +1222,7 @@ mod tests { } #[allow(non_snake_case)] - fn BAN_STATE_SET() -> HashMap, Arc> { + fn BAN_STATE_SET() -> HashMap> { vec![ to_pdu_event( "PA", @@ -1267,7 +1267,7 @@ mod tests { } #[allow(non_snake_case)] - fn JOIN_RULE() -> HashMap, Arc> { + fn JOIN_RULE() -> HashMap> { vec![ to_pdu_event( "JR", diff --git a/crates/ruma-state-res/src/test_utils.rs b/crates/ruma-state-res/src/test_utils.rs index cbcc772c..196d9a1d 100644 --- a/crates/ruma-state-res/src/test_utils.rs +++ b/crates/ruma-state-res/src/test_utils.rs @@ -19,7 +19,8 @@ use ruma_common::{ }, RoomEventType, }, - room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, UserId, + room_id, user_id, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, RoomVersionId, + UserId, }; use serde_json::{ json, @@ -35,8 +36,8 @@ static SERVER_TIMESTAMP: AtomicU64 = AtomicU64::new(0); pub fn do_check( events: &[Arc], - edges: Vec>>, - expected_state_ids: Vec>, + edges: Vec>, + expected_state_ids: Vec, ) { // To activate logging use `RUST_LOG=debug cargo t` @@ -76,10 +77,10 @@ pub fn do_check( } } - // event_id -> OriginalStateEvent - let mut event_map: HashMap, Arc> = HashMap::new(); - // event_id -> StateMap> - let mut state_at_event: HashMap, StateMap>> = HashMap::new(); + // event_id -> PduEvent + let mut event_map: HashMap> = HashMap::new(); + // event_id -> StateMap + let mut state_at_event: HashMap> = HashMap::new(); // Resolve the current state and add it to the state_at_event map then continue // on in "time" @@ -93,7 +94,7 @@ pub fn do_check( let prev_events = graph.get(&node).unwrap(); - let state_before: StateMap> = if prev_events.is_empty() { + let state_before: StateMap = if prev_events.is_empty() { HashMap::new() } else if prev_events.len() == 1 { 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 event = to_pdu_event( e.event_id().as_str(), - e.sender().to_owned(), + e.sender(), e.event_type().clone(), e.state_key(), e.content().to_owned(), @@ -201,13 +202,13 @@ pub fn do_check( && **k != ("m.room.message".into(), "dummy".to_owned()) }) .map(|(k, v)| (k.clone(), v.clone())) - .collect::>>(); + .collect::>(); assert_eq!(expected_state, end_state); } #[allow(clippy::exhaustive_structs)] -pub struct TestStore(pub HashMap, Arc>); +pub struct TestStore(pub HashMap>); impl TestStore { pub fn get_event(&self, _: &RoomId, event_id: &EventId) -> Result> { @@ -248,7 +249,7 @@ impl TestStore { impl TestStore { pub fn set_up( &mut self, - ) -> (StateMap>, StateMap>, StateMap>) { + ) -> (StateMap, StateMap, StateMap) { let create_event = to_pdu_event::<&EventId>( "CREATE", alice(), @@ -265,7 +266,7 @@ impl TestStore { "IMA", alice(), RoomEventType::RoomMember, - Some(alice().to_string().as_str()), + Some(alice().as_str()), member_content_join(), &[cre.clone()], &[cre.clone()], @@ -289,7 +290,7 @@ impl TestStore { "IMB", bob(), RoomEventType::RoomMember, - Some(bob().to_string().as_str()), + Some(bob().as_str()), member_content_join(), &[cre.clone(), join_rules.event_id().to_owned()], &[join_rules.event_id().to_owned()], @@ -300,7 +301,7 @@ impl TestStore { "IMC", charlie(), RoomEventType::RoomMember, - Some(charlie().to_string().as_str()), + Some(charlie().as_str()), member_content_join(), &[cre, join_rules.event_id().to_owned()], &[join_rules.event_id().to_owned()], @@ -332,7 +333,7 @@ impl TestStore { } } -pub fn event_id(id: &str) -> Box { +pub fn event_id(id: &str) -> OwnedEventId { if id.contains('$') { return id.try_into().unwrap(); } @@ -340,24 +341,24 @@ pub fn event_id(id: &str) -> Box { format!("${}:foo", id).try_into().unwrap() } -pub fn alice() -> Box { - user_id!("@alice:foo").to_owned() +pub fn alice() -> &'static UserId { + user_id!("@alice:foo") } -pub fn bob() -> Box { - user_id!("@bob:foo").to_owned() +pub fn bob() -> &'static UserId { + user_id!("@bob:foo") } -pub fn charlie() -> Box { - user_id!("@charlie:foo").to_owned() +pub fn charlie() -> &'static UserId { + user_id!("@charlie:foo") } -pub fn ella() -> Box { - user_id!("@ella:foo").to_owned() +pub fn ella() -> &'static UserId { + user_id!("@ella:foo") } -pub fn zara() -> Box { - user_id!("@zara:foo").to_owned() +pub fn zara() -> &'static UserId { + user_id!("@zara:foo") } pub fn room_id() -> &'static RoomId { @@ -374,7 +375,7 @@ pub fn member_content_join() -> Box { pub fn to_init_pdu_event( id: &str, - sender: Box, + sender: &UserId, ev_type: RoomEventType, state_key: Option<&str>, content: Box, @@ -387,7 +388,7 @@ pub fn to_init_pdu_event( event_id: id.try_into().unwrap(), rest: Pdu::RoomV3Pdu(RoomV3Pdu { room_id: room_id().to_owned(), - sender, + sender: sender.to_owned(), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), state_key, kind: ev_type, @@ -405,7 +406,7 @@ pub fn to_init_pdu_event( pub fn to_pdu_event( id: &str, - sender: Box, + sender: &UserId, ev_type: RoomEventType, state_key: Option<&str>, content: Box, @@ -425,7 +426,7 @@ where event_id: id.try_into().unwrap(), rest: Pdu::RoomV3Pdu(RoomV3Pdu { room_id: room_id().to_owned(), - sender, + sender: sender.to_owned(), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), state_key, kind: ev_type, @@ -443,7 +444,7 @@ where // all graphs start with these input events #[allow(non_snake_case)] -pub fn INITIAL_EVENTS() -> HashMap, Arc> { +pub fn INITIAL_EVENTS() -> HashMap> { vec![ to_pdu_event::<&EventId>( "CREATE", @@ -458,7 +459,7 @@ pub fn INITIAL_EVENTS() -> HashMap, Arc> { "IMA", alice(), RoomEventType::RoomMember, - Some(alice().to_string().as_str()), + Some(alice().as_str()), member_content_join(), &["CREATE"], &["CREATE"], @@ -468,7 +469,7 @@ pub fn INITIAL_EVENTS() -> HashMap, Arc> { alice(), RoomEventType::RoomPowerLevels, Some(""), - to_raw_json_value(&json!({ "users": { alice().to_string(): 100 } })).unwrap(), + to_raw_json_value(&json!({ "users": { alice(): 100 } })).unwrap(), &["CREATE", "IMA"], &["IMA"], ), @@ -485,7 +486,7 @@ pub fn INITIAL_EVENTS() -> HashMap, Arc> { "IMB", bob(), RoomEventType::RoomMember, - Some(bob().to_string().as_str()), + Some(bob().as_str()), member_content_join(), &["CREATE", "IJR", "IPOWER"], &["IJR"], @@ -494,7 +495,7 @@ pub fn INITIAL_EVENTS() -> HashMap, Arc> { "IMC", charlie(), RoomEventType::RoomMember, - Some(charlie().to_string().as_str()), + Some(charlie().as_str()), member_content_join(), &["CREATE", "IJR", "IPOWER"], &["IMB"], @@ -525,7 +526,7 @@ pub fn INITIAL_EVENTS() -> HashMap, Arc> { // all graphs start with these input events #[allow(non_snake_case)] -pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap, Arc> { +pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap> { vec![to_pdu_event::<&EventId>( "CREATE", alice(), @@ -541,7 +542,7 @@ pub fn INITIAL_EVENTS_CREATE_ROOM() -> HashMap, Arc> { } #[allow(non_snake_case)] -pub fn INITIAL_EDGES() -> Vec> { +pub fn INITIAL_EDGES() -> Vec { vec!["START", "IMC", "IMB", "IJR", "IPOWER", "IMA", "CREATE"] .into_iter() .map(event_id) @@ -551,7 +552,7 @@ pub fn INITIAL_EDGES() -> Vec> { pub mod event { use ruma_common::{ events::{pdu::Pdu, RoomEventType}, - EventId, MilliSecondsSinceUnixEpoch, RoomId, UserId, + MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId, }; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue as RawJsonValue; @@ -559,7 +560,7 @@ pub mod event { use crate::Event; impl Event for PduEvent { - type Id = Box; + type Id = OwnedEventId; fn event_id(&self) -> &Self::Id { &self.event_id @@ -650,7 +651,7 @@ pub mod event { #[derive(Clone, Debug, Deserialize, Serialize)] #[allow(clippy::exhaustive_structs)] pub struct PduEvent { - pub event_id: Box, + pub event_id: OwnedEventId, #[serde(flatten)] pub rest: Pdu, }