identifiers: Make RoomId a DST

This commit is contained in:
Jonas Platte 2021-09-19 19:34:14 +02:00
parent b0db5e94e1
commit 2d4dbfe42f
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
64 changed files with 177 additions and 197 deletions

View File

@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
/// A request to create a new room alias. /// A request to create a new room alias.
#[derive(Debug)] #[derive(Debug)]
pub struct Request { pub struct Request {
pub room_id: RoomId, // body pub room_id: Box<RoomId>, // body
pub room_alias: Box<RoomAliasId>, // path pub room_alias: Box<RoomAliasId>, // path
} }
@ -88,7 +88,7 @@ impl IncomingRequest for Request {
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct RequestBody { struct RequestBody {
room_id: RoomId, room_id: Box<RoomId>,
} }
/// The response to a request to create a new room alias. /// The response to a request to create a new room alias.

View File

@ -20,7 +20,7 @@ ruma_api! {
/// Room ID of the room to add or remove from the directory. /// Room ID of the room to add or remove from the directory.
#[ruma_api(path)] #[ruma_api(path)]
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// Whether the room should be visible (public) in the directory or not (private). /// Whether the room should be visible (public) in the directory or not (private).
pub visibility: Visibility, pub visibility: Visibility,

View File

@ -68,7 +68,7 @@ impl IncomingRequest {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct EventDeHelper { struct EventDeHelper {
room_id: Option<RoomId>, room_id: Option<Box<RoomId>>,
} }
let mut response = sync_events::Response::new(next_batch.into()); let mut response = sync_events::Response::new(next_batch.into());
@ -138,7 +138,7 @@ mod helper_tests {
incoming_request.try_into_sync_response(txn_id).unwrap(); incoming_request.try_into_sync_response(txn_id).unwrap();
let response_rooms_join = let response_rooms_join =
response.rooms.join.get(&room_id!("!roomid:room.com")).expect("joined room response"); response.rooms.join.get(room_id!("!roomid:room.com")).expect("joined room response");
assert_eq!(response_rooms_join.timeline.events.len(), 2); assert_eq!(response_rooms_join.timeline.events.len(), 2);
} }

View File

@ -21,7 +21,7 @@ ruma_api! {
response: { response: {
/// The room ID for this room alias. /// The room ID for this room alias.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// A list of servers that are aware of this room ID. /// A list of servers that are aware of this room ID.
pub servers: Vec<Box<ServerName>>, pub servers: Vec<Box<ServerName>>,
@ -39,7 +39,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room id and servers /// Creates a new `Response` with the given room id and servers
pub fn new(room_id: RoomId, servers: Vec<Box<ServerName>>) -> Self { pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers } Self { room_id, servers }
} }
} }

View File

@ -26,7 +26,7 @@ ruma_api! {
pub version: &'a str, pub version: &'a str,
/// A map from room IDs to session IDs to key data. /// A map from room IDs to session IDs to key data.
pub rooms: BTreeMap<RoomId, RoomKeyBackup>, pub rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>,
} }
response: { response: {
@ -45,7 +45,7 @@ ruma_api! {
impl<'a> Request<'a> { impl<'a> Request<'a> {
/// Creates a new `Request` with the given version and room key backups. /// Creates a new `Request` with the given version and room key backups.
pub fn new(version: &'a str, rooms: BTreeMap<RoomId, RoomKeyBackup>) -> Self { pub fn new(version: &'a str, rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>) -> Self {
Self { version, rooms } Self { version, rooms }
} }
} }

View File

@ -27,7 +27,7 @@ ruma_api! {
response: { response: {
/// A map from room IDs to session IDs to key data. /// A map from room IDs to session IDs to key data.
pub rooms: BTreeMap<RoomId, RoomKeyBackup>, pub rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>,
} }
error: crate::Error error: crate::Error
@ -42,7 +42,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room key backups. /// Creates a new `Response` with the given room key backups.
pub fn new(rooms: BTreeMap<RoomId, RoomKeyBackup>) -> Self { pub fn new(rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>) -> Self {
Self { rooms } Self { rooms }
} }
} }

View File

@ -31,7 +31,7 @@ pub struct PublicRoomsChunk {
pub num_joined_members: UInt, pub num_joined_members: UInt,
/// The ID of the room. /// The ID of the room.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The topic of the room, if any. /// The topic of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -68,7 +68,7 @@ impl PublicRoomsChunk {
/// All other fields will be propagated with default values (an empty list of aliases, `None` /// All other fields will be propagated with default values (an empty list of aliases, `None`
/// for all `Option`al fields and `false` for all boolean fields), which should be overridden; /// for all `Option`al fields and `false` for all boolean fields), which should be overridden;
/// the `assign!` macro from the `assign` crate can simplify this. /// the `assign!` macro from the `assign` crate can simplify this.
pub fn new(room_id: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { Self {
room_id, room_id,
aliases: Vec::new(), aliases: Vec::new(),

View File

@ -63,7 +63,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 [RoomId], pub not_rooms: &'a [Box<RoomId>],
/// 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")]
@ -73,7 +73,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 [RoomId]>, pub rooms: Option<&'a [Box<RoomId>]>,
/// A list of sender IDs to exclude. /// A list of sender IDs to exclude.
/// ///
@ -186,14 +186,14 @@ pub struct RoomFilter<'a> {
/// it is listed in the 'rooms' filter. This filter is applied before the filters in /// it is listed in the 'rooms' filter. This filter is applied before the filters in
/// `ephemeral`, `state`, `timeline` or `account_data`. /// `ephemeral`, `state`, `timeline` or `account_data`.
#[serde(default, skip_serializing_if = "<[_]>::is_empty")] #[serde(default, skip_serializing_if = "<[_]>::is_empty")]
pub not_rooms: &'a [RoomId], pub not_rooms: &'a [Box<RoomId>],
/// A list of room IDs to include. /// A list of room IDs to include.
/// ///
/// If this list is absent then all rooms are included. This filter is applied before the /// If this list is absent then all rooms are included. This filter is applied before the
/// filters in `ephemeral`, `state`, `timeline` or `account_data`. /// filters in `ephemeral`, `state`, `timeline` or `account_data`.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub rooms: Option<&'a [RoomId]>, pub rooms: Option<&'a [Box<RoomId>]>,
} }
impl<'a> RoomFilter<'a> { impl<'a> RoomFilter<'a> {

View File

@ -32,7 +32,7 @@ ruma_api! {
response: { response: {
/// The room that the user knocked on. /// The room that the user knocked on.
pub room_id: RoomId, pub room_id: Box<RoomId>,
} }
} }
@ -45,7 +45,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room ID. /// Creates a new `Response` with the given room ID.
pub fn new(room_id: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id } Self { room_id }
} }
} }

View File

@ -33,7 +33,7 @@ ruma_api! {
response: { response: {
/// The room that the user joined. /// The room that the user joined.
pub room_id: RoomId, pub room_id: Box<RoomId>,
} }
error: crate::Error error: crate::Error
@ -53,7 +53,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room id. /// Creates a new `Response` with the given room id.
pub fn new(room_id: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id } Self { room_id }
} }
} }

View File

@ -40,7 +40,7 @@ ruma_api! {
response: { response: {
/// The room that the user joined. /// The room that the user joined.
pub room_id: RoomId, pub room_id: Box<RoomId>,
} }
error: crate::Error error: crate::Error
@ -61,7 +61,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room ID. /// Creates a new `Response` with the given room ID.
pub fn new(room_id: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id } Self { room_id }
} }
} }

View File

@ -19,7 +19,7 @@ ruma_api! {
response: { response: {
/// A list of the rooms the user is in, i.e. the ID of each room in /// A list of the rooms the user is in, i.e. the ID of each room in
/// which the user has joined membership. /// which the user has joined membership.
pub joined_rooms: Vec<RoomId>, pub joined_rooms: Vec<Box<RoomId>>,
} }
error: crate::Error error: crate::Error
@ -34,7 +34,7 @@ impl Request {
impl Response { impl Response {
/// Creates a new `Response` with the given joined rooms. /// Creates a new `Response` with the given joined rooms.
pub fn new(joined_rooms: Vec<RoomId>) -> Self { pub fn new(joined_rooms: Vec<Box<RoomId>>) -> Self {
Self { joined_rooms } Self { joined_rooms }
} }
} }

View File

@ -144,20 +144,20 @@ mod tests {
#[test] #[test]
fn serialize_some_room_event_filter() { fn serialize_some_room_event_filter() {
let room_id = room_id!("!roomid:example.org"); let room_id = room_id!("!roomid:example.org");
let rooms = &[room_id.clone()]; let rooms = &[room_id.to_owned()];
let filter = RoomEventFilter { let filter = RoomEventFilter {
lazy_load_options: LazyLoadOptions::Enabled { include_redundant_members: true }, lazy_load_options: LazyLoadOptions::Enabled { include_redundant_members: true },
rooms: Some(rooms), rooms: Some(rooms),
not_rooms: &[ not_rooms: &[
room_id!("!room:example.org"), room_id!("!room:example.org").to_owned(),
room_id!("!room2:example.org"), room_id!("!room2:example.org").to_owned(),
room_id!("!room3:example.org"), room_id!("!room3:example.org").to_owned(),
], ],
not_types: &["type".into()], not_types: &["type".into()],
..Default::default() ..Default::default()
}; };
let req = Request { let req = Request {
room_id: &room_id, room_id,
from: "token", from: "token",
to: Some("token2"), to: Some("token2"),
dir: Direction::Backward, dir: Direction::Backward,
@ -185,7 +185,7 @@ mod tests {
fn serialize_none_room_event_filter() { fn serialize_none_room_event_filter() {
let room_id = room_id!("!roomid:example.org"); let room_id = room_id!("!roomid:example.org");
let req = Request { let req = Request {
room_id: &room_id, room_id,
from: "token", from: "token",
to: Some("token2"), to: Some("token2"),
dir: Direction::Backward, dir: Direction::Backward,
@ -206,7 +206,7 @@ mod tests {
fn serialize_default_room_event_filter() { fn serialize_default_room_event_filter() {
let room_id = room_id!("!roomid:example.org"); let room_id = room_id!("!roomid:example.org");
let req = Request { let req = Request {
room_id: &room_id, room_id,
from: "token", from: "token",
to: Some("token2"), to: Some("token2"),
dir: Direction::Backward, dir: Direction::Backward,

View File

@ -88,7 +88,7 @@ pub struct Notification {
pub read: bool, pub read: bool,
/// The ID of the room in which the event was posted. /// The ID of the room in which the event was posted.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The time at which the event notification was sent. /// The time at which the event notification was sent.
pub ts: MilliSecondsSinceUnixEpoch, pub ts: MilliSecondsSinceUnixEpoch,
@ -101,7 +101,7 @@ impl Notification {
actions: Vec<Action>, actions: Vec<Action>,
event: Raw<AnySyncRoomEvent>, event: Raw<AnySyncRoomEvent>,
read: bool, read: bool,
room_id: RoomId, room_id: Box<RoomId>,
ts: MilliSecondsSinceUnixEpoch, ts: MilliSecondsSinceUnixEpoch,
) -> Self { ) -> Self {
Self { actions, event, profile_tag: None, read, room_id, ts } Self { actions, event, profile_tag: None, read, room_id, ts }

View File

@ -92,7 +92,7 @@ ruma_api! {
response: { response: {
/// The created room's ID. /// The created room's ID.
pub room_id: RoomId, pub room_id: Box<RoomId>,
} }
error: crate::Error error: crate::Error
@ -107,7 +107,7 @@ impl Request<'_> {
impl Response { impl Response {
/// Creates a new `Response` with the given room id. /// Creates a new `Response` with the given room id.
pub fn new(room_id: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id } Self { room_id }
} }
} }

View File

@ -24,7 +24,7 @@ ruma_api! {
response: { response: {
/// ID of the new room. /// ID of the new room.
pub replacement_room: RoomId, pub replacement_room: Box<RoomId>,
} }
error: crate::Error error: crate::Error
@ -39,7 +39,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room ID. /// Creates a new `Response` with the given room ID.
pub fn new(replacement_room: RoomId) -> Self { pub fn new(replacement_room: Box<RoomId>) -> Self {
Self { replacement_room } Self { replacement_room }
} }
} }

View File

@ -373,7 +373,7 @@ pub struct ResultRoomEvents {
/// ///
/// This is included if the request had the `include_state` key set with a value of `true`. /// This is included if the request had the `include_state` key set with a value of `true`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub state: BTreeMap<RoomId, Vec<Raw<AnyStateEvent>>>, pub state: BTreeMap<Box<RoomId>, Vec<Raw<AnyStateEvent>>>,
/// List of words which should be highlighted, useful for stemming which may /// List of words which should be highlighted, useful for stemming which may
/// change the query terms. /// change the query terms.
@ -498,7 +498,7 @@ impl UserProfile {
#[allow(clippy::exhaustive_enums)] #[allow(clippy::exhaustive_enums)]
pub enum RoomIdOrUserId { pub enum RoomIdOrUserId {
/// Represents a room ID. /// Represents a room ID.
RoomId(RoomId), RoomId(Box<RoomId>),
/// Represents a user ID. /// Represents a user ID.
UserId(UserId), UserId(UserId),

View File

@ -123,7 +123,7 @@ impl ruma_api::IncomingRequest for IncomingRequest {
let decoded = let decoded =
percent_encoding::percent_decode(path_segments[4].as_bytes()).decode_utf8()?; percent_encoding::percent_decode(path_segments[4].as_bytes()).decode_utf8()?;
RoomId::try_from(&*decoded)? Box::<RoomId>::try_from(&*decoded)?
}; };
let event_type = { let event_type = {

View File

@ -149,7 +149,7 @@ impl ruma_api::IncomingRequest for IncomingRequest {
let decoded = let decoded =
percent_encoding::percent_decode(path_segments[4].as_bytes()).decode_utf8()?; percent_encoding::percent_decode(path_segments[4].as_bytes()).decode_utf8()?;
RoomId::try_from(&*decoded)? Box::<RoomId>::try_from(&*decoded)?
}; };
let event_type = percent_encoding::percent_decode(path_segments[6].as_bytes()) let event_type = percent_encoding::percent_decode(path_segments[6].as_bytes())

View File

@ -162,20 +162,20 @@ impl<'a> From<&'a str> for Filter<'a> {
pub struct Rooms { pub struct Rooms {
/// The rooms that the user has left or been banned from. /// The rooms that the user has left or been banned from.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub leave: BTreeMap<RoomId, LeftRoom>, pub leave: BTreeMap<Box<RoomId>, LeftRoom>,
/// The rooms that the user has joined. /// The rooms that the user has joined.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub join: BTreeMap<RoomId, JoinedRoom>, pub join: BTreeMap<Box<RoomId>, JoinedRoom>,
/// The rooms that the user has been invited to. /// The rooms that the user has been invited to.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub invite: BTreeMap<RoomId, InvitedRoom>, pub invite: BTreeMap<Box<RoomId>, InvitedRoom>,
/// The rooms that the user has knocked on. /// The rooms that the user has knocked on.
#[cfg(feature = "unstable-pre-spec")] #[cfg(feature = "unstable-pre-spec")]
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub knock: BTreeMap<RoomId, KnockedRoom>, pub knock: BTreeMap<Box<RoomId>, KnockedRoom>,
} }
impl Rooms { impl Rooms {

View File

@ -35,7 +35,7 @@ pub struct PublicRoomsChunk {
pub num_joined_members: UInt, pub num_joined_members: UInt,
/// The ID of the room. /// The ID of the room.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The topic of the room, if any. /// The topic of the room, if any.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -72,7 +72,7 @@ pub struct PublicRoomsChunkInit {
pub num_joined_members: UInt, pub num_joined_members: UInt,
/// The ID of the room. /// The ID of the room.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// Whether the room may be viewed by guest users without joining. /// Whether the room may be viewed by guest users without joining.
pub world_readable: bool, pub world_readable: bool,

View File

@ -966,7 +966,7 @@ mod tests {
let set = Ruleset::server_default(&user_id!("@jolly_jumper:server.name")); let set = Ruleset::server_default(&user_id!("@jolly_jumper:server.name"));
let context_one_to_one = &PushConditionRoomCtx { let context_one_to_one = &PushConditionRoomCtx {
room_id: room_id!("!dm:server.name"), room_id: room_id!("!dm:server.name").to_owned(),
member_count: 2_u32.into(), member_count: 2_u32.into(),
user_display_name: "Jolly Jumper".into(), user_display_name: "Jolly Jumper".into(),
users_power_levels: BTreeMap::new(), users_power_levels: BTreeMap::new(),
@ -975,7 +975,7 @@ mod tests {
}; };
let context_public_room = &PushConditionRoomCtx { let context_public_room = &PushConditionRoomCtx {
room_id: room_id!("!far_west:server.name"), room_id: room_id!("!far_west:server.name").to_owned(),
member_count: 100_u32.into(), member_count: 100_u32.into(),
user_display_name: "Jolly Jumper".into(), user_display_name: "Jolly Jumper".into(),
users_power_levels: BTreeMap::new(), users_power_levels: BTreeMap::new(),
@ -1065,7 +1065,7 @@ mod tests {
#[test] #[test]
fn custom_ruleset_applies() { fn custom_ruleset_applies() {
let context_one_to_one = &PushConditionRoomCtx { let context_one_to_one = &PushConditionRoomCtx {
room_id: room_id!("!dm:server.name"), room_id: room_id!("!dm:server.name").to_owned(),
member_count: 2_u32.into(), member_count: 2_u32.into(),
user_display_name: "Jolly Jumper".into(), user_display_name: "Jolly Jumper".into(),
users_power_levels: BTreeMap::new(), users_power_levels: BTreeMap::new(),

View File

@ -116,7 +116,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: RoomId, pub room_id: Box<RoomId>,
/// The number of members in the room. /// The number of members in the room.
pub member_count: UInt, pub member_count: UInt,
@ -484,7 +484,7 @@ mod tests {
users_power_levels.insert(first_sender, 25.into()); users_power_levels.insert(first_sender, 25.into());
let context = PushConditionRoomCtx { let context = PushConditionRoomCtx {
room_id: room_id!("!room:server.name"), room_id: room_id!("!room:server.name").to_owned(),
member_count: 3_u8.into(), member_count: 3_u8.into(),
user_display_name: "Groovy Gorilla".into(), user_display_name: "Groovy Gorilla".into(),
users_power_levels, users_power_levels,

View File

@ -509,7 +509,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: #ruma_identifiers::RoomId, room_id: ::std::boxed::Box<#ruma_identifiers::RoomId>,
) -> #full_struct #ty_gen { ) -> #full_struct #ty_gen {
let Self { #( #fields, )* } = self; let Self { #( #fields, )* } = self;
#full_struct { #full_struct {

View File

@ -256,7 +256,7 @@ fn expand_into_full_event(
/// 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: #ruma_identifiers::RoomId room_id: ::std::boxed::Box<#ruma_identifiers::RoomId>,
) -> #full { ) -> #full {
match self { match self {
#( #(

View File

@ -18,10 +18,10 @@ use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)] #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[allow(clippy::exhaustive_structs)] #[allow(clippy::exhaustive_structs)]
#[ruma_event(type = "m.direct", kind = GlobalAccountData)] #[ruma_event(type = "m.direct", kind = GlobalAccountData)]
pub struct DirectEventContent(pub BTreeMap<UserId, Vec<RoomId>>); pub struct DirectEventContent(pub BTreeMap<UserId, Vec<Box<RoomId>>>);
impl Deref for DirectEventContent { impl Deref for DirectEventContent {
type Target = BTreeMap<UserId, Vec<RoomId>>; type Target = BTreeMap<UserId, Vec<Box<RoomId>>>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.0 &self.0

View File

@ -182,7 +182,7 @@ impl AnySyncRoomEvent {
room_ev_accessor!(sender: &UserId); room_ev_accessor!(sender: &UserId);
/// 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: RoomId) -> AnyRoomEvent { pub fn into_full_event(self, room_id: Box<RoomId>) -> AnyRoomEvent {
match self { match self {
Self::Message(ev) => AnyRoomEvent::Message(ev.into_full_event(room_id)), Self::Message(ev) => AnyRoomEvent::Message(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

@ -32,7 +32,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: RoomId, pub room_id: Box<RoomId>,
} }
/// An ephemeral room event without a `room_id`. /// An ephemeral room event without a `room_id`.
@ -61,7 +61,7 @@ pub struct MessageEvent<C: MessageEventContent> {
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: RoomId, pub room_id: Box<RoomId>,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: Unsigned, pub unsigned: Unsigned,
@ -108,7 +108,7 @@ pub struct RedactedMessageEvent<C: RedactedMessageEventContent> {
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: RoomId, pub room_id: Box<RoomId>,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: RedactedUnsigned, pub unsigned: RedactedUnsigned,
@ -155,7 +155,7 @@ pub struct StateEvent<C: StateEventContent> {
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: RoomId, pub room_id: Box<RoomId>,
/// 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.
/// ///
@ -252,7 +252,7 @@ pub struct RedactedStateEvent<C: RedactedStateEventContent> {
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: RoomId, pub room_id: Box<RoomId>,
/// 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.
/// ///
@ -335,5 +335,5 @@ pub struct DecryptedMegolmV1Event<C: MessageEventContent> {
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: RoomId, pub room_id: Box<RoomId>,
} }

View File

@ -16,7 +16,7 @@ pub struct ToDeviceForwardedRoomKeyEventContent {
pub algorithm: EventEncryptionAlgorithm, pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used. /// The room where the key is used.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The Curve25519 key of the device which initiated the session originally. /// The Curve25519 key of the device which initiated the session originally.
pub sender_key: String, pub sender_key: String,
@ -54,7 +54,7 @@ pub struct ToDeviceForwardedRoomKeyEventContentInit {
pub algorithm: EventEncryptionAlgorithm, pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used. /// The room where the key is used.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The Curve25519 key of the device which initiated the session originally. /// The Curve25519 key of the device which initiated the session originally.
pub sender_key: String, pub sender_key: String,

View File

@ -38,7 +38,7 @@ pub struct RoomV1Pdu {
pub event_id: Box<EventId>, pub event_id: Box<EventId>,
/// The room this event belongs to. /// The room this event belongs to.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The user id of the user who sent this event. /// The user id of the user who sent this event.
pub sender: UserId, pub sender: UserId,
@ -97,7 +97,7 @@ 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: RoomId, pub room_id: Box<RoomId>,
/// The user id of the user who sent this event. /// The user id of the user who sent this event.
pub sender: UserId, pub sender: UserId,

View File

@ -35,7 +35,7 @@ mod tests {
event_id: event_id!("$143273582443PhrSn:example.org").to_owned(), event_id: event_id!("$143273582443PhrSn:example.org").to_owned(),
sender: user_id!("@example:example.org"), sender: user_id!("@example:example.org"),
origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_735_824_653_u64.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(1_432_735_824_653_u64.try_into().unwrap()),
room_id: room_id!("!jEsUZKDJdhlrceRyVU:example.org"), room_id: room_id!("!jEsUZKDJdhlrceRyVU:example.org").to_owned(),
state_key: "rule:#*:example.org".into(), state_key: "rule:#*:example.org".into(),
prev_content: None, prev_content: None,
unsigned: Unsigned { unsigned: Unsigned {

View File

@ -54,7 +54,7 @@ mod tests {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: None, prev_content: None,
room_id: room_id!("!dummy:example.com"), room_id: room_id!("!dummy:example.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),

View File

@ -87,7 +87,7 @@ impl RoomType {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct PreviousRoom { pub struct PreviousRoom {
/// The ID of the old room. /// The ID of the old room.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The event ID of the last known event in the old room. /// The event ID of the last known event in the old room.
pub event_id: Box<EventId>, pub event_id: Box<EventId>,
@ -95,7 +95,7 @@ pub struct PreviousRoom {
impl PreviousRoom { impl PreviousRoom {
/// Creates a new `PreviousRoom` from the given room and event IDs. /// Creates a new `PreviousRoom` from the given room and event IDs.
pub fn new(room_id: RoomId, event_id: Box<EventId>) -> Self { pub fn new(room_id: Box<RoomId>, event_id: Box<EventId>) -> Self {
Self { room_id, event_id } Self { room_id, event_id }
} }
} }

View File

@ -172,7 +172,7 @@ pub enum AllowRule {
#[cfg(feature = "unstable-pre-spec")] #[cfg(feature = "unstable-pre-spec")]
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: RoomId) -> Self { pub fn room_membership(room_id: Box<RoomId>) -> Self {
Self::RoomMembership(RoomMembership::new(room_id)) Self::RoomMembership(RoomMembership::new(room_id))
} }
} }
@ -183,13 +183,13 @@ 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: RoomId, pub room_id: Box<RoomId>,
} }
#[cfg(feature = "unstable-pre-spec")] #[cfg(feature = "unstable-pre-spec")]
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: RoomId) -> Self { pub fn new(room_id: Box<RoomId>) -> Self {
Self { room_id } Self { room_id }
} }
} }
@ -275,8 +275,8 @@ mod tests {
JoinRule::Restricted(restricted) => assert_eq!( JoinRule::Restricted(restricted) => assert_eq!(
restricted.allow, restricted.allow,
&[ &[
AllowRule::room_membership(room_id!("!mods:example.org")), AllowRule::room_membership(room_id!("!mods:example.org").to_owned()),
AllowRule::room_membership(room_id!("!users:example.org")) AllowRule::room_membership(room_id!("!users:example.org").to_owned())
] ]
), ),
rule => panic!("Deserialized to wrong variant: {:?}", rule), rule => panic!("Deserialized to wrong variant: {:?}", rule),

View File

@ -302,7 +302,7 @@ fn formatted_or_plain_body<'a>(formatted: &'a Option<FormattedBody>, body: &'a s
mod tests { mod tests {
use std::convert::TryFrom; use std::convert::TryFrom;
use ruma_identifiers::{EventId, RoomId, UserId}; use ruma_identifiers::{room_id, EventId, UserId};
use super::RoomMessageEvent; use super::RoomMessageEvent;
use crate::room::message::RoomMessageEventContent; use crate::room::message::RoomMessageEventContent;
@ -316,7 +316,7 @@ mod tests {
event_id: EventId::new(sender.server_name()), event_id: EventId::new(sender.server_name()),
sender, sender,
origin_server_ts: ruma_common::MilliSecondsSinceUnixEpoch::now(), origin_server_ts: ruma_common::MilliSecondsSinceUnixEpoch::now(),
room_id: RoomId::try_from("!n8f893n9:example.com").unwrap(), room_id: room_id!("!n8f893n9:example.com").to_owned(),
unsigned: crate::Unsigned::new(), unsigned: crate::Unsigned::new(),
}), }),
"> <@alice:example.com> multi\n> line" "> <@alice:example.com> multi\n> line"

View File

@ -44,7 +44,7 @@ mod tests {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: None, prev_content: None,
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
@ -73,7 +73,7 @@ mod tests {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: Some(RoomNameEventContent { name: "The old name".try_into().ok() }), prev_content: Some(RoomNameEventContent { name: "The old name".try_into().ok() }),
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned { age: Some(int!(100)), ..Unsigned::default() }, unsigned: Unsigned { age: Some(int!(100)), ..Unsigned::default() },

View File

@ -182,7 +182,7 @@ mod tests {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: None, prev_content: None,
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
@ -241,7 +241,7 @@ mod tests {
users_default: int!(42), users_default: int!(42),
notifications: assign!(NotificationPowerLevels::new(), { room: int!(42) }), notifications: assign!(NotificationPowerLevels::new(), { room: int!(42) }),
}), }),
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
unsigned: Unsigned { age: Some(int!(100)), ..Unsigned::default() }, unsigned: Unsigned { age: Some(int!(100)), ..Unsigned::default() },
sender: user, sender: user,
state_key: "".into(), state_key: "".into(),

View File

@ -27,7 +27,7 @@ pub struct RoomRedactionEvent {
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: RoomId, pub room_id: Box<RoomId>,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: Unsigned, pub unsigned: Unsigned,
@ -74,7 +74,7 @@ pub struct RedactedRoomRedactionEvent {
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: RoomId, pub room_id: Box<RoomId>,
/// Additional key-value pairs not signed by the homeserver. /// Additional key-value pairs not signed by the homeserver.
pub unsigned: RedactedUnsigned, pub unsigned: RedactedUnsigned,

View File

@ -20,12 +20,12 @@ pub struct RoomTombstoneEventContent {
pub body: String, pub body: String,
/// The new room the client should be visiting. /// The new room the client should be visiting.
pub replacement_room: RoomId, pub replacement_room: Box<RoomId>,
} }
impl RoomTombstoneEventContent { impl RoomTombstoneEventContent {
/// Creates a new `RoomTombstoneEventContent` with the given body and replacement room ID. /// Creates a new `RoomTombstoneEventContent` with the given body and replacement room ID.
pub fn new(body: String, replacement_room: RoomId) -> Self { pub fn new(body: String, replacement_room: Box<RoomId>) -> Self {
Self { body, replacement_room } Self { body, replacement_room }
} }
} }

View File

@ -17,7 +17,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: RoomId, pub room_id: Box<RoomId>,
/// 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,
@ -31,7 +31,7 @@ impl ToDeviceRoomKeyEventContent {
/// and session key. /// and session key.
pub fn new( pub fn new(
algorithm: EventEncryptionAlgorithm, algorithm: EventEncryptionAlgorithm,
room_id: RoomId, room_id: Box<RoomId>,
session_id: String, session_id: String,
session_key: String, session_key: String,
) -> Self { ) -> Self {
@ -52,7 +52,7 @@ mod tests {
let ev = ToDeviceEvent { let ev = ToDeviceEvent {
content: ToDeviceRoomKeyEventContent { content: ToDeviceRoomKeyEventContent {
algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2, algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
room_id: room_id!("!testroomid:example.org"), room_id: room_id!("!testroomid:example.org").to_owned(),
session_id: "SessId".into(), session_id: "SessId".into(),
session_key: "SessKey".into(), session_key: "SessKey".into(),
}, },

View File

@ -75,7 +75,7 @@ pub struct RequestedKeyInfo {
pub algorithm: EventEncryptionAlgorithm, pub algorithm: EventEncryptionAlgorithm,
/// The room where the key is used. /// The room where the key is used.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The Curve25519 key of the device which initiated the session originally. /// The Curve25519 key of the device which initiated the session originally.
pub sender_key: String, pub sender_key: String,
@ -89,7 +89,7 @@ impl RequestedKeyInfo {
/// ID. /// ID.
pub fn new( pub fn new(
algorithm: EventEncryptionAlgorithm, algorithm: EventEncryptionAlgorithm,
room_id: RoomId, room_id: Box<RoomId>,
sender_key: String, sender_key: String,
session_id: String, session_id: String,
) -> Self { ) -> Self {

View File

@ -52,7 +52,7 @@ fn serialize_custom_message_event() {
}, },
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10)),
room_id: room_id!("!room:room.com"), room_id: room_id!("!room:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}; };
@ -93,7 +93,7 @@ fn serialize_custom_state_event() {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10)),
prev_content: None, prev_content: None,
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),

View File

@ -204,7 +204,7 @@ fn message_event_serialization() {
content: RoomMessageEventContent::text_plain("test"), content: RoomMessageEventContent::text_plain("test"),
event_id: event_id!("$1234:example.com").to_owned(), event_id: event_id!("$1234:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(0)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(0)),
room_id: room_id!("!roomid:example.com"), room_id: room_id!("!roomid:example.com").to_owned(),
sender: user_id!("@test:example.com"), sender: user_id!("@test:example.com"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}; };
@ -284,7 +284,7 @@ fn alias_event_field_access() {
from_json_value::<AnyRoomEvent>(json_data.clone()), from_json_value::<AnyRoomEvent>(json_data.clone()),
Ok(AnyRoomEvent::State(state_event)) Ok(AnyRoomEvent::State(state_event))
if state_event.state_key() == "" if state_event.state_key() == ""
&& state_event.room_id() == &room_id!("!room:room.com") && state_event.room_id() == room_id!("!room:room.com")
&& state_event.event_id() == event_id!("$152037280074GZeOm:localhost") && state_event.event_id() == event_id!("$152037280074GZeOm:localhost")
&& state_event.sender() == &user_id!("@example:localhost") && state_event.sender() == &user_id!("@example:localhost")
); );
@ -316,7 +316,7 @@ fn ephemeral_event_deserialization() {
assert_matches!( assert_matches!(
from_json_value::<AnyEphemeralRoomEvent>(json_data), from_json_value::<AnyEphemeralRoomEvent>(json_data),
Ok(ephem @ AnyEphemeralRoomEvent::Typing(_)) Ok(ephem @ AnyEphemeralRoomEvent::Typing(_))
if ephem.room_id() == &room_id!("!jEsUZKDJdhlrceRyVU:example.org") if ephem.room_id() == room_id!("!jEsUZKDJdhlrceRyVU:example.org")
); );
} }

View File

@ -15,7 +15,7 @@ use ruma_events::{
fn ephemeral_serialize_typing() { fn ephemeral_serialize_typing() {
let aliases_event = EphemeralRoomEvent { let aliases_event = EphemeralRoomEvent {
content: TypingEventContent::new(vec![user_id!("@carl:example.com")]), content: TypingEventContent::new(vec![user_id!("@carl:example.com")]),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
}; };
let actual = to_json_value(&aliases_event).unwrap(); let actual = to_json_value(&aliases_event).unwrap();
@ -63,7 +63,7 @@ fn ephemeral_serialize_receipt() {
}, },
}, },
}), }),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
}; };
let actual = to_json_value(&aliases_event).unwrap(); let actual = to_json_value(&aliases_event).unwrap();

View File

@ -88,7 +88,7 @@ fn serialize_message_event() {
), ),
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}); });

View File

@ -34,7 +34,7 @@ fn message_serialize_sticker() {
), ),
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}; };
@ -243,7 +243,7 @@ fn deserialize_message_then_convert_to_full() {
let sync_ev: AnySyncMessageEvent = from_json_value(json_data).unwrap(); let sync_ev: AnySyncMessageEvent = from_json_value(json_data).unwrap();
// Test conversion method // Test conversion method
let full = sync_ev.into_full_event(rid); let full = sync_ev.into_full_event(rid.to_owned());
let full_json = to_json_value(full).unwrap(); let full_json = to_json_value(full).unwrap();
assert_matches!( assert_matches!(

View File

@ -27,7 +27,7 @@ fn serialize_pdu_as_v1() {
unsigned.insert("somekey".into(), to_raw_json_value(&json!({ "a": 456 })).unwrap()); unsigned.insert("somekey".into(), to_raw_json_value(&json!({ "a": 456 })).unwrap());
let v1_pdu = RoomV1Pdu { let v1_pdu = RoomV1Pdu {
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
event_id: event_id!("$somejoinevent:matrix.org").to_owned(), event_id: event_id!("$somejoinevent:matrix.org").to_owned(),
sender: user_id!("@sender:example.com"), sender: user_id!("@sender:example.com"),
origin: "matrix.org".into(), origin: "matrix.org".into(),
@ -94,7 +94,7 @@ fn serialize_pdu_as_v3() {
unsigned.insert("somekey".into(), to_raw_json_value(&json!({ "a": 456 })).unwrap()); unsigned.insert("somekey".into(), to_raw_json_value(&json!({ "a": 456 })).unwrap());
let v3_pdu = RoomV3Pdu { let v3_pdu = RoomV3Pdu {
room_id: room_id!("!n8f893n9:example.com"), room_id: room_id!("!n8f893n9:example.com").to_owned(),
sender: user_id!("@sender:example.com"), sender: user_id!("@sender:example.com"),
origin: "matrix.org".into(), origin: "matrix.org".into(),
origin_server_ts: MilliSecondsSinceUnixEpoch(1_592_050_773_658_u64.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(1_592_050_773_658_u64.try_into().unwrap()),

View File

@ -31,7 +31,7 @@ fn serialize_redaction() {
redacts: event_id!("$nomore:example.com").to_owned(), redacts: event_id!("$nomore:example.com").to_owned(),
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}; };

View File

@ -42,7 +42,7 @@ fn serialization() {
))), ))),
event_id: event_id!("$143273582443PhrSn:example.org").to_owned(), event_id: event_id!("$143273582443PhrSn:example.org").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10_000)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(10_000)),
room_id: room_id!("!testroomid:example.org"), room_id: room_id!("!testroomid:example.org").to_owned(),
sender: user_id!("@user:example.org"), sender: user_id!("@user:example.org"),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
}; };

View File

@ -44,7 +44,7 @@ fn serialize_aliases_with_prev_content() {
prev_content: Some(RoomAliasesEventContent::new(vec![ prev_content: Some(RoomAliasesEventContent::new(vec![
room_alias_id!("#inner:localhost").to_owned() room_alias_id!("#inner:localhost").to_owned()
])), ])),
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),
@ -65,7 +65,7 @@ fn serialize_aliases_without_prev_content() {
event_id: event_id!("$h29iv0s8:example.com").to_owned(), event_id: event_id!("$h29iv0s8:example.com").to_owned(),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)), origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: None, prev_content: None,
room_id: room_id!("!roomid:room.com"), room_id: room_id!("!roomid:room.com").to_owned(),
sender: user_id!("@carl:example.com"), sender: user_id!("@carl:example.com"),
state_key: "".into(), state_key: "".into(),
unsigned: Unsigned::default(), unsigned: Unsigned::default(),

View File

@ -8,7 +8,7 @@ fn serialization() {
sender: user_id!("@example:example.org"), sender: user_id!("@example:example.org"),
content: ToDeviceRoomKeyEventContent::new( content: ToDeviceRoomKeyEventContent::new(
EventEncryptionAlgorithm::MegolmV1AesSha2, EventEncryptionAlgorithm::MegolmV1AesSha2,
room_id!("!testroomid:example.org"), room_id!("!testroomid:example.org").to_owned(),
"SessId".into(), "SessId".into(),
"SessKey".into(), "SessKey".into(),
), ),

View File

@ -15,7 +15,7 @@ pub struct StateEvent<C: StateEventContent> {
pub event_id: Box<EventId>, pub event_id: Box<EventId>,
pub sender: UserId, pub sender: UserId,
pub origin_server_ts: MilliSecondsSinceUnixEpoch, pub origin_server_ts: MilliSecondsSinceUnixEpoch,
pub room_id: RoomId, pub room_id: Box<RoomId>,
pub state_key: String, pub state_key: String,
pub prev_content: Option<C>, pub prev_content: Option<C>,
pub unsigned: Unsigned, pub unsigned: Unsigned,

View File

@ -21,7 +21,7 @@ ruma_api! {
response: { response: {
/// Room ID mapped to queried alias. /// Room ID mapped to queried alias.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room. /// An array of server names that are likely to hold the given room.
pub servers: Vec<Box<ServerName>>, pub servers: Vec<Box<ServerName>>,
@ -37,7 +37,7 @@ impl<'a> Request<'a> {
impl Response { impl Response {
/// Creates a new `Response` with the given room IDs and servers. /// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id: RoomId, servers: Vec<Box<ServerName>>) -> Self { pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers } Self { room_id, servers }
} }
} }

View File

@ -71,7 +71,7 @@ pub struct ThirdPartyInvite {
pub mxid: UserId, pub mxid: UserId,
/// The room ID the invite is valid for. /// The room ID the invite is valid for.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The user ID that sent the invite. /// The user ID that sent the invite.
pub sender: UserId, pub sender: UserId,
@ -85,7 +85,7 @@ impl ThirdPartyInvite {
pub fn new( pub fn new(
address: String, address: String,
mxid: UserId, mxid: UserId,
room_id: RoomId, room_id: Box<RoomId>,
sender: UserId, sender: UserId,
signed: BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId, String>>, signed: BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId, String>>,
) -> Self { ) -> Self {

View File

@ -133,12 +133,12 @@ impl PresenceUpdate {
pub struct ReceiptContent { pub struct ReceiptContent {
/// Receipts for a particular room. /// Receipts for a particular room.
#[serde(flatten)] #[serde(flatten)]
pub receipts: BTreeMap<RoomId, ReceiptMap>, pub receipts: BTreeMap<Box<RoomId>, ReceiptMap>,
} }
impl ReceiptContent { impl ReceiptContent {
/// Creates a new `ReceiptContent`. /// Creates a new `ReceiptContent`.
pub fn new(receipts: BTreeMap<RoomId, ReceiptMap>) -> Self { pub fn new(receipts: BTreeMap<Box<RoomId>, ReceiptMap>) -> Self {
Self { receipts } Self { receipts }
} }
} }
@ -182,7 +182,7 @@ impl ReceiptData {
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct TypingContent { pub struct TypingContent {
/// The room where the user's typing status has been updated. /// The room where the user's typing status has been updated.
pub room_id: RoomId, pub room_id: Box<RoomId>,
/// The user ID that has had their typing status changed. /// The user ID that has had their typing status changed.
pub user_id: UserId, pub user_id: UserId,
@ -193,7 +193,7 @@ pub struct TypingContent {
impl TypingContent { impl TypingContent {
/// Creates a new `TypingContent`. /// Creates a new `TypingContent`.
pub fn new(room_id: RoomId, user_id: UserId, typing: bool) -> Self { pub fn new(room_id: Box<RoomId>, user_id: UserId, typing: bool) -> Self {
Self { room_id, user_id, typing } Self { room_id, user_id, typing }
} }
} }
@ -401,7 +401,7 @@ mod test {
assert_matches!( assert_matches!(
&edu, &edu,
Edu::Receipt(ReceiptContent { receipts }) Edu::Receipt(ReceiptContent { receipts })
if receipts.get(&room_id!("!some_room:example.org")).is_some() if receipts.get(room_id!("!some_room:example.org")).is_some()
); );
assert_eq!(serde_json::to_value(&edu).unwrap(), json); assert_eq!(serde_json::to_value(&edu).unwrap(), json);

View File

@ -67,7 +67,7 @@ pub fn room_id(input: TokenStream) -> TokenStream {
assert!(room_id::validate(&id.value()).is_ok(), "Invalid room_id"); assert!(room_id::validate(&id.value()).is_ok(), "Invalid room_id");
let output = quote! { let output = quote! {
<#dollar_crate::RoomId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap() <&#dollar_crate::RoomId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
}; };
output.into() output.into()

View File

@ -1,7 +1,5 @@
use std::num::NonZeroU8; use crate::{validate_delimited_id, Error};
use crate::{parse_id, Error}; pub fn validate(s: &str) -> Result<(), Error> {
validate_delimited_id(s, &['!'])
pub fn validate(s: &str) -> Result<NonZeroU8, Error> {
parse_id(s, &['!'])
} }

View File

@ -1,6 +1,6 @@
//! Matrix room identifiers. //! Matrix room identifiers.
use std::{convert::TryInto, fmt, num::NonZeroU8}; use std::convert::TryInto;
use crate::{EventId, MatrixToRef, ServerName}; use crate::{EventId, MatrixToRef, ServerName};
@ -13,21 +13,14 @@ use crate::{EventId, MatrixToRef, ServerName};
/// # use std::convert::TryFrom; /// # use std::convert::TryFrom;
/// # use ruma_identifiers::RoomId; /// # use ruma_identifiers::RoomId;
/// assert_eq!( /// assert_eq!(
/// RoomId::try_from("!n8f893n9:example.com").unwrap().as_ref(), /// <&RoomId>::try_from("!n8f893n9:example.com").unwrap(),
/// "!n8f893n9:example.com" /// "!n8f893n9:example.com"
/// ); /// );
/// ``` /// ```
#[derive(Clone)] #[repr(transparent)]
pub struct RoomId { pub struct RoomId(str);
pub(crate) full_id: Box<str>,
pub(crate) colon_idx: NonZeroU8,
}
impl fmt::Debug for RoomId { opaque_identifier_validated!(RoomId, ruma_identifiers_validation::room_id::validate);
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.full_id.fmt(f)
}
}
impl RoomId { impl RoomId {
/// Attempts to generate a `RoomId` for the given origin server with a localpart consisting of /// Attempts to generate a `RoomId` for the given origin server with a localpart consisting of
@ -35,22 +28,18 @@ impl RoomId {
/// ///
/// Fails if the given homeserver cannot be parsed as a valid host. /// Fails if the given homeserver cannot be parsed as a valid host.
#[cfg(feature = "rand")] #[cfg(feature = "rand")]
pub fn new(server_name: &ServerName) -> Self { pub fn new(server_name: &ServerName) -> Box<Self> {
use crate::generate_localpart; Self::from_owned(format!("!{}:{}", crate::generate_localpart(18), server_name).into())
let full_id = format!("!{}:{}", generate_localpart(18), server_name).into();
Self { full_id, colon_idx: NonZeroU8::new(19).unwrap() }
} }
/// Returns the rooms's unique ID. /// Returns the rooms's unique ID.
pub fn localpart(&self) -> &str { pub fn localpart(&self) -> &str {
&self.full_id[1..self.colon_idx.get() as usize] &self.as_str()[1..self.colon_idx()]
} }
/// Returns the server name of the room ID. /// Returns the server name of the room ID.
pub fn server_name(&self) -> &ServerName { pub fn server_name(&self) -> &ServerName {
self.full_id[self.colon_idx.get() as usize + 1..].try_into().unwrap() self.as_str()[self.colon_idx() + 1..].try_into().unwrap()
} }
/// Create a `matrix.to` reference for this room ID. /// Create a `matrix.to` reference for this room ID.
@ -71,28 +60,19 @@ impl RoomId {
&'a self, &'a self,
via: impl IntoIterator<Item = &'a ServerName>, via: impl IntoIterator<Item = &'a ServerName>,
) -> MatrixToRef<'a> { ) -> MatrixToRef<'a> {
MatrixToRef::new(&self.full_id, via.into_iter().collect()) MatrixToRef::new(self.as_str(), via.into_iter().collect())
} }
/// Create a `matrix.to` reference for an event scoped under this room ID. /// Create a `matrix.to` reference for an event scoped under this room ID.
pub fn matrix_to_event_url<'a>(&'a self, ev_id: &'a EventId) -> MatrixToRef<'a> { pub fn matrix_to_event_url<'a>(&'a self, ev_id: &'a EventId) -> MatrixToRef<'a> {
MatrixToRef::event(&self.full_id, ev_id, Vec::new()) MatrixToRef::event(self.as_str(), ev_id, Vec::new())
}
fn colon_idx(&self) -> usize {
self.as_str().find(':').unwrap()
} }
} }
/// Attempts to create a new Matrix room ID from a string representation.
///
/// The string must include the leading ! sigil, the localpart, a literal colon, and a server name.
fn try_from<S>(room_id: S) -> Result<RoomId, crate::Error>
where
S: AsRef<str> + Into<Box<str>>,
{
let colon_idx = ruma_identifiers_validation::room_id::validate(room_id.as_ref())?;
Ok(RoomId { full_id: room_id.into(), colon_idx })
}
common_impls!(RoomId, try_from, "a Matrix room ID");
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::convert::TryFrom; use std::convert::TryFrom;
@ -103,7 +83,7 @@ mod tests {
#[test] #[test]
fn valid_room_id() { fn valid_room_id() {
assert_eq!( assert_eq!(
RoomId::try_from("!29fhd83h92h0:example.com") <&RoomId>::try_from("!29fhd83h92h0:example.com")
.expect("Failed to create RoomId.") .expect("Failed to create RoomId.")
.as_ref(), .as_ref(),
"!29fhd83h92h0:example.com" "!29fhd83h92h0:example.com"
@ -113,7 +93,7 @@ mod tests {
#[test] #[test]
fn empty_localpart() { fn empty_localpart() {
assert_eq!( assert_eq!(
RoomId::try_from("!:example.com").expect("Failed to create RoomId.").as_ref(), <&RoomId>::try_from("!:example.com").expect("Failed to create RoomId.").as_ref(),
"!:example.com" "!:example.com"
); );
} }
@ -135,7 +115,7 @@ mod tests {
fn serialize_valid_room_id() { fn serialize_valid_room_id() {
assert_eq!( assert_eq!(
serde_json::to_string( serde_json::to_string(
&RoomId::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.") <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.")
) )
.expect("Failed to convert RoomId to JSON."), .expect("Failed to convert RoomId to JSON."),
r#""!29fhd83h92h0:example.com""# r#""!29fhd83h92h0:example.com""#
@ -146,16 +126,16 @@ mod tests {
#[test] #[test]
fn deserialize_valid_room_id() { fn deserialize_valid_room_id() {
assert_eq!( assert_eq!(
serde_json::from_str::<RoomId>(r#""!29fhd83h92h0:example.com""#) serde_json::from_str::<Box<RoomId>>(r#""!29fhd83h92h0:example.com""#)
.expect("Failed to convert JSON to RoomId"), .expect("Failed to convert JSON to RoomId"),
RoomId::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.") <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.")
); );
} }
#[test] #[test]
fn valid_room_id_with_explicit_standard_port() { fn valid_room_id_with_explicit_standard_port() {
assert_eq!( assert_eq!(
RoomId::try_from("!29fhd83h92h0:example.com:443") <&RoomId>::try_from("!29fhd83h92h0:example.com:443")
.expect("Failed to create RoomId.") .expect("Failed to create RoomId.")
.as_ref(), .as_ref(),
"!29fhd83h92h0:example.com:443" "!29fhd83h92h0:example.com:443"
@ -165,7 +145,7 @@ mod tests {
#[test] #[test]
fn valid_room_id_with_non_standard_port() { fn valid_room_id_with_non_standard_port() {
assert_eq!( assert_eq!(
RoomId::try_from("!29fhd83h92h0:example.com:5000") <&RoomId>::try_from("!29fhd83h92h0:example.com:5000")
.expect("Failed to create RoomId.") .expect("Failed to create RoomId.")
.as_ref(), .as_ref(),
"!29fhd83h92h0:example.com:5000" "!29fhd83h92h0:example.com:5000"
@ -174,23 +154,26 @@ mod tests {
#[test] #[test]
fn missing_room_id_sigil() { fn missing_room_id_sigil() {
assert_eq!(RoomId::try_from("carl:example.com").unwrap_err(), Error::MissingLeadingSigil); assert_eq!(
<&RoomId>::try_from("carl:example.com").unwrap_err(),
Error::MissingLeadingSigil
);
} }
#[test] #[test]
fn missing_room_id_delimiter() { fn missing_room_id_delimiter() {
assert_eq!(RoomId::try_from("!29fhd83h92h0").unwrap_err(), Error::MissingDelimiter); assert_eq!(<&RoomId>::try_from("!29fhd83h92h0").unwrap_err(), Error::MissingDelimiter);
} }
#[test] #[test]
fn invalid_room_id_host() { fn invalid_room_id_host() {
assert_eq!(RoomId::try_from("!29fhd83h92h0:/").unwrap_err(), Error::InvalidServerName); assert_eq!(<&RoomId>::try_from("!29fhd83h92h0:/").unwrap_err(), Error::InvalidServerName);
} }
#[test] #[test]
fn invalid_room_id_port() { fn invalid_room_id_port() {
assert_eq!( assert_eq!(
RoomId::try_from("!29fhd83h92h0:example.com:notaport").unwrap_err(), <&RoomId>::try_from("!29fhd83h92h0:example.com:notaport").unwrap_err(),
Error::InvalidServerName Error::InvalidServerName
); );
} }

View File

@ -63,11 +63,9 @@ impl RoomIdOrAliasId {
/// Turn this `RoomIdOrAliasId` into `Either<RoomId, RoomAliasId>` /// Turn this `RoomIdOrAliasId` into `Either<RoomId, RoomAliasId>`
#[cfg(feature = "either")] #[cfg(feature = "either")]
pub fn into_either(self) -> either::Either<RoomId, Box<RoomAliasId>> { pub fn into_either(self) -> either::Either<Box<RoomId>, Box<RoomAliasId>> {
match self.variant() { match self.variant() {
Variant::RoomId => { Variant::RoomId => either::Either::Left(self.as_str().try_into().unwrap()),
either::Either::Left(RoomId { full_id: self.full_id, colon_idx: self.colon_idx })
}
Variant::RoomAliasId => either::Either::Right(self.as_str().try_into().unwrap()), Variant::RoomAliasId => either::Either::Right(self.as_str().try_into().unwrap()),
} }
} }
@ -103,9 +101,9 @@ where
common_impls!(RoomIdOrAliasId, try_from, "a Matrix room ID or room alias ID"); common_impls!(RoomIdOrAliasId, try_from, "a Matrix room ID or room alias ID");
impl From<RoomId> for RoomIdOrAliasId { impl From<Box<RoomId>> for RoomIdOrAliasId {
fn from(RoomId { full_id, colon_idx }: RoomId) -> Self { fn from(room_id: Box<RoomId>) -> Self {
Self { full_id, colon_idx } Self::try_from(room_id.as_str()).unwrap()
} }
} }
@ -115,24 +113,24 @@ impl From<Box<RoomAliasId>> for RoomIdOrAliasId {
} }
} }
impl TryFrom<RoomIdOrAliasId> for RoomId { impl TryFrom<RoomIdOrAliasId> for Box<RoomId> {
type Error = Box<RoomAliasId>; type Error = Box<RoomAliasId>;
fn try_from(id: RoomIdOrAliasId) -> Result<RoomId, Box<RoomAliasId>> { fn try_from(id: RoomIdOrAliasId) -> Result<Box<RoomId>, Box<RoomAliasId>> {
match id.variant() { match id.variant() {
Variant::RoomId => Ok(RoomId { full_id: id.full_id, colon_idx: id.colon_idx }), Variant::RoomId => Ok(id.as_str().try_into().unwrap()),
Variant::RoomAliasId => Err(id.as_str().try_into().unwrap()), Variant::RoomAliasId => Err(id.as_str().try_into().unwrap()),
} }
} }
} }
impl TryFrom<RoomIdOrAliasId> for Box<RoomAliasId> { impl TryFrom<RoomIdOrAliasId> for Box<RoomAliasId> {
type Error = RoomId; type Error = Box<RoomId>;
fn try_from(id: RoomIdOrAliasId) -> Result<Box<RoomAliasId>, RoomId> { fn try_from(id: RoomIdOrAliasId) -> Result<Box<RoomAliasId>, Box<RoomId>> {
match id.variant() { match id.variant() {
Variant::RoomAliasId => Ok(id.as_str().try_into().unwrap()), Variant::RoomAliasId => Ok(id.as_str().try_into().unwrap()),
Variant::RoomId => Err(RoomId { full_id: id.full_id, colon_idx: id.colon_idx }), Variant::RoomId => Err(id.as_str().try_into().unwrap()),
} }
} }
} }

View File

@ -364,7 +364,7 @@ mod tests {
let notice = Notification { let notice = Notification {
event_id: Some(eid), event_id: Some(eid),
room_id: Some(&rid), room_id: Some(rid),
event_type: Some(&EventType::RoomMessage), event_type: Some(&EventType::RoomMessage),
sender: Some(&uid), sender: Some(&uid),
sender_display_name: Some("Major Tom"), sender_display_name: Some("Major Tom"),

View File

@ -268,6 +268,7 @@ fn strip_lifetimes(field_type: &mut Type) -> bool {
|| last_seg.ident == "SessionId" || last_seg.ident == "SessionId"
|| last_seg.ident == "RawJsonValue" || last_seg.ident == "RawJsonValue"
|| last_seg.ident == "RoomAliasId" || last_seg.ident == "RoomAliasId"
|| last_seg.ident == "RoomId"
|| last_seg.ident == "RoomName" || last_seg.ident == "RoomName"
{ {
// The identifiers that need to be boxed `Box<T>` since they are DST's. // The identifiers that need to be boxed `Box<T>` since they are DST's.

View File

@ -29,7 +29,7 @@ use ruma_events::{
}, },
EventType, EventType,
}; };
use ruma_identifiers::{EventId, RoomId, RoomVersionId, UserId}; use ruma_identifiers::{room_id, EventId, 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::{
json, json,
@ -71,7 +71,7 @@ fn resolution_shallow_auth_chain(c: &mut Criterion) {
state_sets state_sets
.iter() .iter()
.map(|map| { .map(|map| {
store.auth_event_ids(&room_id(), map.values().cloned().collect()).unwrap() store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap()
}) })
.collect(), .collect(),
|id| ev_map.get(id).map(Arc::clone), |id| ev_map.get(id).map(Arc::clone),
@ -135,7 +135,7 @@ fn resolve_deeper_event_set(c: &mut Criterion) {
state_sets state_sets
.iter() .iter()
.map(|map| { .map(|map| {
store.auth_event_ids(&room_id(), map.values().cloned().collect()).unwrap() store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap()
}) })
.collect(), .collect(),
|id| inner.get(id).map(Arc::clone), |id| inner.get(id).map(Arc::clone),
@ -355,8 +355,8 @@ fn ella() -> UserId {
UserId::try_from("@ella:foo").unwrap() UserId::try_from("@ella:foo").unwrap()
} }
fn room_id() -> RoomId { fn room_id() -> &'static RoomId {
RoomId::try_from("!test:foo").unwrap() room_id!("!test:foo")
} }
fn member_content_ban() -> Box<RawJsonValue> { fn member_content_ban() -> Box<RawJsonValue> {
@ -390,7 +390,7 @@ where
Arc::new(StateEvent { Arc::new(StateEvent {
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id(), room_id: room_id().to_owned(),
sender, sender,
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,

View File

@ -1044,7 +1044,7 @@ mod tests {
state_sets state_sets
.iter() .iter()
.map(|map| { .map(|map| {
store.auth_event_ids(&room_id(), map.values().cloned().collect()).unwrap() store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap()
}) })
.collect(), .collect(),
|id| ev_map.get(id).map(Arc::clone), |id| ev_map.get(id).map(Arc::clone),
@ -1148,7 +1148,7 @@ mod tests {
state_sets state_sets
.iter() .iter()
.map(|map| { .map(|map| {
store.auth_event_ids(&room_id(), map.values().cloned().collect()).unwrap() store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap()
}) })
.collect(), .collect(),
|id| ev_map.get(id).map(Arc::clone), |id| ev_map.get(id).map(Arc::clone),

View File

@ -112,7 +112,7 @@ pub fn do_check(
let auth_chain_sets = state_sets let auth_chain_sets = state_sets
.iter() .iter()
.map(|map| { .map(|map| {
store.auth_event_ids(&room_id(), map.values().cloned().collect()).unwrap() store.auth_event_ids(room_id(), map.values().cloned().collect()).unwrap()
}) })
.collect(); .collect();
@ -367,7 +367,7 @@ pub fn zara() -> UserId {
user_id!("@zara:foo") user_id!("@zara:foo")
} }
pub fn room_id() -> RoomId { pub fn room_id() -> &'static RoomId {
room_id!("!test:foo") room_id!("!test:foo")
} }
@ -393,7 +393,7 @@ pub fn to_init_pdu_event(
Arc::new(StateEvent { Arc::new(StateEvent {
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id(), room_id: room_id().to_owned(),
sender, sender,
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,
@ -433,7 +433,7 @@ where
Arc::new(StateEvent { Arc::new(StateEvent {
event_id: id.try_into().unwrap(), event_id: id.try_into().unwrap(),
rest: Pdu::RoomV3Pdu(RoomV3Pdu { rest: Pdu::RoomV3Pdu(RoomV3Pdu {
room_id: room_id(), room_id: room_id().to_owned(),
sender, sender,
origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()), origin_server_ts: MilliSecondsSinceUnixEpoch(ts.try_into().unwrap()),
state_key, state_key,