Skip to content

Commit c41e1a0

Browse files
committed
Implement Arbitrary for SocketAddr{,V4,V6}
1 parent 7ea39f1 commit c41e1a0

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

src/lib.rs

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ use std::borrow::{Cow, ToOwned};
4747
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
4848
use std::ffi::{CString, OsString};
4949
use std::hash::BuildHasher;
50-
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
50+
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
5151
use std::ops::Bound;
5252
use std::path::PathBuf;
5353
use std::rc::Rc;
@@ -1189,6 +1189,59 @@ impl<'a> Arbitrary<'a> for IpAddr {
11891189
}
11901190
}
11911191

1192+
impl<'a> Arbitrary<'a> for SocketAddrV4 {
1193+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1194+
Ok(SocketAddrV4::new(u.arbitrary()?, u.arbitrary()?))
1195+
}
1196+
1197+
#[inline]
1198+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1199+
size_hint::and(Ipv4Addr::size_hint(depth), u16::size_hint(depth))
1200+
}
1201+
}
1202+
1203+
impl<'a> Arbitrary<'a> for SocketAddrV6 {
1204+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1205+
Ok(SocketAddrV6::new(
1206+
u.arbitrary()?,
1207+
u.arbitrary()?,
1208+
u.arbitrary()?,
1209+
u.arbitrary()?,
1210+
))
1211+
}
1212+
1213+
#[inline]
1214+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1215+
size_hint::and(
1216+
Ipv6Addr::size_hint(depth),
1217+
size_hint::and(
1218+
u16::size_hint(depth),
1219+
size_hint::and(u32::size_hint(depth), u32::size_hint(depth)),
1220+
),
1221+
)
1222+
}
1223+
}
1224+
1225+
impl<'a> Arbitrary<'a> for SocketAddr {
1226+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1227+
if u.arbitrary()? {
1228+
Ok(SocketAddr::V4(u.arbitrary()?))
1229+
} else {
1230+
Ok(SocketAddr::V6(u.arbitrary()?))
1231+
}
1232+
}
1233+
1234+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1235+
size_hint::and(
1236+
bool::size_hint(depth),
1237+
size_hint::or(
1238+
SocketAddrV4::size_hint(depth),
1239+
SocketAddrV6::size_hint(depth),
1240+
),
1241+
)
1242+
}
1243+
}
1244+
11921245
#[cfg(test)]
11931246
mod test {
11941247
use super::*;

0 commit comments

Comments
 (0)