Skip to content

Commit 87cef15

Browse files
authored
Merge pull request #169 from wackbyte/arbitrary-for-socketaddr
Implement `Arbitrary` for `SocketAddr{,V4,V6}`
2 parents 0169264 + c41e1a0 commit 87cef15

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;
@@ -1200,6 +1200,59 @@ impl<'a> Arbitrary<'a> for IpAddr {
12001200
}
12011201
}
12021202

1203+
impl<'a> Arbitrary<'a> for SocketAddrV4 {
1204+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1205+
Ok(SocketAddrV4::new(u.arbitrary()?, u.arbitrary()?))
1206+
}
1207+
1208+
#[inline]
1209+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1210+
size_hint::and(Ipv4Addr::size_hint(depth), u16::size_hint(depth))
1211+
}
1212+
}
1213+
1214+
impl<'a> Arbitrary<'a> for SocketAddrV6 {
1215+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1216+
Ok(SocketAddrV6::new(
1217+
u.arbitrary()?,
1218+
u.arbitrary()?,
1219+
u.arbitrary()?,
1220+
u.arbitrary()?,
1221+
))
1222+
}
1223+
1224+
#[inline]
1225+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1226+
size_hint::and(
1227+
Ipv6Addr::size_hint(depth),
1228+
size_hint::and(
1229+
u16::size_hint(depth),
1230+
size_hint::and(u32::size_hint(depth), u32::size_hint(depth)),
1231+
),
1232+
)
1233+
}
1234+
}
1235+
1236+
impl<'a> Arbitrary<'a> for SocketAddr {
1237+
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
1238+
if u.arbitrary()? {
1239+
Ok(SocketAddr::V4(u.arbitrary()?))
1240+
} else {
1241+
Ok(SocketAddr::V6(u.arbitrary()?))
1242+
}
1243+
}
1244+
1245+
fn size_hint(depth: usize) -> (usize, Option<usize>) {
1246+
size_hint::and(
1247+
bool::size_hint(depth),
1248+
size_hint::or(
1249+
SocketAddrV4::size_hint(depth),
1250+
SocketAddrV6::size_hint(depth),
1251+
),
1252+
)
1253+
}
1254+
}
1255+
12031256
#[cfg(test)]
12041257
mod test {
12051258
use super::*;

0 commit comments

Comments
 (0)