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
//! IP address type for network programming.
//!
//! This module provides a type-safe abstraction for IP addresses (IPv4 and IPv6),
//! wrapping the standard library's `IpAddr` type.
//!
//! # Examples
//!
//! ```rust
//! use bare_types::net::IpAddr;
//! use core::net::{Ipv4Addr, Ipv6Addr};
//!
//! // Create an IPv4 address
//! let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
//! assert!(v4.is_ipv4());
//! assert!(v4.is_loopback());
//!
//! // Create an IPv6 address
//! let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
//! assert!(v6.is_ipv6());
//! assert!(v6.is_loopback());
//!
//! // Parse from string
//! let addr: IpAddr = "192.168.1.1".parse()?;
//! # Ok::<(), bare_types::net::IpAddrError>(())
//! ```

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

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

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

/// Error type for IP address parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum IpAddrError {
    /// Invalid IP address format
    ///
    /// The input string is not a valid IPv4 or IPv6 address.
    /// IPv4 addresses must be in dotted decimal notation (e.g., "192.168.1.1").
    /// IPv6 addresses must be in colon-separated hexadecimal notation (e.g., "`::1`").
    InvalidFormat,
}

impl fmt::Display for IpAddrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat => write!(f, "invalid IP address format"),
        }
    }
}

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

/// An IP address (IPv4 or IPv6).
///
/// This type wraps the standard library's `IpAddr` to provide type safety
/// and consistent API with other types in this crate. It uses the newtype
/// pattern with `#[repr(transparent)]` for zero-cost abstraction.
///
/// # Invariants
///
/// - The inner value is always a valid IP address
/// - IPv4 addresses are 4 octets (0-255 each)
/// - IPv6 addresses are 8 groups of 16 bits
///
/// # Examples
///
/// ```rust
/// use bare_types::net::IpAddr;
/// use core::net::{Ipv4Addr, Ipv6Addr};
///
/// // Create an IPv4 address
/// let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
/// assert!(v4.is_ipv4());
/// assert!(v4.is_loopback());
///
/// // Create an IPv6 address
/// let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
/// assert!(v6.is_ipv6());
/// assert!(v6.is_loopback());
///
/// // Access the inner value
/// let inner: core::net::IpAddr = v4.into_inner();
/// assert_eq!(inner, core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
///
/// // Parse from string
/// let addr: IpAddr = "192.168.1.1".parse()?;
/// assert!(addr.is_ipv4());
/// # Ok::<(), bare_types::net::IpAddrError>(())
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub struct IpAddr(core::net::IpAddr);

impl IpAddr {
    /// Creates a new IP address from a standard library `IpAddr`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::Ipv4Addr;
    ///
    /// let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// assert!(addr.is_ipv4());
    /// ```
    #[inline]
    #[must_use]
    pub const fn new(inner: core::net::IpAddr) -> Self {
        Self(inner)
    }

    /// Returns a reference to the underlying `IpAddr`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::Ipv4Addr;
    ///
    /// let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// let inner = addr.as_inner();
    /// assert_eq!(inner, &core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_inner(&self) -> &core::net::IpAddr {
        &self.0
    }

    /// Consumes this IP address and returns the underlying `IpAddr`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::Ipv4Addr;
    ///
    /// let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// let inner: core::net::IpAddr = addr.into_inner();
    /// assert_eq!(inner, core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// ```
    #[must_use]
    #[inline]
    pub const fn into_inner(self) -> core::net::IpAddr {
        self.0
    }

    /// Returns `true` if this is an IPv4 address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
    ///
    /// assert!(v4.is_ipv4());
    /// assert!(!v6.is_ipv4());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_ipv4(&self) -> bool {
        self.0.is_ipv4()
    }

    /// Returns `true` if this is an IPv6 address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
    ///
    /// assert!(!v4.is_ipv6());
    /// assert!(v6.is_ipv6());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_ipv6(&self) -> bool {
        self.0.is_ipv6()
    }

    /// Returns `true` if this is a loopback address.
    ///
    /// For IPv4, this is 127.0.0.1.
    /// For IPv6, this is `::1`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let v4_loopback = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
    /// let v6_loopback = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
    ///
    /// assert!(v4_loopback.is_loopback());
    /// assert!(v6_loopback.is_loopback());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_loopback(&self) -> bool {
        self.0.is_loopback()
    }

    /// Returns `true` if this is an unspecified address.
    ///
    /// For IPv4, this is 0.0.0.0.
    /// For IPv6, this is ::.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let v4_unspecified = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));
    /// let v6_unspecified = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)));
    ///
    /// assert!(v4_unspecified.is_unspecified());
    /// assert!(v6_unspecified.is_unspecified());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_unspecified(&self) -> bool {
        self.0.is_unspecified()
    }

    /// Returns `true` if this is a multicast address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::IpAddr;
    /// use core::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let v4_multicast = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)));
    /// let v6_multicast = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)));
    ///
    /// assert!(v4_multicast.is_multicast());
    /// assert!(v6_multicast.is_multicast());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_multicast(&self) -> bool {
        self.0.is_multicast()
    }
}

impl From<core::net::IpAddr> for IpAddr {
    fn from(inner: core::net::IpAddr) -> Self {
        Self(inner)
    }
}

impl From<IpAddr> for core::net::IpAddr {
    fn from(addr: IpAddr) -> Self {
        addr.0
    }
}

impl FromStr for IpAddr {
    type Err = IpAddrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<core::net::IpAddr>()
            .map(Self)
            .map_err(|_| IpAddrError::InvalidFormat)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use core::net::{Ipv4Addr, Ipv6Addr};

    #[test]
    fn test_new_ipv4() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        assert!(addr.is_ipv4());
        assert!(!addr.is_ipv6());
    }

    #[test]
    fn test_new_ipv6() {
        let addr = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::LOCALHOST));
        assert!(addr.is_ipv6());
        assert!(!addr.is_ipv4());
    }

    #[test]
    fn test_as_inner() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let inner = addr.as_inner();
        assert_eq!(inner, &core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
    }

    #[test]
    fn test_into_inner() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let inner: core::net::IpAddr = addr.into_inner();
        assert_eq!(inner, core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
    }

    #[test]
    fn test_is_ipv4() {
        let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::LOCALHOST));

        assert!(v4.is_ipv4());
        assert!(!v6.is_ipv4());
    }

    #[test]
    fn test_is_ipv6() {
        let v4 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let v6 = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::LOCALHOST));

        assert!(!v4.is_ipv6());
        assert!(v6.is_ipv6());
    }

    #[test]
    fn test_is_loopback() {
        let v4_loopback = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let v6_loopback = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::LOCALHOST));
        let v4_not_loopback = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));

        assert!(v4_loopback.is_loopback());
        assert!(v6_loopback.is_loopback());
        assert!(!v4_not_loopback.is_loopback());
    }

    #[test]
    fn test_is_unspecified() {
        let v4_unspecified = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::UNSPECIFIED));
        let v6_unspecified = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::UNSPECIFIED));
        let v4_specified = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));

        assert!(v4_unspecified.is_unspecified());
        assert!(v6_unspecified.is_unspecified());
        assert!(!v4_specified.is_unspecified());
    }

    #[test]
    fn test_is_multicast() {
        let v4_multicast = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(224, 0, 0, 1)));
        let v6_multicast = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::new(
            0xff00, 0, 0, 0, 0, 0, 0, 0,
        )));
        let v4_not_multicast = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));

        assert!(v4_multicast.is_multicast());
        assert!(v6_multicast.is_multicast());
        assert!(!v4_not_multicast.is_multicast());
    }

    #[test]
    fn test_from_std_ipaddr() {
        let std_addr = core::net::IpAddr::V4(Ipv4Addr::LOCALHOST);
        let addr = IpAddr::from(std_addr);
        assert!(addr.is_ipv4());
    }

    #[test]
    fn test_into_std_ipaddr() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let std_addr: core::net::IpAddr = addr.into();
        assert_eq!(std_addr, core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
    }

    #[test]
    fn test_from_str_ipv4() {
        let addr: IpAddr = "127.0.0.1".parse().unwrap();
        assert!(addr.is_ipv4());
        assert!(addr.is_loopback());
    }

    #[test]
    fn test_from_str_ipv6() {
        let addr: IpAddr = "::1".parse().unwrap();
        assert!(addr.is_ipv6());
        assert!(addr.is_loopback());
    }

    #[test]
    fn test_from_str_invalid() {
        let result: Result<IpAddr, _> = "invalid".parse();
        assert!(result.is_err());
    }

    #[test]
    fn test_display_ipv4() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
        assert_eq!(format!("{addr}"), "192.168.1.1");
    }

    #[test]
    fn test_display_ipv6() {
        let addr = IpAddr::new(core::net::IpAddr::V6(Ipv6Addr::LOCALHOST));
        assert_eq!(format!("{addr}"), "::1");
    }

    #[test]
    fn test_equality() {
        let addr1 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let addr2 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let addr3 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));

        assert_eq!(addr1, addr2);
        assert_ne!(addr1, addr3);
    }

    #[test]
    fn test_ordering() {
        let addr1 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let addr2 = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));

        assert!(addr1 < addr2);
    }

    #[test]
    fn test_copy() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let addr2 = addr;
        assert_eq!(addr, addr2);
    }

    #[test]
    fn test_clone() {
        let addr = IpAddr::new(core::net::IpAddr::V4(Ipv4Addr::LOCALHOST));
        let addr2 = addr;
        assert_eq!(addr, addr2);
    }

    #[test]
    fn test_error_display() {
        let err = IpAddrError::InvalidFormat;
        assert_eq!(format!("{err}"), "invalid IP address format");
    }
}