bare-types 0.3.0

A zero-cost foundation for type-safe domain modeling in Rust. Implements the 'Parse, don't validate' philosophy to eliminate primitive obsession and ensure data integrity at the system boundary.
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
//! Port number type for network programming.
//!
//! This module provides a type-safe abstraction for network port numbers,
//! ensuring valid port ranges and providing convenient access to common service ports.
//!
//! # Port Ranges
//!
//! According to [IANA port assignments](https://www.iana.org/assignments/service-names-port-numbers/):
//!
//! - **1-1023**: System ports (well-known ports, require privileges)
//! - **1024-49151**: Registered ports (user ports, IANA registered)
//! - **49152-65535**: Dynamic/Private ports (ephemeral ports)
//!
//! Note: Port 0 is reserved and rejected by this type.
//!
//! # Examples
//!
//! ```rust
//! use bare_types::net::Port;
//!
//! // Create a port from a number
//! let port = Port::new(8080)?;
//!
//! // Check port category
//! assert!(port.is_registered_port());
//!
//! // Get the underlying value
//! assert_eq!(port.as_u16(), 8080);
//!
//! // Use common service ports
//! assert_eq!(Port::HTTP.as_u16(), 80);
//! assert_eq!(Port::HTTPS.as_u16(), 443);
//!
//! // Parse from string
//! let port: Port = "8080".parse()?;
//! # Ok::<(), bare_types::net::PortError>(())
//! ```

use core::fmt;
use core::str::FromStr;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;

#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

/// Error type for port number validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum PortError {
    /// Port 0 is reserved and cannot be used
    ///
    /// Port 0 is reserved by IANA and cannot be used for network connections.
    /// Valid port numbers are in the range 1-65535.
    PortZero,
    /// Port number out of valid valid range
    ///
    /// The provided port number exceeds the maximum valid value (65535).
    /// This variant contains the invalid port value.
    OutOfRange(u16),
    /// Invalid port format (non-numeric string)
    ///
    /// The input string could not be parsed as a valid port number.
    /// Port numbers must be numeric (digits only).
    InvalidFormat,
}

impl fmt::Display for PortError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PortZero => write!(f, "port 0 is reserved and cannot be used"),
            Self::OutOfRange(port) => write!(f, "port number {port} is out of valid range"),
            Self::InvalidFormat => write!(f, "invalid port format"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PortError {}

/// A network port number (1-65535).
///
/// This type provides type-safe port numbers with validation and categorization.
/// It uses the newtype pattern with `#[repr(transparent)]` for zero-cost abstraction.
///
/// # Invariants
///
/// - The inner value is always in the range 1-65535
/// - Ports 1-1023 are system ports (require privileges)
/// - Ports 1024-49151 are registered ports
/// - Ports 49152-65535 are dynamic/private ports
///
/// # Examples
///
/// ```rust
/// use bare_types::net::Port;
///
/// // Create a port
/// let port = Port::new(8080)?;
///
/// // Access the value
/// assert_eq!(port.as_u16(), 8080);
///
/// // Convert back to u16
/// let value: u16 = port.into();
/// assert_eq!(value, 8080);
///
/// // Parse from string
/// let port: Port = "443".parse()?;
/// assert_eq!(port, Port::HTTPS);
/// # Ok::<(), bare_types::net::PortError>(())
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "zeroize", derive(Zeroize))]
pub struct Port(u16);

impl Port {
    /// Creates a new port number.
    ///
    /// # Errors
    ///
    /// Returns `PortError::PortZero` if port is 0 (reserved).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// let port = Port::new(8080)?;
    /// assert_eq!(port.as_u16(), 8080);
    /// # Ok::<(), bare_types::net::PortError>(())
    /// ```
    pub const fn new(port: u16) -> Result<Self, PortError> {
        if port == 0 {
            return Err(PortError::PortZero);
        }
        Ok(Self(port))
    }

    /// Returns the underlying port number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// let port = Port::HTTP;
    /// assert_eq!(port.as_u16(), 80);
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_u16(&self) -> u16 {
        self.0
    }

    /// Consumes this port and returns the underlying port number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// let port = Port::HTTP;
    /// assert_eq!(port.into_u16(), 80);
    /// ```
    #[must_use]
    #[inline]
    pub const fn into_u16(self) -> u16 {
        self.0
    }

    /// Returns `true` if this is a system port (1-1023).
    ///
    /// System ports are well-known ports that typically require privileges to bind to.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// assert!(Port::HTTP.is_system_port());
    /// assert!(Port::SSH.is_system_port());
    /// assert!(!Port::HTTP_ALT.is_system_port());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_system_port(&self) -> bool {
        self.0 >= 1 && self.0 <= 1023
    }

    /// Returns `true` if this is a registered port (1024-49151).
    ///
    /// Registered ports are user ports registered with IANA.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// assert!(Port::MYSQL.is_registered_port());
    /// assert!(Port::POSTGRESQL.is_registered_port());
    /// assert!(!Port::HTTP.is_registered_port());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_registered_port(&self) -> bool {
        self.0 >= 1024 && self.0 <= 49151
    }

    /// Returns `true` if this is a dynamic/private port (49152-65535).
    ///
    /// Dynamic ports are typically used for temporary connections.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Port;
    ///
    /// assert!(Port::new(50000).unwrap().is_dynamic_port());
    /// assert!(!Port::HTTP.is_dynamic_port());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_dynamic_port(&self) -> bool {
        self.0 >= 49152
    }

    /// HTTP port (80)
    pub const HTTP: Self = Self(80);

    /// HTTPS port (443)
    pub const HTTPS: Self = Self(443);

    /// SSH port (22)
    pub const SSH: Self = Self(22);

    /// FTP port (21)
    pub const FTP: Self = Self(21);

    /// FTP data port (20)
    pub const FTP_DATA: Self = Self(20);

    /// SMTP port (25)
    pub const SMTP: Self = Self(25);

    /// DNS port (53)
    pub const DNS: Self = Self(53);

    /// DNS over TLS port (853)
    pub const DNS_OVER_TLS: Self = Self(853);

    /// POP3 port (110)
    pub const POP3: Self = Self(110);

    /// POP3S port (995)
    pub const POP3S: Self = Self(995);

    /// IMAP port (143)
    pub const IMAP: Self = Self(143);

    /// IMAPS port (993)
    pub const IMAPS: Self = Self(993);

    /// Telnet port (23)
    pub const TELNET: Self = Self(23);

    /// Telnet over SSL port (992)
    pub const TELNETS: Self = Self(992);

    /// `MySQL` port (3306)
    pub const MYSQL: Self = Self(3306);

    /// `PostgreSQL` port (5432)
    pub const POSTGRESQL: Self = Self(5432);

    /// `Redis` port (6379)
    pub const REDIS: Self = Self(6379);

    /// `MongoDB` port (27017)
    pub const MONGODB: Self = Self(27017);

    /// HTTP alternate port (8080)
    pub const HTTP_ALT: Self = Self(8080);

    /// HTTPS alternate port (8443)
    pub const HTTPS_ALT: Self = Self(8443);
}

impl TryFrom<u16> for Port {
    type Error = PortError;

    fn try_from(port: u16) -> Result<Self, Self::Error> {
        Self::new(port)
    }
}

impl TryFrom<&str> for Port {
    type Error = PortError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let port: u16 = s.parse().map_err(|_| PortError::InvalidFormat)?;
        Self::new(port)
    }
}

impl From<Port> for u16 {
    fn from(port: Port) -> Self {
        port.0
    }
}

impl FromStr for Port {
    type Err = PortError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let port: u16 = s.parse().map_err(|_| PortError::InvalidFormat)?;
        Self::new(port)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_valid_port() {
        assert!(Port::new(80).is_ok());
        assert!(Port::new(8080).is_ok());
        assert!(Port::new(65535).is_ok());
    }

    #[test]
    fn test_port_zero_rejected() {
        assert_eq!(Port::new(0), Err(PortError::PortZero));
    }

    #[test]
    fn test_as_u16() {
        let port = Port::new(8080).unwrap();
        assert_eq!(port.as_u16(), 8080);
    }

    #[test]
    fn test_into_u16() {
        let port = Port::new(8080).unwrap();
        assert_eq!(port.into_u16(), 8080);
    }

    #[test]
    fn test_is_system_port() {
        assert!(Port::HTTP.is_system_port());
        assert!(Port::HTTPS.is_system_port());
        assert!(Port::SSH.is_system_port());
        assert!(Port::FTP.is_system_port());
        assert!(Port::SMTP.is_system_port());
        assert!(Port::DNS.is_system_port());
        assert!(Port::POP3.is_system_port());
        assert!(Port::IMAP.is_system_port());
        assert!(Port::TELNET.is_system_port());
        assert!(!Port::HTTP_ALT.is_system_port());
        assert!(!Port::MYSQL.is_system_port());
    }

    #[test]
    fn test_is_registered_port() {
        assert!(Port::MYSQL.is_registered_port());
        assert!(Port::POSTGRESQL.is_registered_port());
        assert!(Port::REDIS.is_registered_port());
        assert!(Port::HTTP_ALT.is_registered_port());
        assert!(!Port::HTTP.is_registered_port());
        assert!(!Port::new(50000).unwrap().is_registered_port());
    }

    #[test]
    fn test_is_dynamic_port() {
        assert!(Port::new(49152).unwrap().is_dynamic_port());
        assert!(Port::new(50000).unwrap().is_dynamic_port());
        assert!(Port::new(65535).unwrap().is_dynamic_port());
        assert!(!Port::HTTP.is_dynamic_port());
        assert!(!Port::MYSQL.is_dynamic_port());
    }

    #[test]
    fn test_port_zero_error_message() {
        let err = Port::new(0).unwrap_err();
        assert_eq!(format!("{err}"), "port 0 is reserved and cannot be used");
    }

    #[test]
    fn test_service_port_constants() {
        assert_eq!(Port::HTTP.as_u16(), 80);
        assert_eq!(Port::HTTPS.as_u16(), 443);
        assert_eq!(Port::SSH.as_u16(), 22);
        assert_eq!(Port::FTP.as_u16(), 21);
        assert_eq!(Port::FTP_DATA.as_u16(), 20);
        assert_eq!(Port::SMTP.as_u16(), 25);
        assert_eq!(Port::DNS.as_u16(), 53);
        assert_eq!(Port::DNS_OVER_TLS.as_u16(), 853);
        assert_eq!(Port::POP3.as_u16(), 110);
        assert_eq!(Port::POP3S.as_u16(), 995);
        assert_eq!(Port::IMAP.as_u16(), 143);
        assert_eq!(Port::IMAPS.as_u16(), 993);
        assert_eq!(Port::TELNET.as_u16(), 23);
        assert_eq!(Port::TELNETS.as_u16(), 992);
        assert_eq!(Port::MYSQL.as_u16(), 3306);
        assert_eq!(Port::POSTGRESQL.as_u16(), 5432);
        assert_eq!(Port::REDIS.as_u16(), 6379);
        assert_eq!(Port::MONGODB.as_u16(), 27017);
        assert_eq!(Port::HTTP_ALT.as_u16(), 8080);
        assert_eq!(Port::HTTPS_ALT.as_u16(), 8443);
    }

    #[test]
    fn test_try_from_u16() {
        assert_eq!(Port::try_from(80).unwrap(), Port::HTTP);
        assert_eq!(Port::try_from(8080).unwrap().as_u16(), 8080);
    }

    #[test]
    fn test_from_port_to_u16() {
        let port = Port::HTTP;
        let value: u16 = port.into();
        assert_eq!(value, 80);
    }

    #[test]
    fn test_from_str() {
        assert_eq!("80".parse::<Port>().unwrap(), Port::HTTP);
        assert_eq!("8080".parse::<Port>().unwrap().as_u16(), 8080);
        assert_eq!("65535".parse::<Port>().unwrap().as_u16(), 65535);
        assert!("70000".parse::<Port>().is_err());
        assert!("abc".parse::<Port>().is_err());
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", Port::HTTP), "80");
        assert_eq!(format!("{}", Port::HTTP_ALT), "8080");
    }

    #[test]
    fn test_equality() {
        assert_eq!(Port::HTTP, Port::HTTP);
        assert_eq!(Port::new(8080).unwrap(), Port::new(8080).unwrap());
        assert_ne!(Port::HTTP, Port::HTTPS);
    }

    #[test]
    fn test_ordering() {
        assert!(Port::HTTP < Port::HTTPS);
        assert!(Port::HTTP < Port::HTTP_ALT);
        assert!(Port::HTTPS < Port::HTTP_ALT);
    }

    #[test]
    fn test_copy() {
        let port = Port::HTTP;
        let port2 = port;
        assert_eq!(port, port2);
    }

    #[test]
    fn test_clone() {
        let port = Port::HTTP;
        let port2 = port;
        assert_eq!(port, port2);
    }
}