Skip to main content

gosuto_livekit/room/
id.rs

1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// https://doc.rust-lang.org/rust-by-example/generics/new_types.html
16
17use std::fmt::Display;
18
19const ROOM_PREFIX: &str = "RM_";
20const PARTICIPANT_PREFIX: &str = "PA_";
21const TRACK_PREFIX: &str = "TR_";
22
23#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
24pub struct ParticipantSid(String);
25
26#[derive(Clone, Default, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
27pub struct ParticipantIdentity(pub String);
28
29#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
30pub struct TrackSid(String);
31
32#[derive(Clone, Default, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
33pub struct RoomSid(String);
34
35impl From<String> for ParticipantIdentity {
36    fn from(value: String) -> Self {
37        Self(value)
38    }
39}
40
41macro_rules! impl_string_into {
42    ($from:ty) => {
43        impl From<$from> for String {
44            fn from(value: $from) -> Self {
45                value.0
46            }
47        }
48
49        impl Display for $from {
50            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51                write!(f, "{}", self.0)
52            }
53        }
54
55        impl $from {
56            pub fn as_str(&self) -> &str {
57                &self.0
58            }
59        }
60    };
61}
62
63impl_string_into!(ParticipantSid);
64impl_string_into!(ParticipantIdentity);
65impl_string_into!(TrackSid);
66impl_string_into!(RoomSid);
67
68macro_rules! impl_from_prefix {
69    ($to:ty, $prefix:ident) => {
70        impl TryFrom<String> for $to {
71            type Error = String;
72
73            fn try_from(value: String) -> Result<Self, Self::Error> {
74                if value.starts_with($prefix) {
75                    Ok(Self(value))
76                } else {
77                    Err(value)
78                }
79            }
80        }
81    };
82}
83
84impl_from_prefix!(RoomSid, ROOM_PREFIX);
85impl_from_prefix!(ParticipantSid, PARTICIPANT_PREFIX);
86impl_from_prefix!(TrackSid, TRACK_PREFIX);