tcplane 8.1.0

tcplane is a lightweight and high-performance Rust TCP server library designed to simplify network service development. It supports TCP communication, data stream management, and connection handling, focusing on providing efficient low-level network connections and data transmission capabilities, making it ideal for building modern network services.
Documentation
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use crate::*;

/// Provides a default implementation for ContextData.
impl Default for ContextData {
    /// Creates a new ContextData instance with default values.
    ///
    /// # Returns
    ///
    /// - `Self` - A new instance with default configuration.
    #[inline(always)]
    fn default() -> Self {
        Self {
            aborted: false,
            closed: false,
            stream: None,
            request: Request::new(),
            response: Response::default(),
            attributes: HashMap::new(),
        }
    }
}

impl ContextData {
    /// Creates a new ContextData instance with default values.
    ///
    /// # Returns
    ///
    /// - `Self` - A new instance with default configuration.
    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Provides a default implementation for Context.
impl Default for Context {
    /// Creates a new Context instance with default values.
    ///
    /// # Returns
    ///
    /// - `Self` - A new Context wrapping default ContextData.
    #[inline(always)]
    fn default() -> Self {
        Self(Arc::new(RwLock::new(ContextData::default())))
    }
}

/// Implementation of `From<ContextData>` for `Context`.
impl From<ContextData> for Context {
    /// Converts a `ContextData` into a `Context`.
    ///
    /// # Arguments
    ///
    /// - `ContextData` - The context data to wrap.
    ///
    /// # Returns
    ///
    /// - `Context` - A new Context instance.
    #[inline(always)]
    fn from(data: ContextData) -> Self {
        Self(Arc::new(RwLock::new(data)))
    }
}

/// Implementation of `From<ArcRwLockStream>` for `Context`.
impl From<ArcRwLockStream> for Context {
    /// Converts an `ArcRwLockStream` into a `Context`.
    ///
    /// # Arguments
    ///
    /// - `ArcRwLockStream` - The stream to set in the context.
    ///
    /// # Returns
    ///
    /// - `Context` - A new Context instance with the stream set.
    #[inline(always)]
    fn from(stream: ArcRwLockStream) -> Self {
        let data: ContextData = ContextData {
            stream: Some(stream),
            ..Default::default()
        };
        Self::from(data)
    }
}

/// Implementation of methods for the Context structure.
impl Context {
    /// Creates a new Context with default values.
    ///
    /// # Returns
    ///
    /// - `Self` - A new Context instance.
    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Acquires a read lock on the inner context data.
    ///
    /// # Returns
    ///
    /// - `ArcRwLockReadGuard<ContextData>` - The read guard.
    pub(crate) async fn read(&self) -> ArcRwLockReadGuard<'_, ContextData> {
        self.0.read().await
    }

    /// Acquires a write lock on the inner context data.
    ///
    /// # Returns
    ///
    /// - `ArcRwLockWriteGuard<ContextData>` - The write guard.
    pub(crate) async fn write(&self) -> ArcRwLockWriteGuard<'_, ContextData> {
        self.0.write().await
    }

    /// Checks if the context has been marked as aborted.
    ///
    /// # Returns
    ///
    /// - `bool` - True if the context is aborted, otherwise false.
    pub async fn is_aborted(&self) -> bool {
        self.read().await.aborted
    }

    /// Sets the aborted flag for the context.
    ///
    /// # Arguments
    ///
    /// - `bool` - The aborted state to set.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_aborted(&self, aborted: bool) -> &Self {
        self.write().await.aborted = aborted;
        self
    }

    /// Marks the context as aborted.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to the modified context.
    pub async fn abort(&self) -> &Self {
        self.set_aborted(true).await
    }

    /// Cancels the aborted state of the context.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to the modified context.
    pub async fn cancel_abort(&self) -> &Self {
        self.set_aborted(false).await
    }

    /// Checks if the connection has been closed.
    ///
    /// # Returns
    ///
    /// - `bool` - True if the connection is closed, otherwise false.
    pub async fn is_closed(&self) -> bool {
        self.read().await.closed
    }

    /// Sets the closed flag for the connection.
    ///
    /// # Arguments
    ///
    /// - `bool` - The closed state to set.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_closed(&self, closed: bool) -> &Self {
        self.write().await.closed = closed;
        self
    }

    /// Marks the connection as closed.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to the modified context.
    pub async fn close(&self) -> &Self {
        self.set_closed(true).await
    }

    /// Opens the connection (clears the closed flag).
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to the modified context.
    pub async fn open(&self) -> &Self {
        self.set_closed(false).await
    }

    /// Checks if the connection has been terminated (aborted or closed).
    ///
    /// # Returns
    ///
    /// - `bool` - True if the connection is either aborted or closed, otherwise false.
    pub async fn is_terminated(&self) -> bool {
        self.is_aborted().await || self.is_closed().await
    }

    /// Gets the stream from the context.
    ///
    /// # Returns
    ///
    /// - `Option<ArcRwLockStream>` - The stream if available.
    pub async fn try_get_stream(&self) -> Option<ArcRwLockStream> {
        self.read().await.stream.clone()
    }

    /// Gets the stream from the context.
    ///
    /// # Returns
    ///
    /// - `ArcRwLockStream` - The stream.
    ///
    /// # Panics
    ///
    /// Panics if the stream is not set.
    pub async fn get_stream(&self) -> ArcRwLockStream {
        self.try_get_stream().await.unwrap()
    }

    /// Sets the stream in the context.
    ///
    /// # Arguments
    ///
    /// - `ArcRwLockStream` - The stream to set.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_stream(&self, stream: ArcRwLockStream) -> &Self {
        self.write().await.stream = Some(stream);
        self
    }

    /// Gets the request from the context.
    ///
    /// # Returns
    ///
    /// - `Request` - A clone of the request.
    pub async fn get_request(&self) -> Request {
        self.read().await.request.clone()
    }

    /// Sets the request in the context.
    ///
    /// # Arguments
    ///
    /// - `Request` - The request to set.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_request(&self, request: Request) -> &Self {
        self.write().await.request = request;
        self
    }

    /// Gets the response from the context.
    ///
    /// # Returns
    ///
    /// - `Response` - A clone of the response.
    pub async fn get_response(&self) -> Response {
        self.read().await.response.clone()
    }

    /// Sets the response in the context.
    ///
    /// # Arguments
    ///
    /// - `Response` - The response to set.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_response(&self, response: Response) -> &Self {
        self.write().await.response = response;
        self
    }

    /// Attempts to get the socket address from the stream.
    ///
    /// # Returns
    ///
    /// - `OptionSocketAddr` - The socket address if available.
    pub async fn try_get_socket_addr(&self) -> OptionSocketAddr {
        if let Some(stream) = self.try_get_stream().await {
            return stream.try_get_peer_addr().await;
        }
        None
    }

    /// Gets the socket address.
    ///
    /// # Returns
    ///
    /// - `SocketAddr` - The socket address.
    ///
    /// # Panics
    ///
    /// Panics if the socket address is not available.
    pub async fn get_socket_addr(&self) -> SocketAddr {
        self.try_get_socket_addr().await.unwrap()
    }

    /// Gets the socket address as a string.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - The socket address as a string if available.
    pub async fn try_get_socket_addr_string(&self) -> Option<String> {
        self.try_get_socket_addr()
            .await
            .map(|addr| addr.to_string())
    }

    /// Gets the socket address as a string.
    ///
    /// # Returns
    ///
    /// - `String` - The socket address as a string.
    ///
    /// # Panics
    ///
    /// Panics if the socket address is not available.
    pub async fn get_socket_addr_string(&self) -> String {
        self.get_socket_addr().await.to_string()
    }

    /// Attempts to get the socket host (IP address).
    ///
    /// # Returns
    ///
    /// - `OptionSocketHost` - The socket host if available.
    pub async fn try_get_socket_host(&self) -> OptionSocketHost {
        self.try_get_socket_addr().await.map(|addr| addr.ip())
    }

    /// Gets the socket host.
    ///
    /// # Returns
    ///
    /// - `std::net::IpAddr` - The socket host.
    ///
    /// # Panics
    ///
    /// Panics if the socket host is not available.
    pub async fn get_socket_host(&self) -> std::net::IpAddr {
        self.try_get_socket_host().await.unwrap()
    }

    /// Attempts to get the socket port.
    ///
    /// # Returns
    ///
    /// - `OptionSocketPort` - The socket port if available.
    pub async fn try_get_socket_port(&self) -> OptionSocketPort {
        self.try_get_socket_addr().await.map(|addr| addr.port())
    }

    /// Gets the socket port.
    ///
    /// # Returns
    ///
    /// - `u16` - The socket port.
    ///
    /// # Panics
    ///
    /// Panics if the socket port is not available.
    pub async fn get_socket_port(&self) -> u16 {
        self.try_get_socket_port().await.unwrap()
    }

    /// Sets a data value in the context's data map.
    ///
    /// # Arguments
    ///
    /// - `Into<String>` - The key for the data.
    /// - `Any + Send + Sync + Clone` - The value to set, which must be cloneable and thread-safe.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn set_data<K, V>(&self, key: K, value: V) -> &Self
    where
        K: Into<String>,
        V: Any + Send + Sync + Clone,
    {
        self.write()
            .await
            .attributes
            .insert(key.into(), Arc::new(value));
        self
    }

    /// Gets a data value from the context's data map.
    ///
    /// # Arguments
    ///
    /// - `AsRef<str>` - The key for the data.
    ///
    /// # Returns
    ///
    /// - `Option<V>` - The data value if found and successfully downcasted, otherwise `None`.
    pub async fn try_get_data<V, K>(&self, key: K) -> Option<V>
    where
        V: Any + Send + Sync + Clone,
        K: AsRef<str>,
    {
        self.read()
            .await
            .attributes
            .get(key.as_ref())
            .and_then(|arc| arc.downcast_ref::<V>())
            .cloned()
    }

    /// Gets a data value from the context's data map.
    ///
    /// # Arguments
    ///
    /// - `AsRef<str>` - The key for the data.
    ///
    /// # Returns
    ///
    /// - `V` - The data value.
    ///
    /// # Panics
    ///
    /// Panics if the data is not found or cannot be downcasted.
    pub async fn get_data_value<V, K>(&self, key: K) -> V
    where
        V: Any + Send + Sync + Clone,
        K: AsRef<str>,
    {
        self.try_get_data(key).await.unwrap()
    }

    /// Removes a data value from the context's data map.
    ///
    /// # Arguments
    ///
    /// - `AsRef<str>` - The key of the data to remove.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn remove_data<K>(&self, key: K) -> &Self
    where
        K: AsRef<str>,
    {
        self.write().await.attributes.remove(key.as_ref());
        self
    }

    /// Clears all data from the context's data map.
    ///
    /// # Returns
    ///
    /// - `&Self` - Reference to self for method chaining.
    pub async fn clear_data(&self) -> &Self {
        self.write().await.attributes.clear();
        self
    }

    /// Attempts to send data through the stream.
    ///
    /// # Arguments
    ///
    /// - `D` - Data that can be converted to a byte slice.
    ///
    /// # Returns
    ///
    /// - `ResponseResult` - Ok(()) on success, or an error on failure.
    pub async fn try_send<D>(&self, data: D) -> ResponseResult
    where
        D: AsRef<[u8]>,
    {
        if self.is_terminated().await {
            return Err(ResponseError::Terminated);
        }
        if let Some(stream) = self.try_get_stream().await {
            return stream.try_send(data).await;
        }
        Err(ResponseError::NotFoundStream)
    }

    /// Sends data through the stream.
    ///
    /// # Arguments
    ///
    /// - `D` - Data that can be converted to a byte slice.
    ///
    /// # Panics
    ///
    /// Panics if the send operation fails.
    pub async fn send<D>(&self, data: D)
    where
        D: AsRef<[u8]>,
    {
        self.try_send(data).await.unwrap();
    }

    /// Attempts to flush the stream.
    ///
    /// # Returns
    ///
    /// - `ResponseResult` - Ok(()) on success, or an error on failure.
    pub async fn try_flush(&self) -> ResponseResult {
        if self.is_terminated().await {
            return Err(ResponseError::Terminated);
        }
        if let Some(stream) = self.try_get_stream().await {
            return stream.try_flush().await;
        }
        Err(ResponseError::NotFoundStream)
    }

    /// Flushes the stream.
    ///
    /// # Panics
    ///
    /// Panics if the flush operation fails.
    pub async fn flush(&self) {
        self.try_flush().await.unwrap();
    }

    /// Attempts to shut down the stream.
    ///
    /// # Returns
    ///
    /// - `ResponseResult` - Ok(()) on success, or an error on failure.
    pub async fn try_shutdown(&self) -> ResponseResult {
        if let Some(stream) = self.try_get_stream().await {
            let result: ResponseResult = stream.try_shutdown().await;
            self.close().await;
            return result;
        }
        Err(ResponseError::NotFoundStream)
    }

    /// Shuts down the stream.
    ///
    /// # Panics
    ///
    /// Panics if the shutdown operation fails.
    pub async fn shutdown(&self) {
        self.try_shutdown().await.unwrap();
    }
}