transport.rs 6.71 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Transport key type for type-safe transport identification.

use std::fmt;
use std::sync::Arc;

/// A type-safe wrapper around transport keys for WorkerAddress.
///
/// This provides a zero-cost abstraction over `Arc<str>` with type safety
/// to prevent accidentally mixing transport keys with other string types.
///
/// # Examples
///
/// ```
/// use velo_common::TransportKey;
///
/// let key = TransportKey::new("tcp");
/// assert_eq!(key.as_str(), "tcp");
///
/// // Ergonomic conversions
/// let key2: TransportKey = "rdma".into();
/// let key3 = TransportKey::from("udp");
///
/// // Use in collections
/// use std::collections::HashMap;
/// let mut transports = HashMap::new();
/// transports.insert(TransportKey::from("tcp"), "tcp://127.0.0.1:5555");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TransportKey(Arc<str>);

impl TransportKey {
    /// Create a new TransportKey from any type that can be converted into Arc<str>.
    pub fn new(key: impl Into<Arc<str>>) -> Self {
        Self(key.into())
    }

    /// Get the key as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

// Deref to str for ergonomic usage
impl std::ops::Deref for TransportKey {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

// AsRef for flexible parameter types
impl AsRef<str> for TransportKey {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

// From conversions for ergonomic construction
impl From<&str> for TransportKey {
    fn from(s: &str) -> Self {
        Self(Arc::from(s))
    }
}

impl From<String> for TransportKey {
    fn from(s: String) -> Self {
        Self(Arc::from(s))
    }
}

impl From<Arc<str>> for TransportKey {
    fn from(s: Arc<str>) -> Self {
        Self(s)
    }
}

impl From<&String> for TransportKey {
    fn from(s: &String) -> Self {
        Self(Arc::from(s.as_str()))
    }
}

impl From<TransportKey> for String {
    fn from(val: TransportKey) -> Self {
        val.0.to_string()
    }
}

// Borrow trait for HashMap lookups with &str
impl std::borrow::Borrow<str> for TransportKey {
    fn borrow(&self) -> &str {
        &self.0
    }
}

// Display for printing
impl fmt::Display for TransportKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{HashMap, HashSet};

    #[test]
    fn test_transport_key_creation() {
        // Test new() method
        let key1 = TransportKey::new("tcp");
        assert_eq!(key1.as_str(), "tcp");

        // Test From<&str>
        let key2: TransportKey = "rdma".into();
        assert_eq!(key2.as_str(), "rdma");

        // Test From<String>
        let key3 = TransportKey::from(String::from("udp"));
        assert_eq!(key3.as_str(), "udp");

        // Test From<&String>
        let s = String::from("grpc");
        let key4 = TransportKey::from(&s);
        assert_eq!(key4.as_str(), "grpc");

        // Test From<Arc<str>>
        let arc_str: Arc<str> = Arc::from("http");
        let key5 = TransportKey::from(arc_str);
        assert_eq!(key5.as_str(), "http");
    }

    #[test]
    fn test_transport_key_deref() {
        let key = TransportKey::from("tcp");

        // Deref to str methods should work
        assert_eq!(key.len(), 3);
        assert_eq!(key.chars().count(), 3);
        assert!(key.starts_with("tc"));
        assert!(key.ends_with("cp"));

        // Can use str slicing through Deref
        assert_eq!(&key[0..2], "tc");
    }

    #[test]
    fn test_transport_key_as_ref() {
        let key = TransportKey::from("tcp");

        // AsRef<str> allows passing to functions expecting &str
        fn takes_str_ref(s: &str) -> usize {
            s.len()
        }

        assert_eq!(takes_str_ref(&key), 3);
        assert_eq!(takes_str_ref(key.as_ref()), 3);
    }

    #[test]
    fn test_transport_key_display() {
        let key = TransportKey::from("tcp");
        assert_eq!(format!("{}", key), "tcp");
        assert_eq!(key.to_string(), "tcp");
    }

    #[test]
    fn test_transport_key_debug() {
        let key = TransportKey::from("tcp");
        let debug_str = format!("{:?}", key);
        assert!(debug_str.contains("TransportKey"));
        assert!(debug_str.contains("tcp"));
    }

    #[test]
    fn test_transport_key_equality() {
        let key1 = TransportKey::from("tcp");
        let key2 = TransportKey::from("tcp");
        let key3 = TransportKey::from("rdma");

        assert_eq!(key1, key2);
        assert_ne!(key1, key3);

        // Test with different source types
        let key4: TransportKey = String::from("tcp").into();
        assert_eq!(key1, key4);
    }

    #[test]
    fn test_transport_key_ordering() {
        let mut keys = [
            TransportKey::from("udp"),
            TransportKey::from("tcp"),
            TransportKey::from("rdma"),
            TransportKey::from("grpc"),
        ];

        keys.sort();

        assert_eq!(keys[0], TransportKey::from("grpc"));
        assert_eq!(keys[1], TransportKey::from("rdma"));
        assert_eq!(keys[2], TransportKey::from("tcp"));
        assert_eq!(keys[3], TransportKey::from("udp"));
    }

    #[test]
    fn test_transport_key_hash() {
        let mut set = HashSet::new();
        set.insert(TransportKey::from("tcp"));
        set.insert(TransportKey::from("rdma"));
        set.insert(TransportKey::from("tcp")); // Duplicate

        assert_eq!(set.len(), 2);
        assert!(set.contains(&TransportKey::from("tcp")));
        assert!(set.contains(&TransportKey::from("rdma")));
        assert!(!set.contains(&TransportKey::from("udp")));
    }

    #[test]
    fn test_transport_key_in_hashmap() {
        let mut map = HashMap::new();
        map.insert(TransportKey::from("tcp"), "tcp://127.0.0.1:5555");
        map.insert(TransportKey::from("rdma"), "rdma://10.0.0.1:6666");

        // Can lookup with TransportKey
        assert_eq!(
            map.get(&TransportKey::from("tcp")),
            Some(&"tcp://127.0.0.1:5555")
        );

        // Can lookup with &str via Borrow trait
        assert_eq!(map.get("tcp"), Some(&"tcp://127.0.0.1:5555"));
        assert_eq!(map.get("rdma"), Some(&"rdma://10.0.0.1:6666"));
        assert_eq!(map.get("udp"), None);
    }

    #[test]
    fn test_transport_key_clone() {
        let key1 = TransportKey::from("tcp");
        let key2 = key1.clone();

        assert_eq!(key1, key2);
        assert_eq!(key1.as_str(), key2.as_str());

        // Verify Arc is shared (same pointer)
        let ptr1 = key1.as_str().as_ptr();
        let ptr2 = key2.as_str().as_ptr();
        assert_eq!(ptr1, ptr2);
    }
}