diff --git a/Cargo.lock b/Cargo.lock index a62e0cb4..96f35354 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,13 +128,11 @@ checksum = "2911526fe9fc3bb90ff13ff52bd5454e93da0685ba8ed105f06bfc0e898fd950" [[package]] name = "colored" -version = "2.0.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "atty", - "lazy_static", - "winapi", + "windows-sys 0.61.2", ] [[package]] @@ -263,6 +261,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + [[package]] name = "digest" version = "0.10.6" @@ -406,7 +413,7 @@ dependencies = [ "log", "thiserror", "walkdir", - "windows-sys", + "windows-sys 0.45.0", ] [[package]] @@ -430,12 +437,6 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "libc" version = "0.2.142" @@ -464,12 +465,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.17" +version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "memchr" @@ -526,6 +524,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + [[package]] name = "num-integer" version = "0.1.45" @@ -621,7 +625,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.117", ] [[package]] @@ -676,6 +680,12 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -684,18 +694,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.56" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.26" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -706,7 +716,16 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_core 0.9.5", ] [[package]] @@ -716,7 +735,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -725,6 +754,12 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" + [[package]] name = "rayon" version = "1.7.0" @@ -802,10 +837,11 @@ checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" [[package]] name = "serde" -version = "1.0.160" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ + "serde_core", "serde_derive", ] @@ -830,15 +866,24 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + [[package]] name = "serde_derive" -version = "1.0.160" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.117", ] [[package]] @@ -854,15 +899,14 @@ dependencies = [ [[package]] name = "simple_logger" -version = "2.3.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48047e77b528151aaf841a10a9025f9459da80ba820e425ff7eb005708a76dc7" +checksum = "c7038d0e96661bf9ce647e1a6f6ef6d6f3663f66d9bf741abf14ba4876071c17" dependencies = [ - "atty", "colored", "log", "time", - "winapi", + "windows-sys 0.61.2", ] [[package]] @@ -899,9 +943,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.15" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", @@ -934,35 +978,39 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.15", + "syn 2.0.117", ] [[package]] name = "time" -version = "0.3.20" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ + "deranged", "itoa", "libc", + "num-conv", "num_threads", - "serde", + "powerfmt", + "serde_core", "time-core", "time-macros", ] [[package]] name = "time-core" -version = "0.1.0" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.8" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ + "num-conv", "time-core", ] @@ -981,21 +1029,29 @@ name = "tinyvec" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "toad" version = "0.19.1" dependencies = [ "embedded-time", - "lazycell", "log", "naan", "nb", "no-std-net", "openssl", "paste", - "rand", - "rand_chacha", + "rand 0.9.2", + "rand_chacha 0.9.0", "serde", "serde-json-core", "serde_json", @@ -1006,7 +1062,7 @@ dependencies = [ "toad-len 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "toad-macros 0.2.0", "toad-map 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "toad-msg 0.18.1 (registry+https://github.com/rust-lang/crates.io-index)", + "toad-msg 0.18.1", "toad-stem 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-string 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-writable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1025,8 +1081,8 @@ dependencies = [ "no-std-net", "openssl", "paste", - "rand", - "rand_chacha", + "rand 0.8.5", + "rand_chacha 0.3.1", "serde", "serde_json", "tinyvec", @@ -1035,7 +1091,7 @@ dependencies = [ "toad-len 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "toad-macros 0.2.0", "toad-map 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "toad-msg 0.18.1 (registry+https://github.com/rust-lang/crates.io-index)", + "toad-msg 0.18.1", "toad-stem 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-string 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-writable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1126,7 +1182,7 @@ dependencies = [ "toad 0.19.1 (registry+https://github.com/rust-lang/crates.io-index)", "toad-array 0.5.0", "toad-len 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "toad-msg 0.18.1 (registry+https://github.com/rust-lang/crates.io-index)", + "toad-msg 0.18.1", "toad-stem 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1187,15 +1243,12 @@ dependencies = [ [[package]] name = "toad-msg" version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78ad790094eefd8146fab35178e23b224285fe9b275132a31872c0f74b1a8ff" dependencies = [ - "arrayvec", "blake2", - "coap-lite", - "criterion", - "heapless", - "itertools", "tinyvec", - "toad-array 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "toad-array 0.2.3", "toad-cursor 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-hash 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-len 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1205,13 +1258,16 @@ dependencies = [ [[package]] name = "toad-msg" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ad790094eefd8146fab35178e23b224285fe9b275132a31872c0f74b1a8ff" +version = "0.19.0" dependencies = [ + "arrayvec", "blake2", + "coap-lite", + "criterion", + "heapless", + "itertools", "tinyvec", - "toad-array 0.2.3", + "toad-array 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-cursor 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-hash 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "toad-len 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1402,6 +1458,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-sys" version = "0.45.0" @@ -1411,6 +1473,15 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.42.2" diff --git a/toad-array/Cargo.toml b/toad-array/Cargo.toml index e3d9ec9d..3ed06ab7 100644 --- a/toad-array/Cargo.toml +++ b/toad-array/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-array" version = "0.8.0" edition = "2021" +rust-version = "1.70" description = "Array trait used by the toad ecosystem to abstract over heap or heapless collections" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -22,5 +23,5 @@ test = [] docs = [] [dependencies] -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} toad-len = {version = "^0.1.2", default_features = false} diff --git a/toad-array/src/lib.rs b/toad-array/src/lib.rs index f652a867..0abf1119 100644 --- a/toad-array/src/lib.rs +++ b/toad-array/src/lib.rs @@ -36,8 +36,7 @@ use toad_len::Len; /// Operations on ordered indexed collections pub trait Indexed -where - Self: Len + Deref, + where Self: Len + Deref { /// Insert a new element at `ix`, shifting all other elements to the right. /// @@ -182,8 +181,7 @@ where /// assert_eq!(v, vec![5]); /// ``` fn drop_while(&mut self, f: F) - where - F: for<'a> Fn(&'a T) -> bool, + where F: for<'a> Fn(&'a T) -> bool { match self.get(0) { | Some(t) if !f(&t) => return, @@ -202,8 +200,7 @@ where /// - `Vec` is `Reserve`, and invokes `Vec::with_capacity` /// - `tinyvec::ArrayVec` is `Reserve` and invokes `Default::default()` because creating an `ArrayVec` automatically allocates the required space on the stack. pub trait Reserve -where - Self: Default, + where Self: Default { /// Create an instance of the collection with a given capacity. /// @@ -221,8 +218,7 @@ where /// /// If self was longer, drops elements up to `len` pub trait Trunc -where - Self: Sized, + where Self: Sized { #[allow(missing_docs)] fn trunc(&mut self, len: usize) -> (); @@ -240,9 +236,7 @@ impl Trunc for Vec { } } -impl Trunc for tinyvec::ArrayVec<[T; N]> -where - T: Default, +impl Trunc for tinyvec::ArrayVec<[T; N]> where T: Default { fn trunc(&mut self, len: usize) -> () { self.truncate(len) @@ -257,24 +251,21 @@ where pub trait Filled: Sized { #[allow(missing_docs)] fn filled(t: T) -> Option - where - T: Copy, + where T: Copy { Self::filled_using(|| t) } #[allow(missing_docs)] fn filled_default() -> Option - where - T: Default, + where T: Default { Self::filled_using(|| Default::default()) } #[allow(missing_docs)] fn filled_using(f: F) -> Option - where - F: Fn() -> T; + where F: Fn() -> T; } #[cfg(feature = "alloc")] @@ -287,8 +278,7 @@ impl Reserve for Vec { #[cfg(feature = "alloc")] impl Filled for Vec { fn filled_using(_: F) -> Option - where - F: Fn() -> T, + where F: Fn() -> T { None } @@ -296,20 +286,16 @@ impl Filled for Vec { impl Reserve for tinyvec::ArrayVec {} -impl Filled for tinyvec::ArrayVec<[T; N]> -where - T: Default, +impl Filled for tinyvec::ArrayVec<[T; N]> where T: Default { fn filled_using(f: F) -> Option - where - F: Fn() -> T, + where F: Fn() -> T { Some(core::iter::repeat(()).take(N).map(|_| f()).collect()) } fn filled(t: T) -> Option - where - T: Copy, + where T: Copy { Some(Self::from([t; N])) } @@ -361,8 +347,7 @@ pub trait Array: /// Collections that support extending themselves mutably from copyable slices pub trait AppendCopy -where - T: Copy, + where T: Copy { /// Extend self mutably, copying from a slice. /// @@ -375,9 +360,7 @@ where } #[cfg(feature = "alloc")] -impl AppendCopy for Vec -where - T: Copy, +impl AppendCopy for Vec where T: Copy { fn append_copy(&mut self, i: &[T]) { self.extend(i); @@ -385,9 +368,8 @@ where } impl AppendCopy for tinyvec::ArrayVec -where - T: Copy, - A: tinyvec::Array, + where T: Copy, + A: tinyvec::Array { fn append_copy(&mut self, i: &[T]) { self.extend_from_slice(i); @@ -415,17 +397,15 @@ impl Indexed for Vec { } impl Array for tinyvec::ArrayVec -where - Self: Filled + Trunc, - A: tinyvec::Array, + where Self: Filled + Trunc, + A: tinyvec::Array { type Item = T; } impl Indexed for tinyvec::ArrayVec -where - Self: Filled + Trunc, - A: tinyvec::Array, + where Self: Filled + Trunc, + A: tinyvec::Array { fn insert(&mut self, ix: usize, t: A::Item) { tinyvec::ArrayVec::insert(self, ix, t) diff --git a/toad-common/Cargo.toml b/toad-common/Cargo.toml index b0a4f06f..102ceed8 100644 --- a/toad-common/Cargo.toml +++ b/toad-common/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-common" version = "0.15.0" edition = "2021" +rust-version = "1.70" description = "Common structs and abstractions used by toad" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -22,5 +23,5 @@ test = [] docs = [] [dependencies] -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} blake2 = "0.10" diff --git a/toad-common/src/array.rs b/toad-common/src/array.rs index 6eb46f8a..505c355d 100644 --- a/toad-common/src/array.rs +++ b/toad-common/src/array.rs @@ -103,8 +103,7 @@ pub trait Reserve: Default { /// /// If self was longer, drops elements up to `len` pub trait Trunc -where - Self: Sized, + where Self: Sized { #[allow(missing_docs)] fn trunc(&mut self, len: usize) -> (); @@ -122,9 +121,7 @@ impl Trunc for Vec { } } -impl Trunc for tinyvec::ArrayVec<[T; N]> -where - T: Default, +impl Trunc for tinyvec::ArrayVec<[T; N]> where T: Default { fn trunc(&mut self, len: usize) -> () { self.truncate(len) @@ -139,24 +136,21 @@ where pub trait Filled: Sized { #[allow(missing_docs)] fn filled(t: T) -> Option - where - T: Copy, + where T: Copy { Self::filled_using(|| t) } #[allow(missing_docs)] fn filled_default() -> Option - where - T: Default, + where T: Default { Self::filled_using(|| Default::default()) } #[allow(missing_docs)] fn filled_using(f: F) -> Option - where - F: Fn() -> T; + where F: Fn() -> T; } #[cfg(feature = "alloc")] @@ -169,8 +163,7 @@ impl Reserve for Vec { #[cfg(feature = "alloc")] impl Filled for Vec { fn filled_using(_: F) -> Option - where - F: Fn() -> T, + where F: Fn() -> T { None } @@ -178,20 +171,16 @@ impl Filled for Vec { impl Reserve for tinyvec::ArrayVec {} -impl Filled for tinyvec::ArrayVec<[T; N]> -where - T: Default, +impl Filled for tinyvec::ArrayVec<[T; N]> where T: Default { fn filled_using(f: F) -> Option - where - F: Fn() -> T, + where F: Fn() -> T { Some(core::iter::repeat(()).take(N).map(|_| f()).collect()) } fn filled(t: T) -> Option - where - T: Copy, + where T: Copy { Some(Self::from([t; N])) } @@ -293,9 +282,7 @@ impl Array for Vec { } } -impl, T> Array for tinyvec::ArrayVec -where - Self: Filled + Trunc, +impl, T> Array for tinyvec::ArrayVec where Self: Filled + Trunc { type Item = T; diff --git a/toad-common/src/cursor.rs b/toad-common/src/cursor.rs index 7cf005df..e6938411 100644 --- a/toad-common/src/cursor.rs +++ b/toad-common/src/cursor.rs @@ -73,9 +73,9 @@ impl> Cursor { #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option { self.take_exact(1).and_then(|a| match a { - | &[a] => Some(a), - | _ => None, - }) + | &[a] => Some(a), + | _ => None, + }) } /// Take `n` bytes from the cursor, stopping early if @@ -83,12 +83,15 @@ impl> Cursor { /// /// Runs in O(1) time. pub fn take(&mut self, n: usize) -> &[u8] { - Self::peek_(self.len, self.cursor, &self.t, n) - .map(|a| { - Self::skip_(&mut self.cursor, self.len, n); - a - }) - .unwrap_or_else(|| Self::take_until_end_(&mut self.cursor, self.len, &self.t)) + Self::peek_(self.len, self.cursor, &self.t, n).map(|a| { + Self::skip_(&mut self.cursor, self.len, n); + a + }) + .unwrap_or_else(|| { + Self::take_until_end_(&mut self.cursor, + self.len, + &self.t) + }) } /// Take `n` bytes from the cursor, returning None if @@ -97,9 +100,9 @@ impl> Cursor { /// Runs in O(1) time. pub fn take_exact(&mut self, n: usize) -> Option<&[u8]> { Self::peek_(self.len, self.cursor, &self.t, n).map(|a| { - Self::skip_(&mut self.cursor, self.len, n); - a - }) + Self::skip_(&mut self.cursor, self.len, n); + a + }) } /// Without advancing the position, look at the next @@ -140,16 +143,15 @@ impl> Cursor { return &[]; } - (self.cursor..self.len) - .into_iter() - .take_while(|ix| f(self.t.as_ref()[*ix])) - .last() - .map(|end_ix| { - let out = &self.t.as_ref()[self.cursor..=end_ix]; - self.cursor = end_ix + 1; - out - }) - .unwrap_or(&[]) + (self.cursor..self.len).into_iter() + .take_while(|ix| f(self.t.as_ref()[*ix])) + .last() + .map(|end_ix| { + let out = &self.t.as_ref()[self.cursor..=end_ix]; + self.cursor = end_ix + 1; + out + }) + .unwrap_or(&[]) } /// Whether the cursor has reached the end @@ -267,9 +269,8 @@ mod tests { #[test] pub fn take_while() { let til_slash = |c: &mut Cursor<&str>| { - core::str::from_utf8(c.take_while(|b| (b as char) != '/')) - .unwrap() - .to_string() + core::str::from_utf8(c.take_while(|b| (b as char) != '/')).unwrap() + .to_string() }; let mut cur = Cursor::new("abc/def"); diff --git a/toad-common/src/hash.rs b/toad-common/src/hash.rs index 3a2ad8f3..a7d615e0 100644 --- a/toad-common/src/hash.rs +++ b/toad-common/src/hash.rs @@ -44,8 +44,8 @@ impl Blake2Hasher { impl Debug for Blake2Hasher { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Blake2Hasher") - .field(&">") - .finish() + .field(&">") + .finish() } } diff --git a/toad-common/src/map.rs b/toad-common/src/map.rs index cfdd5307..363961e9 100644 --- a/toad-common/src/map.rs +++ b/toad-common/src/map.rs @@ -42,23 +42,19 @@ pub trait Map: /// See [`HashMap.remove`] fn remove(&mut self, key: &Q) -> Option - where - K: Borrow; + where K: Borrow; /// See [`HashMap.get`] fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a; + where K: Borrow + 'a; /// See [`HashMap.get_mut`] fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a; + where K: Borrow + 'a; /// See [`HashMap.contains_key`] fn has(&self, key: &Q) -> bool - where - K: Borrow, + where K: Borrow { self.get(key).is_some() } @@ -73,96 +69,80 @@ pub trait Map: #[cfg(feature = "alloc")] impl Map for BTreeMap { fn insert(&mut self, key: K, val: V) -> Result<(), InsertError> { - self - .insert(key, val) - .map(InsertError::Exists) - .ok_or(()) - .swap() + self.insert(key, val) + .map(InsertError::Exists) + .ok_or(()) + .swap() } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { self.remove(key) } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get(key) } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get_mut(key) } fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - btreemap_iter: Some(self.iter()), - } + Iter { array_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None, + btreemap_iter: Some(self.iter()) } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - btreemap_iter: Some(self.iter_mut()), - } + IterMut { array_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None, + btreemap_iter: Some(self.iter_mut()) } } } #[cfg(feature = "std")] impl Map for HashMap { fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: None, - btreemap_iter: None, - hashmap_iter: Some(self.iter()), - } + Iter { array_iter: None, + btreemap_iter: None, + hashmap_iter: Some(self.iter()) } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: None, - btreemap_iter: None, - hashmap_iter: Some(self.iter_mut()), - } + IterMut { array_iter: None, + btreemap_iter: None, + hashmap_iter: Some(self.iter_mut()) } } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get(key) } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get_mut(key) } fn insert(&mut self, key: K, val: V) -> Result<(), InsertError> { - self - .insert(key, val) - .map(InsertError::Exists) - .ok_or(()) - .swap() + self.insert(key, val) + .map(InsertError::Exists) + .ok_or(()) + .swap() } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { self.remove(key) } @@ -186,13 +166,11 @@ impl, K: Eq + Hash + Ord, V> Map for T { } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { - match self - .iter() - .enumerate() - .find(|(_, (k, _))| Borrow::::borrow(*k) == key) + match self.iter() + .enumerate() + .find(|(_, (k, _))| Borrow::::borrow(*k) == key) { | Some((ix, _)) => self.remove(ix).map(|(_, v)| v), | None => None, @@ -200,8 +178,7 @@ impl, K: Eq + Hash + Ord, V> Map for T { } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { match self.iter().find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), @@ -210,12 +187,10 @@ impl, K: Eq + Hash + Ord, V> Map for T { } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { - match self - .iter_mut() - .find(|(k, _)| Borrow::::borrow(*k) == key) + match self.iter_mut() + .find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), | None => None, @@ -223,23 +198,19 @@ impl, K: Eq + Hash + Ord, V> Map for T { } fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + Iter { array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + IterMut { array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } } @@ -325,20 +296,16 @@ impl<'a, K: Eq + Hash, V> Iter<'a, K, V> { fn get_iter(&mut self) -> &mut dyn Iterator { #[cfg(feature = "std")] { - let (a, b, c) = ( - self.hashmap_iter.as_mut().map(|a| a as &mut _), - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b, c) = (self.hashmap_iter.as_mut().map(|a| a as &mut _), + self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).or(c).unwrap(); }; #[cfg(feature = "alloc")] { - let (a, b) = ( - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b) = (self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).unwrap(); } @@ -394,20 +361,16 @@ impl<'a, K: Eq + Hash, V> IterMut<'a, K, V> { fn get_iter(&mut self) -> &mut dyn Iterator { #[cfg(feature = "std")] { - let (a, b, c) = ( - self.hashmap_iter.as_mut().map(|a| a as &mut _), - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b, c) = (self.hashmap_iter.as_mut().map(|a| a as &mut _), + self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).or(c).unwrap(); }; #[cfg(feature = "alloc")] { - let (a, b) = ( - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b) = (self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).unwrap(); } @@ -428,18 +391,17 @@ impl<'a, K: Eq + Hash, V> Iterator for IterMut<'a, K, V> { mod tests { use super::*; - fn impls() -> ( - impl Map, - impl Map, - impl Map, - impl Map, - ) { - ( - HashMap::::from([("foo".into(), "bar".into())]), - BTreeMap::::from([("foo".into(), "bar".into())]), - tinyvec::array_vec!([(String, String); 16] => ("foo".into(), "bar".into())), - vec![("foo".to_string(), "bar".to_string())], + fn impls( ) + -> (impl Map, + impl Map, + impl Map, + impl Map) + { + (HashMap::::from([("foo".into(), "bar".into())]), + BTreeMap::::from([("foo".into(), "bar".into())]), + tinyvec::array_vec!([(String, String); 16] => ("foo".into(), "bar".into())), + vec![("foo".to_string(), "bar".to_string())]) } macro_rules! each_impl { @@ -528,15 +490,11 @@ mod tests { let mut kvs = map.into_iter().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - ("a".into(), "a".into()), - ("b".into(), "b".into()), - ("c".into(), "c".into()), - ("foo".into(), "bar".into()), - ] - ); + assert_eq!(kvs, + vec![("a".into(), "a".into()), + ("b".into(), "b".into()), + ("c".into(), "c".into()), + ("foo".into(), "bar".into()),]); } each_impl!(test_into_iter); @@ -552,15 +510,11 @@ mod tests { let mut kvs = map.iter().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - (&"a".into(), &"a".into()), - (&"b".into(), &"b".into()), - (&"c".into(), &"c".into()), - (&"foo".into(), &"bar".into()), - ] - ); + assert_eq!(kvs, + vec![(&"a".into(), &"a".into()), + (&"b".into(), &"b".into()), + (&"c".into(), &"c".into()), + (&"foo".into(), &"bar".into()),]); } each_impl!(test_iter); @@ -576,15 +530,11 @@ mod tests { let mut kvs = map.iter_mut().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - (&"a".into(), &mut "a".into()), - (&"b".into(), &mut "b".into()), - (&"c".into(), &mut "c".into()), - (&"foo".into(), &mut "bar".into()), - ] - ); + assert_eq!(kvs, + vec![(&"a".into(), &mut "a".into()), + (&"b".into(), &mut "b".into()), + (&"c".into(), &mut "c".into()), + (&"foo".into(), &mut "bar".into()),]); } each_impl!(test_iter_mut); diff --git a/toad-common/src/result.rs b/toad-common/src/result.rs index 21bdae58..e2def8c1 100644 --- a/toad-common/src/result.rs +++ b/toad-common/src/result.rs @@ -53,23 +53,23 @@ impl ResultExt for Result { fn perform(self, f: impl FnOnce(&T) -> ()) -> Result { self.map(|t| { - f(&t); - t - }) + f(&t); + t + }) } fn perform_err(self, f: impl FnOnce(&E) -> ()) -> Result { self.map_err(|t| { - f(&t); - t - }) + f(&t); + t + }) } fn perform_mut(self, f: impl FnOnce(&mut T) -> ()) -> Result { self.map(|mut t| { - f(&mut t); - t - }) + f(&mut t); + t + }) } fn filter(self, pred: impl FnOnce(&T) -> bool, on_fail: impl FnOnce(&T) -> E) -> Result { diff --git a/toad-common/src/stem.rs b/toad-common/src/stem.rs index 17cb6cb6..e9a7f693 100644 --- a/toad-common/src/stem.rs +++ b/toad-common/src/stem.rs @@ -27,8 +27,7 @@ impl Stem { /// There can be any number of concurrent `map_ref` /// sections running at a given time. pub fn map_ref(&self, f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { self.0.map_ref(f) } @@ -37,8 +36,7 @@ impl Stem { /// /// This will block if called concurrently with `map_ref` or `map_mut`. pub fn map_mut(&self, f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { self.0.map_mut(f) } @@ -55,24 +53,21 @@ impl Stem { pub trait StemCellBehavior { /// Create an instance of `Self` fn new(t: T) -> Self - where - Self: Sized; + where Self: Sized; /// Map a reference to `T` to a new type /// /// Implementors may choose to panic or block /// if `map_mut` called concurrently. fn map_ref(&self, f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R; + where F: for<'a> FnMut(&'a T) -> R; /// Map a mutable reference to `T` to a new type /// /// Implementors may choose to panic or block /// if `map_ref` or `map_mut` called concurrently. fn map_mut(&self, f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R; + where F: for<'a> FnMut(&'a mut T) -> R; } #[cfg(feature = "std")] @@ -82,15 +77,13 @@ impl StemCellBehavior for std::sync::RwLock { } fn map_ref(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { f(self.read().unwrap().deref()) } fn map_mut(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { f(self.write().unwrap().deref_mut()) } @@ -102,15 +95,13 @@ impl StemCellBehavior for core::cell::RefCell { } fn map_ref(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { f(self.borrow().deref()) } fn map_mut(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { f(self.borrow_mut().deref_mut()) } @@ -173,10 +164,10 @@ mod test { std::thread::spawn(|| { wait!(START); VEC.map_ref(|v| { - assert!(v.is_empty()); - wait!(READING); - wait!(READING_DONE); - }); + assert!(v.is_empty()); + wait!(READING); + wait!(READING_DONE); + }); wait!(MODIFY_DONE); }); diff --git a/toad-common/src/writable.rs b/toad-common/src/writable.rs index 922e2645..ca474180 100644 --- a/toad-common/src/writable.rs +++ b/toad-common/src/writable.rs @@ -43,9 +43,7 @@ impl> Writable { } } -impl Display for Writable -where - A: Array, +impl Display for Writable where A: Array { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.as_str()) diff --git a/toad-cursor/Cargo.toml b/toad-cursor/Cargo.toml index d0a3eb4a..1854eceb 100644 --- a/toad-cursor/Cargo.toml +++ b/toad-cursor/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-cursor" version = "0.2.0" edition = "2021" +rust-version = "1.70" description = "no_std Cursor struct" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" diff --git a/toad-cursor/src/lib.rs b/toad-cursor/src/lib.rs index a0068413..a1461145 100644 --- a/toad-cursor/src/lib.rs +++ b/toad-cursor/src/lib.rs @@ -97,9 +97,9 @@ impl> Cursor { #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option { self.take_exact(1).and_then(|a| match a { - | &[a] => Some(a), - | _ => None, - }) + | &[a] => Some(a), + | _ => None, + }) } /// Take `n` bytes from the cursor, stopping early if @@ -107,12 +107,15 @@ impl> Cursor { /// /// Runs in O(1) time. pub fn take(&mut self, n: usize) -> &[u8] { - Self::peek_(self.len, self.cursor, &self.t, n) - .map(|a| { - Self::skip_(&mut self.cursor, self.len, n); - a - }) - .unwrap_or_else(|| Self::take_until_end_(&mut self.cursor, self.len, &self.t)) + Self::peek_(self.len, self.cursor, &self.t, n).map(|a| { + Self::skip_(&mut self.cursor, self.len, n); + a + }) + .unwrap_or_else(|| { + Self::take_until_end_(&mut self.cursor, + self.len, + &self.t) + }) } /// Take `n` bytes from the cursor, returning None if @@ -121,9 +124,9 @@ impl> Cursor { /// Runs in O(1) time. pub fn take_exact(&mut self, n: usize) -> Option<&[u8]> { Self::peek_(self.len, self.cursor, &self.t, n).map(|a| { - Self::skip_(&mut self.cursor, self.len, n); - a - }) + Self::skip_(&mut self.cursor, self.len, n); + a + }) } /// Without advancing the position, look at the next @@ -164,16 +167,15 @@ impl> Cursor { return &[]; } - (self.cursor..self.len) - .into_iter() - .take_while(|ix| f(self.t.as_ref()[*ix])) - .last() - .map(|end_ix| { - let out = &self.t.as_ref()[self.cursor..=end_ix]; - self.cursor = end_ix + 1; - out - }) - .unwrap_or(&[]) + (self.cursor..self.len).into_iter() + .take_while(|ix| f(self.t.as_ref()[*ix])) + .last() + .map(|end_ix| { + let out = &self.t.as_ref()[self.cursor..=end_ix]; + self.cursor = end_ix + 1; + out + }) + .unwrap_or(&[]) } /// Whether the cursor has reached the end @@ -291,9 +293,8 @@ mod tests { #[test] pub fn take_while() { let til_slash = |c: &mut Cursor<&str>| { - core::str::from_utf8(c.take_while(|b| (b as char) != '/')) - .unwrap() - .to_string() + core::str::from_utf8(c.take_while(|b| (b as char) != '/')).unwrap() + .to_string() }; let mut cur = Cursor::new("abc/def"); diff --git a/toad-hash/Cargo.toml b/toad-hash/Cargo.toml index fa43026c..1a4589a2 100644 --- a/toad-hash/Cargo.toml +++ b/toad-hash/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-hash" version = "0.3.0" edition = "2021" +rust-version = "1.70" description = "no_std hashing used by toad" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" diff --git a/toad-hash/src/lib.rs b/toad-hash/src/lib.rs index 39d00f3d..3127474d 100644 --- a/toad-hash/src/lib.rs +++ b/toad-hash/src/lib.rs @@ -71,8 +71,8 @@ impl Blake2Hasher { impl Debug for Blake2Hasher { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Blake2Hasher") - .field(&">") - .finish() + .field(&">") + .finish() } } diff --git a/toad-jni/Cargo.toml b/toad-jni/Cargo.toml index 74b2a84e..a92ce441 100644 --- a/toad-jni/Cargo.toml +++ b/toad-jni/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-jni" version = "0.16.1" edition = "2021" +rust-version = "1.70" description = "JNI abstractions and bindings used by the toad ecosystem" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -22,7 +23,7 @@ docs = [] [dependencies] nb = "1" no-std-net = "0.6" -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} toad-msg = "0.18.1" toad = "0.19.1" jni = {version = "0.21.1", features = ["invocation"]} diff --git a/toad-jni/src/java/field.rs b/toad-jni/src/java/field.rs index 766dace3..c80ad1d6 100644 --- a/toad-jni/src/java/field.rs +++ b/toad-jni/src/java/field.rs @@ -15,17 +15,14 @@ pub struct Field { } impl Field -where - C: java::Class, - T: java::Object, + where C: java::Class, + T: java::Object { /// Creates a new field lens pub const fn new(name: &'static str) -> Self { - Self { - name, - id: RwLock::new(None), - _t: PhantomData, - } + Self { name, + id: RwLock::new(None), + _t: PhantomData } } /// Get the value of this field @@ -41,13 +38,11 @@ where self.get(e, inst) } else { let inst = inst.downcast_ref(e); - let val = e - .get_field_unchecked( - &inst, - id.unwrap(), - jni::signature::ReturnType::from_str(T::SIG.as_str()).unwrap(), - ) - .unwrap_java(e); + let val = + e.get_field_unchecked(&inst, + id.unwrap(), + jni::signature::ReturnType::from_str(T::SIG.as_str()).unwrap()) + .unwrap_java(e); T::upcast_value(e, val) } } @@ -57,7 +52,7 @@ where let inst = inst.downcast_ref(e); let t = t.downcast_value(e); e.set_field(inst, self.name, T::SIG, (&t).into()) - .unwrap_java(e); + .unwrap_java(e); } } @@ -69,17 +64,14 @@ pub struct StaticField { } impl StaticField -where - C: java::Class, - T: java::Object, + where C: java::Class, + T: java::Object { /// Creates a new static field lens pub const fn new(name: &'static str) -> Self { - Self { - name, - id: RwLock::new(None), - _t: PhantomData, - } + Self { name, + id: RwLock::new(None), + _t: PhantomData } } /// Get the static field value @@ -89,17 +81,14 @@ where drop(id); let mut id = self.id.write().unwrap(); - *id = Some( - e.get_static_field_id(C::PATH, self.name, T::SIG) - .unwrap_java(e), - ); + *id = Some(e.get_static_field_id(C::PATH, self.name, T::SIG) + .unwrap_java(e)); drop(id); self.get(e) } else { - let val = e - .get_static_field_unchecked(C::PATH, id.unwrap(), T::jni()) - .unwrap(); + let val = e.get_static_field_unchecked(C::PATH, id.unwrap(), T::jni()) + .unwrap(); T::upcast_value(e, val) } } diff --git a/toad-jni/src/java/function.rs b/toad-jni/src/java/function.rs index 6822de34..5e264392 100644 --- a/toad-jni/src/java/function.rs +++ b/toad-jni/src/java/function.rs @@ -18,20 +18,17 @@ pub struct Method { } impl Method -where - F: Type, - C: Class, + where F: Type, + C: Class { /// Create a new method lens that invokes the method named `name` on class `C`. /// /// If you want to invoke a potentially overridden method definition on the /// object instances, use [`Method::new_overrideable`] pub const fn new(name: &'static str) -> Self { - Self { - name, - mid: RwLock::new(None), - _t: PhantomData, - } + Self { name, + mid: RwLock::new(None), + _t: PhantomData } } /// Get & cache the method ID for this method @@ -51,9 +48,8 @@ where } impl Method FR> -where - C: Class, - FR: Object, + where C: Class, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C) -> FR { @@ -61,7 +57,7 @@ where let mid = self.find(e); let jv = unsafe { e.call_method_unchecked(&inst, mid, Signature::of:: FR>().return_type(), &[]) - .unwrap_java(e) + .unwrap_java(e) }; FR::upcast_value(e, jv) @@ -69,10 +65,9 @@ where } impl Method FR> -where - C: Class, - FA: Object, - FR: Object, + where C: Class, + FA: Object, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA) -> FR { @@ -80,24 +75,21 @@ where let fa = fa.downcast_value(e); let mid = self.find(e); let jv = unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni()], - ) - .unwrap_java(e) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl Method FR> -where - C: Class, - FA: Object, - FB: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA, fb: FB) -> FR { @@ -105,124 +97,100 @@ where let (fa, fb) = (fa.downcast_value(e), fb.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni()], - ) - .unwrap_java(e) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl Method FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA, fb: FB, fc: FC) -> FR { let inst = inst.downcast_ref(e); - let (fa, fb, fc) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - ); + let (fa, fb, fc) = (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni()], - ) - .unwrap_java(e) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl Method FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA, fb: FB, fc: FC, fd: FD) -> FR { let inst = inst.downcast_ref(e); - let (fa, fb, fc, fd) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - ); + let (fa, fb, fc, fd) = + (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e), fd.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()], - ) - .unwrap_java(e) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl Method FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FE: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FE: Object, + FR: Object { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA, fb: FB, fc: FC, fd: FD, fe: FE) -> FR { let inst = inst.downcast_ref(e); - let (fa, fb, fc, fd, fe) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - fe.downcast_value(e), - ); + let (fa, fb, fc, fd, fe) = (fa.downcast_value(e), + fb.downcast_value(e), + fc.downcast_value(e), + fd.downcast_value(e), + fe.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[ - fa.as_jni(), - fb.as_jni(), - fc.as_jni(), - fd.as_jni(), - fe.as_jni(), - ], - ) - .unwrap_java(e) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), + fb.as_jni(), + fc.as_jni(), + fd.as_jni(), + fe.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl Method Result> -where - C: Class, - FR: Class, + where C: Class, + FR: Class { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C) -> Result { @@ -230,17 +198,16 @@ where let mid = self.find(e); unsafe { e.call_method_unchecked(&inst, mid, Signature::of:: FR>().return_type(), &[]) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } impl Method Result> -where - C: Class, - FA: Object, - FR: Class, + where C: Class, + FA: Object, + FR: Class { /// Call the method pub fn invoke(&self, e: &mut java::Env, inst: &C, fa: FA) -> Result { @@ -248,172 +215,142 @@ where let fa = fa.downcast_value(e); let mid = self.find(e); unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni()], - ) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni()]) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } impl Method Result> -where - C: Class, - FA: Object, - FB: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FR: Class { /// Call the method - pub fn invoke( - &self, - e: &mut java::Env, - inst: &C, - fa: FA, - fb: FB, - ) -> Result { + pub fn invoke(&self, + e: &mut java::Env, + inst: &C, + fa: FA, + fb: FB) + -> Result { let inst = inst.downcast_ref(e); let (fa, fb) = (fa.downcast_value(e), fb.downcast_value(e)); let mid = self.find(e); unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni()], - ) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni()]) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } impl Method Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FR: Class { /// Call the method - pub fn invoke( - &self, - e: &mut java::Env, - inst: &C, - fa: FA, - fb: FB, - fc: FC, - ) -> Result { + pub fn invoke(&self, + e: &mut java::Env, + inst: &C, + fa: FA, + fb: FB, + fc: FC) + -> Result { let inst = inst.downcast_ref(e); - let (fa, fb, fc) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - ); + let (fa, fb, fc) = (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e)); let mid = self.find(e); unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni()], - ) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni()]) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } impl Method Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FR: Class { /// Call the method - pub fn invoke( - &self, - e: &mut java::Env, - inst: &C, - fa: FA, - fb: FB, - fc: FC, - fd: FD, - ) -> Result { + pub fn invoke(&self, + e: &mut java::Env, + inst: &C, + fa: FA, + fb: FB, + fc: FC, + fd: FD) + -> Result { let inst = inst.downcast_ref(e); - let (fa, fb, fc, fd) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - ); + let (fa, fb, fc, fd) = + (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e), fd.downcast_value(e)); let mid = self.find(e); unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()], - ) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()]) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } impl Method Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FE: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FE: Object, + FR: Class { /// Call the method - pub fn invoke( - &self, - e: &mut java::Env, - inst: &C, - fa: FA, - fb: FB, - fc: FC, - fd: FD, - fe: FE, - ) -> Result { + pub fn invoke(&self, + e: &mut java::Env, + inst: &C, + fa: FA, + fb: FB, + fc: FC, + fd: FD, + fe: FE) + -> Result { let inst = inst.downcast_ref(e); - let (fa, fb, fc, fd, fe) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - fe.downcast_value(e), - ); + let (fa, fb, fc, fd, fe) = (fa.downcast_value(e), + fb.downcast_value(e), + fc.downcast_value(e), + fd.downcast_value(e), + fe.downcast_value(e)); let mid = self.find(e); unsafe { - e.call_method_unchecked( - &inst, - mid, - Signature::of:: FR>().return_type(), - &[ - fa.as_jni(), - fb.as_jni(), - fc.as_jni(), - fd.as_jni(), - fe.as_jni(), - ], - ) - .to_throwable(e) - .map(|jv| FR::upcast_value(e, jv)) + e.call_method_unchecked(&inst, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), + fb.as_jni(), + fc.as_jni(), + fd.as_jni(), + fe.as_jni()]) + .to_throwable(e) + .map(|jv| FR::upcast_value(e, jv)) } } } @@ -428,17 +365,14 @@ pub struct StaticMethod { } impl StaticMethod -where - F: Type, - C: Class, + where F: Type, + C: Class { /// Create the static method lens pub const fn new(name: &'static str) -> Self { - Self { - name, - ids: RwLock::new(None), - _t: PhantomData, - } + Self { name, + ids: RwLock::new(None), + _t: PhantomData } } /// Get & cache the method ID for this method @@ -449,9 +383,8 @@ where drop(ids); let class = e.find_class(C::PATH).unwrap_java(e); let class = e.new_global_ref(class).unwrap_java(e); - let mid = e - .get_static_method_id(C::PATH, self.name, F::SIG) - .unwrap_java(e); + let mid = e.get_static_method_id(C::PATH, self.name, F::SIG) + .unwrap_java(e); let mut field = self.ids.write().unwrap(); *field = Some((class, mid)); drop(field); @@ -469,171 +402,142 @@ where } impl StaticMethod FR> -where - C: Class, - FR: Object, + where C: Class, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env) -> FR { let (class, mid) = self.find(e); let jv = unsafe { e.call_static_method_unchecked(class, mid, Signature::of:: FR>().return_type(), &[]) - .unwrap_java(e) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod FR> -where - C: Class, - FA: Object, - FR: Object, + where C: Class, + FA: Object, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA) -> FR { let fa = fa.downcast_value(e); let (class, mid) = self.find(e); let jv = unsafe { - e.call_static_method_unchecked( - class, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni()], - ) - .unwrap_java(e) + e.call_static_method_unchecked(class, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod FR> -where - C: Class, - FA: Object, - FB: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB) -> FR { let (fa, fb) = (fa.downcast_value(e), fb.downcast_value(e)); let (class, mid) = self.find(e); let jv = unsafe { - e.call_static_method_unchecked( - class, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni()], - ) - .unwrap_java(e) + e.call_static_method_unchecked(class, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC) -> FR { - let (fa, fb, fc) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - ); + let (fa, fb, fc) = (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e)); let (class, mid) = self.find(e); let jv = unsafe { - e.call_static_method_unchecked( - class, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni()], - ) - .unwrap_java(e) + e.call_static_method_unchecked(class, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC, fd: FD) -> FR { - let (fa, fb, fc, fd) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - ); + let (fa, fb, fc, fd) = + (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e), fd.downcast_value(e)); let (class, mid) = self.find(e); let jv = unsafe { - e.call_static_method_unchecked( - class, - mid, - Signature::of:: FR>().return_type(), - &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()], - ) - .unwrap_java(e) + e.call_static_method_unchecked(class, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod FR> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FE: Object, - FR: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FE: Object, + FR: Object { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC, fd: FD, fe: FE) -> FR { - let (fa, fb, fc, fd, fe) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - fe.downcast_value(e), - ); + let (fa, fb, fc, fd, fe) = (fa.downcast_value(e), + fb.downcast_value(e), + fc.downcast_value(e), + fd.downcast_value(e), + fe.downcast_value(e)); let (class, mid) = self.find(e); let jv = unsafe { - e.call_static_method_unchecked( - class, - mid, - Signature::of:: FR>().return_type(), - &[ - fa.as_jni(), - fb.as_jni(), - fc.as_jni(), - fd.as_jni(), - fe.as_jni(), - ], - ) - .unwrap_java(e) + e.call_static_method_unchecked(class, + mid, + Signature::of:: FR>().return_type(), + &[fa.as_jni(), + fb.as_jni(), + fc.as_jni(), + fd.as_jni(), + fe.as_jni()]) + .unwrap_java(e) }; FR::upcast_value(e, jv) } } impl StaticMethod Result> -where - C: Class, - FR: Class, + where C: Class, + FR: Class { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env) -> Result { @@ -652,10 +556,9 @@ where } impl StaticMethod Result> -where - C: Class, - FA: Object, - FR: Class, + where C: Class, + FA: Object, + FR: Class { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA) -> Result { @@ -675,11 +578,10 @@ where } impl StaticMethod Result> -where - C: Class, - FA: Object, - FB: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FR: Class { /// Invoke the static method pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB) -> Result { @@ -699,26 +601,20 @@ where } impl StaticMethod Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FR: Class { /// Invoke the static method - pub fn invoke( - &self, - e: &mut java::Env, - fa: FA, - fb: FB, - fc: FC, - ) -> Result { - let (fa, fb, fc) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - ); + pub fn invoke(&self, + e: &mut java::Env, + fa: FA, + fb: FB, + fc: FC) + -> Result { + let (fa, fb, fc) = (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e)); let (class, mid) = self.find(e); unsafe { e.call_static_method_unchecked( @@ -734,29 +630,23 @@ where } impl StaticMethod Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FR: Class { /// Invoke the static method - pub fn invoke( - &self, - e: &mut java::Env, - fa: FA, - fb: FB, - fc: FC, - fd: FD, - ) -> Result { - let (fa, fb, fc, fd) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - ); + pub fn invoke(&self, + e: &mut java::Env, + fa: FA, + fb: FB, + fc: FC, + fd: FD) + -> Result { + let (fa, fb, fc, fd) = + (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e), fd.downcast_value(e)); let (class, mid) = self.find(e); unsafe { e.call_static_method_unchecked( @@ -773,32 +663,28 @@ where impl StaticMethod Result> -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FE: Object, - FR: Class, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FE: Object, + FR: Class { /// Invoke the static method - pub fn invoke( - &self, - e: &mut java::Env, - fa: FA, - fb: FB, - fc: FC, - fd: FD, - fe: FE, - ) -> Result { - let (fa, fb, fc, fd, fe) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - fe.downcast_value(e), - ); + pub fn invoke(&self, + e: &mut java::Env, + fa: FA, + fb: FB, + fc: FC, + fd: FD, + fe: FE) + -> Result { + let (fa, fb, fc, fd, fe) = (fa.downcast_value(e), + fb.downcast_value(e), + fc.downcast_value(e), + fd.downcast_value(e), + fe.downcast_value(e)); let (class, mid) = self.find(e); unsafe { e.call_static_method_unchecked( @@ -830,16 +716,13 @@ pub struct Constructor { } impl Constructor -where - F: Type, - C: Class, + where F: Type, + C: Class { /// Creates the lens pub const fn new() -> Self { - Self { - id: RwLock::new(None), - _t: PhantomData, - } + Self { id: RwLock::new(None), + _t: PhantomData } } /// Get & cache the method ID for this constructor @@ -858,23 +741,19 @@ where } } -impl Constructor -where - C: Class, +impl Constructor where C: Class { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env) -> C { - let jobj = e - .new_object(C::PATH, Signature::of::(), &[]) - .unwrap_java(e); + let jobj = e.new_object(C::PATH, Signature::of::(), &[]) + .unwrap_java(e); java::lang::Object::from_local(e, jobj).upcast_to::(e) } } impl Constructor -where - C: Class, - FA: Object, + where C: Class, + FA: Object { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env, fa: FA) -> C { @@ -882,7 +761,7 @@ where let mid = self.find(e); let jv = unsafe { e.new_object_unchecked(C::PATH, mid, &[fa.as_jni()]) - .unwrap_java(e) + .unwrap_java(e) }; java::lang::Object::from_local(e, jv).upcast_to::(e) @@ -890,10 +769,9 @@ where } impl Constructor -where - C: Class, - FA: Object, - FB: Object, + where C: Class, + FA: Object, + FB: Object { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB) -> C { @@ -901,96 +779,77 @@ where let mid = self.find(e); let jv = unsafe { e.new_object_unchecked(C::PATH, mid, &[fa.as_jni(), fb.as_jni()]) - .unwrap_java(e) + .unwrap_java(e) }; java::lang::Object::from_local(e, jv).upcast_to::(e) } } impl Constructor -where - C: Class, - FA: Object, - FB: Object, - FC: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC) -> C { - let (fa, fb, fc) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - ); + let (fa, fb, fc) = (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e)); let mid = self.find(e); let jv = unsafe { e.new_object_unchecked(C::PATH, mid, &[fa.as_jni(), fb.as_jni(), fc.as_jni()]) - .unwrap_java(e) + .unwrap_java(e) }; java::lang::Object::from_local(e, jv).upcast_to::(e) } } impl Constructor -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC, fd: FD) -> C { - let (fa, fb, fc, fd) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - ); + let (fa, fb, fc, fd) = + (fa.downcast_value(e), fb.downcast_value(e), fc.downcast_value(e), fd.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.new_object_unchecked( - C::PATH, - mid, - &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()], - ) - .unwrap_java(e) + e.new_object_unchecked(C::PATH, + mid, + &[fa.as_jni(), fb.as_jni(), fc.as_jni(), fd.as_jni()]) + .unwrap_java(e) }; java::lang::Object::from_local(e, jv).upcast_to::(e) } } impl Constructor -where - C: Class, - FA: Object, - FB: Object, - FC: Object, - FD: Object, - FE: Object, + where C: Class, + FA: Object, + FB: Object, + FC: Object, + FD: Object, + FE: Object { /// Invoke the constructor pub fn invoke(&self, e: &mut java::Env, fa: FA, fb: FB, fc: FC, fd: FD, fe: FE) -> C { - let (fa, fb, fc, fd, fe) = ( - fa.downcast_value(e), - fb.downcast_value(e), - fc.downcast_value(e), - fd.downcast_value(e), - fe.downcast_value(e), - ); + let (fa, fb, fc, fd, fe) = (fa.downcast_value(e), + fb.downcast_value(e), + fc.downcast_value(e), + fd.downcast_value(e), + fe.downcast_value(e)); let mid = self.find(e); let jv = unsafe { - e.new_object_unchecked( - C::PATH, - mid, - &[ - fa.as_jni(), - fb.as_jni(), - fc.as_jni(), - fd.as_jni(), - fe.as_jni(), - ], - ) - .unwrap_java(e) + e.new_object_unchecked(C::PATH, + mid, + &[fa.as_jni(), + fb.as_jni(), + fc.as_jni(), + fd.as_jni(), + fe.as_jni()]) + .unwrap_java(e) }; java::lang::Object::from_local(e, jv).upcast_to::(e) } diff --git a/toad-jni/src/java/io/console.rs b/toad-jni/src/java/io/console.rs index 526f5af3..eef2a9cf 100644 --- a/toad-jni/src/java/io/console.rs +++ b/toad-jni/src/java/io/console.rs @@ -5,12 +5,11 @@ pub struct Console(java::lang::Object); impl Console { /// `java.io.Console.printf(String, java.lang.Object...)` - pub fn printf( - &self, - e: &mut java::Env, - fmt: impl ToString, - args: Vec, - ) -> &Self { + pub fn printf(&self, + e: &mut java::Env, + fmt: impl ToString, + args: Vec) + -> &Self { static PRINTF: java::Method) -> NoUpcast> = java::Method::new("printf"); PRINTF.invoke(e, &self, fmt.to_string(), args); @@ -18,12 +17,11 @@ impl Console { } /// `java.io.Console.readLine(String, java.lang.Object...)` - pub fn readline( - &self, - e: &mut java::Env, - fmt: impl ToString, - args: Vec, - ) -> String { + pub fn readline(&self, + e: &mut java::Env, + fmt: impl ToString, + args: Vec) + -> String { static READLINE: java::Method) -> String> = java::Method::new("readLine"); READLINE.invoke(e, &self, fmt.to_string(), args) diff --git a/toad-jni/src/java/io/io_exception.rs b/toad-jni/src/java/io/io_exception.rs index 1a8bddc8..e013a0f4 100644 --- a/toad-jni/src/java/io/io_exception.rs +++ b/toad-jni/src/java/io/io_exception.rs @@ -35,8 +35,7 @@ impl java::Class for IOException { } impl toad::platform::PlatformError for IOException -where - StepError: core::fmt::Debug, + where StepError: core::fmt::Debug { fn msg_to_bytes(e: toad_msg::to_bytes::MessageToBytesError) -> Self { Self::new(&mut java::env(), format!("{:?}", e)) diff --git a/toad-jni/src/java/lang/object.rs b/toad-jni/src/java/lang/object.rs index eb59b3cf..5fb19e1d 100644 --- a/toad-jni/src/java/lang/object.rs +++ b/toad-jni/src/java/lang/object.rs @@ -14,16 +14,14 @@ pub struct Object(GlobalRef); impl Object { /// Is this object `instanceof C`? pub fn is_instance_of(&self, e: &mut java::Env) -> bool - where - T: java::Type, + where T: java::Type { T::is_type_of(e, self) } /// Shorthand for `T::upcast(e, jobj)` pub fn upcast_to(self, e: &mut java::Env) -> T - where - T: java::Object, + where T: java::Object { T::upcast(e, self) } @@ -63,26 +61,23 @@ impl Object { /// Convert an owned local jvalue to an object pub fn from_value<'a, 'b>(e: &mut java::Env<'a>, jv: JValueGen>) -> Self - where - 'a: 'b, + where 'a: 'b { Self::from_local(e, jv.l().unwrap()) } /// Convert a borrowed local jvalue to an object pub fn from_value_ref<'a, 'b, 'c>(e: &mut java::Env<'a>, jv: JValueGen<&'c JObject<'b>>) -> Self - where - 'a: 'b, - 'c: 'b, + where 'a: 'b, + 'c: 'b { Self::from_local(e, jv.l().unwrap()) } /// Convert a local jobject to an object pub fn from_local<'a, 'b, T>(e: &mut java::Env<'a>, t: T) -> Self - where - 'a: 'b, - T: AsRef>, + where 'a: 'b, + T: AsRef> { Self(e.new_global_ref(t.as_ref()).unwrap_java(e)) } @@ -126,22 +121,19 @@ impl java::Object for Object { } fn upcast_value_ref<'e>(e: &mut java::Env<'e>, jv: jni::objects::JValue<'e, '_>) -> Self - where - Self: Sized, + where Self: Sized { Self::from_value_ref(e, jv) } fn upcast_value<'e>(e: &mut java::Env<'e>, jv: jni::objects::JValueOwned<'e>) -> Self - where - Self: Sized, + where Self: Sized { Self::from_value(e, jv) } fn downcast_value<'e>(self, e: &mut java::Env<'e>) -> jni::objects::JValueOwned<'e> - where - Self: Sized, + where Self: Sized { self.to_value(e) } diff --git a/toad-jni/src/java/lang/system.rs b/toad-jni/src/java/lang/system.rs index bd3bb1ec..f2746f11 100644 --- a/toad-jni/src/java/lang/system.rs +++ b/toad-jni/src/java/lang/system.rs @@ -24,16 +24,14 @@ impl System { /// `String java.lang.System.setProperty(String)` /// /// Returns `Some(val)` when there was a previous value. - pub fn set_property( - e: &mut java::Env, - key: impl ToString, - value: impl ToString, - ) -> Option { + pub fn set_property(e: &mut java::Env, + key: impl ToString, + value: impl ToString) + -> Option { static SET_PROPERTY: java::StaticMethod Nullable> = java::StaticMethod::new("setProperty"); - SET_PROPERTY - .invoke(e, key.to_string(), value.to_string()) - .into_option(e) + SET_PROPERTY.invoke(e, key.to_string(), value.to_string()) + .into_option(e) } /// `java.lang.System.gc()` diff --git a/toad-jni/src/java/lang/throwable.rs b/toad-jni/src/java/lang/throwable.rs index 0b35fb98..1aadb4f2 100644 --- a/toad-jni/src/java/lang/throwable.rs +++ b/toad-jni/src/java/lang/throwable.rs @@ -25,9 +25,8 @@ impl Throwable { /// `java.lang.Throwable.getCause()` pub fn cause(&self, e: &mut java::Env) -> Option { - java::Method:: Nullable>::new("getCause") - .invoke(e, self) - .into_option(e) + java::Method:: Nullable>::new("getCause").invoke(e, self) + .into_option(e) } /// Recursively travel up the `Throwable` cause chain until one has no inner exception @@ -56,14 +55,12 @@ impl core::fmt::Debug for Throwable { let mut e = java::env(); let e = &mut e; let traces = self.stack_trace(e); - let traces = traces - .into_iter() - .map(|o| o.downcast(e).to_string(e)) - .collect::>(); + let traces = traces.into_iter() + .map(|o| o.downcast(e).to_string(e)) + .collect::>(); write!(f, "{}\n", self.downcast_ref(e).to_string(e))?; - self - .cause_iter(e) - .try_for_each(|cause| write!(f, " {}\n", cause.downcast_ref(e).to_string(e)))?; + self.cause_iter(e) + .try_for_each(|cause| write!(f, " {}\n", cause.downcast_ref(e).to_string(e)))?; write!(f, "\nstacktrace:\n{:#?}", traces)?; Ok(()) @@ -83,18 +80,17 @@ mod tests { let foo = IOException::new_caused_by(e, "foo", bar).to_throwable(e); assert_eq!( - format!("{:?}", foo), - format!( - r#" + format!("{:?}", foo), + format!( + r#" java.io.IOException: foo java.io.IOException: bar java.io.IOException: baz stacktrace: {:#?}"#, - Vec::::new() - ) - .trim_start() + Vec::::new() + ).trim_start() ); } } diff --git a/toad-jni/src/java/math/bigint.rs b/toad-jni/src/java/math/bigint.rs index 0ac8277a..603f78f9 100644 --- a/toad-jni/src/java/math/bigint.rs +++ b/toad-jni/src/java/math/bigint.rs @@ -77,20 +77,19 @@ impl BigInteger { bytes.drain(0..first_nonzero_ix).for_each(|_| ()); } - bytes - .iter() - .map(|i| { - // https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/math/BigInteger.html#toByteArray() - // - // toByteArray returns the raw byte representation - // of the integer, NOT i8s which are the normal - // interpretation for a java `byte` primitive. - i8::to_be_bytes(*i)[0] - }) - .rfold(N - 1, |ix, b| { - byte_array[ix] = b; - ix.saturating_sub(1) - }); + bytes.iter() + .map(|i| { + // https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/math/BigInteger.html#toByteArray() + // + // toByteArray returns the raw byte representation + // of the integer, NOT i8s which are the normal + // interpretation for a java `byte` primitive. + i8::to_be_bytes(*i)[0] + }) + .rfold(N - 1, |ix, b| { + byte_array[ix] = b; + ix.saturating_sub(1) + }); byte_array } @@ -103,14 +102,11 @@ impl BigInteger { /// must represent a signed two's complement integer, in big-endian order. pub fn from_be_bytes(e: &mut java::Env, bytes: &[u8]) -> Self { static CTOR_BYTE_ARRAY: java::Constructor)> = java::Constructor::new(); - CTOR_BYTE_ARRAY.invoke( - e, - bytes - .iter() - .copied() - .map(|u| i8::from_be_bytes(u.to_be_bytes())) - .collect(), - ) + CTOR_BYTE_ARRAY.invoke(e, + bytes.iter() + .copied() + .map(|u| i8::from_be_bytes(u.to_be_bytes())) + .collect()) } } diff --git a/toad-jni/src/java/net/inetaddress.rs b/toad-jni/src/java/net/inetaddress.rs index 7f978355..7fd4589f 100644 --- a/toad-jni/src/java/net/inetaddress.rs +++ b/toad-jni/src/java/net/inetaddress.rs @@ -55,26 +55,20 @@ macro_rules! from_net_impl { impl InetAddress { /// [`InetAddress getByAddress(byte[])`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/net/InetAddress.html#getByAddress(byte%5B%5D)) pub fn new_ipv4(e: &mut java::Env, addr: [u8; 4]) -> Self { - INETADDRESS_GET_BY_ADDRESS.invoke( - e, - addr - .iter() - .copied() - .map(|u| i8::from_be_bytes(u.to_be_bytes())) - .collect(), - ) + INETADDRESS_GET_BY_ADDRESS.invoke(e, + addr.iter() + .copied() + .map(|u| i8::from_be_bytes(u.to_be_bytes())) + .collect()) } /// [`InetAddress getByAddress(byte[])`](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/net/InetAddress.html#getByAddress(byte%5B%5D)) pub fn new_ipv6(e: &mut java::Env, addr: [u8; 16]) -> Self { - INETADDRESS_GET_BY_ADDRESS.invoke( - e, - addr - .iter() - .copied() - .map(|u| i8::from_be_bytes(u.to_be_bytes())) - .collect(), - ) + INETADDRESS_GET_BY_ADDRESS.invoke(e, + addr.iter() + .copied() + .map(|u| i8::from_be_bytes(u.to_be_bytes())) + .collect()) } fn get_address(&self, e: &mut java::Env) -> Vec { @@ -82,11 +76,10 @@ impl InetAddress { java::Method::new("getAddress"); let bytes = GET_ADDRESS.invoke(e, self); - bytes - .iter() - .copied() - .map(|i| u8::from_be_bytes(i.to_be_bytes())) - .collect::>() + bytes.iter() + .copied() + .map(|i| u8::from_be_bytes(i.to_be_bytes())) + .collect::>() } /// Convert `InetAddress` to `std::net::IpAddr` diff --git a/toad-jni/src/java/net/protocol_family.rs b/toad-jni/src/java/net/protocol_family.rs index 3e2da091..7b2ec1a5 100644 --- a/toad-jni/src/java/net/protocol_family.rs +++ b/toad-jni/src/java/net/protocol_family.rs @@ -27,11 +27,8 @@ impl StandardProtocolFamily { impl java::Object for StandardProtocolFamily { fn upcast(e: &mut java::Env, jobj: java::lang::Object) -> Self { - let (inet, inet6, unix) = ( - Self::INet.downcast(e), - Self::INet6.downcast(e), - Self::Unix.downcast(e), - ); + let (inet, inet6, unix) = + (Self::INet.downcast(e), Self::INet6.downcast(e), Self::Unix.downcast(e)); if jobj.equals(e, &inet) { Self::INet } else if jobj.equals(e, &inet6) { diff --git a/toad-jni/src/java/nio/byte_buffer.rs b/toad-jni/src/java/nio/byte_buffer.rs index cfe00340..629c3876 100644 --- a/toad-jni/src/java/nio/byte_buffer.rs +++ b/toad-jni/src/java/nio/byte_buffer.rs @@ -23,13 +23,10 @@ impl ByteBuffer { pub fn new(e: &mut java::Env, bytes: impl IntoIterator) -> Self { static WRAP: java::StaticMethod) -> ByteBuffer> = java::StaticMethod::new("wrap"); - WRAP.invoke( - e, - bytes - .into_iter() - .map(|u| i8::from_be_bytes(u.to_be_bytes())) - .collect(), - ) + WRAP.invoke(e, + bytes.into_iter() + .map(|u| i8::from_be_bytes(u.to_be_bytes())) + .collect()) } /// Upcast `Buffer` to `ByteBuffer` @@ -83,13 +80,11 @@ impl ByteBuffer { let arr = e.new_byte_array(len as i32).unwrap(); - e.call_method( - self.0.as_local(), - "get", - Signature::of::) -> ByteBuffer>(), - &[(&arr).into()], - ) - .unwrap_java(e); + e.call_method(self.0.as_local(), + "get", + Signature::of::) -> ByteBuffer>(), + &[(&arr).into()]) + .unwrap_java(e); e.get_byte_array_region(&arr, 0, bytes_i8_mut).unwrap(); bytes } diff --git a/toad-jni/src/java/nio/channels/datagram_channel.rs b/toad-jni/src/java/nio/channels/datagram_channel.rs index 36edc6bf..550b76de 100644 --- a/toad-jni/src/java/nio/channels/datagram_channel.rs +++ b/toad-jni/src/java/nio/channels/datagram_channel.rs @@ -26,20 +26,18 @@ impl DatagramChannel { /// `java.nio.channels.DatagramChannel.open` pub fn open(e: &mut java::Env, proto: StandardProtocolFamily) -> Result { - static OPEN: java::StaticMethod< - DatagramChannel, - fn(ProtocolFamily) -> Result, - > = java::StaticMethod::new("open"); + static OPEN: java::StaticMethod Result> = + java::StaticMethod::new("open"); let proto = proto.into_protocol_family(e); OPEN.invoke(e, proto) } /// `java.nio.channels.DatagramChannel.bind` pub fn bind(&self, e: &mut java::Env, addr: InetSocketAddress) -> Result<(), Throwable> { - static BIND: java::Method< - DatagramChannel, - fn(SocketAddress) -> Result, Throwable>, - > = java::Method::new("bind"); + static BIND: java::Method Result, Throwable>> = + java::Method::new("bind"); let addr = addr.as_socket_address(e); BIND.invoke(e, self, addr).map(|_| ()) } @@ -59,27 +57,20 @@ impl DatagramChannel { } /// `java.nio.channels.DatagramChannel.send(ByteBuffer, SocketAddress)` - pub fn send( - &self, - e: &mut java::Env, - buf: &ByteBuffer, - dst: &InetSocketAddress, - ) -> nb::Result { + pub fn send(&self, + e: &mut java::Env, + buf: &ByteBuffer, + dst: &InetSocketAddress) + -> nb::Result { let dst = dst.as_socket_address(e); - let (buf, dst) = ( - buf.downcast_ref(e).to_value(e), - dst.downcast_ref(e).to_value(e), - ); - let written = e - .call_method( - self.0.as_local(), - "send", - Signature::of:: i32>(), - &[(&buf).into(), (&dst).into()], - ) - .to_throwable(e) - .map(|i| i.i().unwrap() as u32); + let (buf, dst) = (buf.downcast_ref(e).to_value(e), dst.downcast_ref(e).to_value(e)); + let written = e.call_method(self.0.as_local(), + "send", + Signature::of:: i32>(), + &[(&buf).into(), (&dst).into()]) + .to_throwable(e) + .map(|i| i.i().unwrap() as u32); if let Ok(0) = written { Err(nb::Error::WouldBlock) @@ -89,28 +80,25 @@ impl DatagramChannel { } /// `java.nio.channels.DatagramChannel.send(ByteBuffer, SocketAddress)` - pub fn recv( - &self, - e: &mut java::Env, - buf: &mut ByteBuffer, - ) -> nb::Result<(u32, InetSocketAddress), Throwable> { + pub fn recv(&self, + e: &mut java::Env, + buf: &mut ByteBuffer) + -> nb::Result<(u32, InetSocketAddress), Throwable> { let buf_ = buf.downcast_ref(e).to_value(e); - e.call_method( - self.0.as_local(), - "receive", - Signature::of:: SocketAddress>(), - &[(&buf_).into()], - ) - .to_throwable(e) - .map_err(nb::Error::Other) - .and_then(|jv| { - let read = buf.position(e); - buf.rewind(e); - let addr = Nullable::::upcast_value(e, jv); - let addr = addr.into_option(e).ok_or(nb::Error::WouldBlock)?; - let addr = InetSocketAddress::from_socket_address(e, addr); - Ok((read, addr)) - }) + e.call_method(self.0.as_local(), + "receive", + Signature::of:: SocketAddress>(), + &[(&buf_).into()]) + .to_throwable(e) + .map_err(nb::Error::Other) + .and_then(|jv| { + let read = buf.position(e); + buf.rewind(e); + let addr = Nullable::::upcast_value(e, jv); + let addr = addr.into_option(e).ok_or(nb::Error::WouldBlock)?; + let addr = InetSocketAddress::from_socket_address(e, addr); + Ok((read, addr)) + }) } } @@ -142,10 +130,8 @@ impl java::Class for PeekableDatagramChannel { impl From for PeekableDatagramChannel { fn from(chan: DatagramChannel) -> Self { - Self { - chan, - peeked: RwLock::new(None), - } + Self { chan, + peeked: RwLock::new(None) } } } @@ -265,10 +251,8 @@ mod tests { let mut e = crate::test::init(); let e = &mut e; - let addr = Addr { - java: "127.0.0.1:5683".parse().unwrap(), - rust: "127.0.0.1:5684".parse().unwrap(), - }; + let addr = Addr { java: "127.0.0.1:5683".parse().unwrap(), + rust: "127.0.0.1:5684".parse().unwrap() }; let rust_sock = ::bind(addr.rust).unwrap(); let java_sock = PeekableDatagramChannel::bind(addr.java).unwrap(); @@ -295,10 +279,8 @@ mod tests { let mut e = crate::test::init(); let e = &mut e; - let addr = Addr { - java: "127.0.0.1:5685".parse().unwrap(), - rust: "127.0.0.1:5686".parse().unwrap(), - }; + let addr = Addr { java: "127.0.0.1:5685".parse().unwrap(), + rust: "127.0.0.1:5686".parse().unwrap() }; let rust_sock = ::bind(addr.rust).unwrap(); let java_sock = ::bind(addr.java).unwrap(); @@ -308,10 +290,7 @@ mod tests { let mut recvd = Vec::new(); recvd.resize(data.len(), 0); - assert!(matches!( - java_sock.peek(&mut recvd), - Err(nb::Error::WouldBlock) - )); + assert!(matches!(java_sock.peek(&mut recvd), Err(nb::Error::WouldBlock))); rust_sock.send_to(&data, addr.java.to_string()).unwrap(); @@ -330,10 +309,7 @@ mod tests { assert_eq!(from, addr.rust); assert_eq!(recvd, data); - assert!(matches!( - java_sock.peek(&mut recvd), - Err(nb::Error::WouldBlock) - )); + assert!(matches!(java_sock.peek(&mut recvd), Err(nb::Error::WouldBlock))); } #[test] @@ -346,10 +322,8 @@ mod tests { let mut e = crate::test::init(); let e = &mut e; - let addr = Addr { - java: "127.0.0.1:5688".parse().unwrap(), - rust: "127.0.0.1:5689".parse().unwrap(), - }; + let addr = Addr { java: "127.0.0.1:5688".parse().unwrap(), + rust: "127.0.0.1:5689".parse().unwrap() }; let rust_sock = ::bind(addr.rust).unwrap(); let java_sock = ::bind(addr.java).unwrap(); diff --git a/toad-jni/src/java/no_upcast.rs b/toad-jni/src/java/no_upcast.rs index b8ab00e5..000191c5 100644 --- a/toad-jni/src/java/no_upcast.rs +++ b/toad-jni/src/java/no_upcast.rs @@ -7,9 +7,7 @@ use crate::java; /// the [`java::lang::Object`]. pub struct NoUpcast(java::lang::Object, PhantomData); -impl NoUpcast -where - T: java::Class, +impl NoUpcast where T: java::Class { /// Unwrap, yielding the object reference pub fn object(self) -> java::lang::Object { @@ -22,16 +20,12 @@ where } } -impl java::Class for NoUpcast -where - T: java::Class, +impl java::Class for NoUpcast where T: java::Class { const PATH: &'static str = T::PATH; } -impl java::Object for NoUpcast -where - T: java::Class, +impl java::Object for NoUpcast where T: java::Class { fn upcast(_: &mut java::Env, jobj: java::lang::Object) -> Self { Self(jobj, PhantomData) diff --git a/toad-jni/src/java/nullable.rs b/toad-jni/src/java/nullable.rs index d3c36016..d3ea8c18 100644 --- a/toad-jni/src/java/nullable.rs +++ b/toad-jni/src/java/nullable.rs @@ -7,9 +7,7 @@ use crate::java; /// potential NullPointerExceptions. pub struct Nullable(java::lang::Object, PhantomData); -impl Nullable -where - T: java::Class, +impl Nullable where T: java::Class { /// Convert this to [`Option`]``, invoking [`java::Object::upcast`] /// _only_ if the object reference is non-null. @@ -22,16 +20,12 @@ where } } -impl java::Class for Nullable -where - T: java::Class, +impl java::Class for Nullable where T: java::Class { const PATH: &'static str = T::PATH; } -impl java::Object for Nullable -where - T: java::Class, +impl java::Object for Nullable where T: java::Class { fn upcast(_: &mut java::Env, jobj: java::lang::Object) -> Self { Self(jobj, PhantomData) diff --git a/toad-jni/src/java/object.rs b/toad-jni/src/java/object.rs index 6caef184..ba0a5f79 100644 --- a/toad-jni/src/java/object.rs +++ b/toad-jni/src/java/object.rs @@ -1,8 +1,17 @@ use java::{ResultExt, Type}; -use jni::objects::{ - GlobalRef, JBooleanArray, JByteArray, JCharArray, JDoubleArray, JFloatArray, JIntArray, - JLongArray, JObject, JObjectArray, JShortArray, JValue, JValueOwned, -}; +use jni::objects::{GlobalRef, + JBooleanArray, + JByteArray, + JCharArray, + JDoubleArray, + JFloatArray, + JIntArray, + JLongArray, + JObject, + JObjectArray, + JShortArray, + JValue, + JValueOwned}; use jni::sys::jobject; use crate::java; @@ -13,8 +22,7 @@ use crate::java; /// /// For more information, see [`java::Type`] pub trait Object -where - Self: java::Type, + where Self: java::Type { /// Try to interpret an object as `Self` fn upcast(e: &mut java::Env, jobj: java::lang::Object) -> Self; @@ -27,24 +35,21 @@ where /// Try to interpret a `JValue` as `Self` fn upcast_value_ref<'e>(e: &mut java::Env<'e>, jv: JValue<'e, '_>) -> Self - where - Self: Sized, + where Self: Sized { java::lang::Object::upcast_value_ref(e, jv).upcast_to::(e) } /// Try to interpret a `JValueOwned` as `Self` fn upcast_value<'e>(e: &mut java::Env<'e>, jv: JValueOwned<'e>) -> Self - where - Self: Sized, + where Self: Sized { Self::upcast_value_ref(e, (&jv).into()) } /// Create a `JValueOwned` from `self` fn downcast_value<'e>(self, e: &mut java::Env<'e>) -> JValueOwned<'e> - where - Self: Sized, + where Self: Sized { self.downcast(e).downcast_value(e) } @@ -71,9 +76,7 @@ impl Object for GlobalRef { } } -impl Object for Vec -where - T: java::Object, +impl Object for Vec where T: java::Object { fn upcast(e: &mut java::Env, jobj: java::lang::Object) -> Self { let arr = <&JObjectArray>::from(jobj.as_local()); @@ -85,13 +88,12 @@ where let mut els = Vec::new(); els.resize(len, Default::default()); e.$get_region(&arr, 0, &mut els).unwrap_java(e); - els - .into_iter() - .map(|b| { - let val = b.downcast_value(e); - T::upcast_value(e, val) - }) - .collect() + els.into_iter() + .map(|b| { + let val = b.downcast_value(e); + T::upcast_value(e, val) + }) + .collect() }}; } @@ -108,30 +110,27 @@ where let mut els = Vec::new(); els.resize(len, 0u8); e.get_boolean_array_region(arr, 0, &mut els).unwrap_java(e); - els - .into_iter() - .map(|b| { - let val = (b == jni::sys::JNI_TRUE).downcast_value(e); - T::upcast_value(e, val) - }) - .collect() + els.into_iter() + .map(|b| { + let val = (b == jni::sys::JNI_TRUE).downcast_value(e); + T::upcast_value(e, val) + }) + .collect() }, | _ if jobj.is_instance_of::>(e) => { let mut vec = Vec::new(); (0..len).for_each(|ix| { - let obj = e.get_object_array_element(arr, ix as i32).unwrap_java(e); - vec.push(java::lang::Object::from_local(e, obj).upcast_to::(e)); - }); + let obj = e.get_object_array_element(arr, ix as i32).unwrap_java(e); + vec.push(java::lang::Object::from_local(e, obj).upcast_to::(e)); + }); vec }, | _ => { let cls = e.get_object_class(&jobj).unwrap_java(e); - panic!( - "unknown array type {}", - java::lang::Object::from_local(e, cls).to_string(e) - ); + panic!("unknown array type {}", + java::lang::Object::from_local(e, cls).to_string(e)); }, } } @@ -172,15 +171,14 @@ where | u16::SIG => go!(new_char_array, set_char_array_region), | bool::SIG => go!(new_boolean_array, set_boolean_array_region), | _ => { - let arr = e - .new_object_array(self.len() as i32, java::lang::Object::SIG, JObject::null()) - .unwrap_java(e); + let arr = e.new_object_array(self.len() as i32, java::lang::Object::SIG, JObject::null()) + .unwrap_java(e); let arr_ref = &arr; self.iter().enumerate().for_each(|(ix, o)| { - let val = o.downcast_ref(e); - e.set_object_array_element(arr_ref, ix as i32, &val) - .unwrap_java(e); - }); + let val = o.downcast_ref(e); + e.set_object_array_element(arr_ref, ix as i32, &val) + .unwrap_java(e); + }); java::lang::Object::from_local(e, arr) }, @@ -188,9 +186,7 @@ where } } -impl Object for T -where - T: java::Primitive, +impl Object for T where T: java::Primitive { fn upcast(e: &mut java::Env, jobj: java::lang::Object) -> Self { let w = ::PrimitiveWrapper::upcast(e, jobj); @@ -206,22 +202,19 @@ where } fn upcast_value_ref<'e>(_: &mut java::Env<'e>, jv: JValue<'e, '_>) -> Self - where - Self: Sized, + where Self: Sized { T::from_jvalue_ref(jv) } fn upcast_value(_: &mut java::Env, jv: JValueOwned) -> Self - where - Self: Sized, + where Self: Sized { T::from_jvalue(jv) } fn downcast_value<'e>(self, _: &mut java::Env<'e>) -> JValueOwned<'e> - where - Self: Sized, + where Self: Sized { self.into_jvalue() } @@ -241,22 +234,19 @@ impl Object for () { } fn upcast_value_ref<'e>(_: &mut java::Env<'e>, jv: JValue<'e, '_>) -> Self - where - Self: Sized, + where Self: Sized { jv.v().unwrap() } fn upcast_value<'e>(_: &mut java::Env<'e>, jv: JValueOwned<'e>) -> Self - where - Self: Sized, + where Self: Sized { jv.v().unwrap() } fn downcast_value<'e>(self, _: &mut java::Env<'e>) -> JValueOwned<'e> - where - Self: Sized, + where Self: Sized { JValueOwned::Void } diff --git a/toad-jni/src/java/primitive.rs b/toad-jni/src/java/primitive.rs index cd4ef4f3..db4f582e 100644 --- a/toad-jni/src/java/primitive.rs +++ b/toad-jni/src/java/primitive.rs @@ -5,8 +5,7 @@ use crate::java; /// Primitive java values that can be cheaply converted to / from [`JValue`] /// and can be wrapped by an Object class. pub trait Primitive -where - Self: java::Type + Sized + Copy, + where Self: java::Type + Sized + Copy { /// The Object type that this type may be wrapped with type PrimitiveWrapper: java::Class; diff --git a/toad-jni/src/java/result.rs b/toad-jni/src/java/result.rs index 46e85783..7beb01a0 100644 --- a/toad-jni/src/java/result.rs +++ b/toad-jni/src/java/result.rs @@ -15,18 +15,15 @@ pub trait ResultYieldToJavaOrThrow { fn yield_to_java_or_throw(self, e: &mut java::Env) -> jobject; } -impl ResultYieldToJavaOrThrow for Result -where - T: java::Object, +impl ResultYieldToJavaOrThrow for Result where T: java::Object { fn yield_to_java_or_throw(self, e: &mut java::Env) -> jobject { - self - .map(|ok| ok.yield_to_java(e)) - .map_err(|err| { - let err = JThrowable::from(err.downcast(e).to_local(e)); - e.throw(err).unwrap() - }) - .unwrap_or(*JObject::null()) + self.map(|ok| ok.yield_to_java(e)) + .map_err(|err| { + let err = JThrowable::from(err.downcast(e).to_local(e)); + e.throw(err).unwrap() + }) + .unwrap_or(*JObject::null()) } } diff --git a/toad-jni/src/java/ty.rs b/toad-jni/src/java/ty.rs index 990838cb..4d51616a 100644 --- a/toad-jni/src/java/ty.rs +++ b/toad-jni/src/java/ty.rs @@ -34,8 +34,7 @@ impl Signature { /// Get the `Signature` instance for type `T` pub const fn of() -> Self - where - T: Type, + where T: Type { T::SIG } @@ -46,10 +45,9 @@ impl Signature { use jni::signature::ReturnType::*; let ret = self.as_str(); - let ret = ret - .split(')') - .nth(1) - .unwrap_or_else(|| panic!("{:?} is not a function signature", self)); + let ret = ret.split(')') + .nth(1) + .unwrap_or_else(|| panic!("{:?} is not a function signature", self)); if ret.starts_with(Self::ARRAY_OF.as_str()) { Array @@ -57,26 +55,24 @@ impl Signature { Object } else { Primitive(match Signature::empty().push_str(ret) { - | <()>::SIG => Void, - | bool::SIG => Boolean, - | u16::SIG => Char, - | i8::SIG => Byte, - | i16::SIG => Short, - | i32::SIG => Int, - | i64::SIG => Long, - | f32::SIG => Float, - | f64::SIG => Double, - | _ => unreachable!(), - }) + | <()>::SIG => Void, + | bool::SIG => Boolean, + | u16::SIG => Char, + | i8::SIG => Byte, + | i16::SIG => Short, + | i32::SIG => Int, + | i64::SIG => Long, + | f32::SIG => Float, + | f64::SIG => Double, + | _ => unreachable!(), + }) } } const fn empty() -> Self { - Self { - bytes: [0; 256], - len: 0, - finished: false, - } + Self { bytes: [0; 256], + len: 0, + finished: false } } pub(crate) const fn function() -> Self { @@ -88,10 +84,9 @@ impl Signature { } const fn class(path: &'static str) -> Self { - Self::empty() - .concat(Self::CLASS_PATH_OPEN) - .push_str(path) - .concat(Self::CLASS_PATH_CLOSE) + Self::empty().concat(Self::CLASS_PATH_OPEN) + .push_str(path) + .concat(Self::CLASS_PATH_CLOSE) } const fn next(&self) -> usize { @@ -230,9 +225,7 @@ pub trait Type: type_sealed::TypeSealed { fn jni() -> jni::signature::JavaType; } -impl Type for T -where - T: java::Class, +impl Type for T where T: java::Class { const SIG: Signature = Signature::class(T::PATH); fn jni() -> jni::signature::JavaType { @@ -240,9 +233,7 @@ where } } -impl Type for Result -where - T: java::Class, +impl Type for Result where T: java::Class { const SIG: Signature = Signature::class(T::PATH); fn jni() -> jni::signature::JavaType { @@ -320,9 +311,7 @@ impl Type for bool { } } -impl Type for Vec -where - T: Type, +impl Type for Vec where T: Type { const SIG: Signature = Signature::array_of(T::SIG); fn jni() -> jni::signature::JavaType { @@ -330,9 +319,7 @@ where } } -impl Type for fn() -> R -where - R: Type, +impl Type for fn() -> R where R: Type { const SIG: Signature = Signature::function().ret(R::SIG); fn jni() -> jni::signature::JavaType { @@ -344,9 +331,8 @@ where } impl Type for fn(A) -> R -where - R: Type, - A: Type, + where R: Type, + A: Type { const SIG: Signature = Signature::function().concat(A::SIG).ret(R::SIG); fn jni() -> jni::signature::JavaType { @@ -358,15 +344,13 @@ where } impl Type for fn(A, B) -> R -where - R: Type, - A: Type, - B: Type, + where R: Type, + A: Type, + B: Type { - const SIG: Signature = Signature::function() - .concat(A::SIG) - .concat(B::SIG) - .ret(R::SIG); + const SIG: Signature = Signature::function().concat(A::SIG) + .concat(B::SIG) + .ret(R::SIG); fn jni() -> jni::signature::JavaType { jni::signature::JavaType::Method(Box::new(jni::signature::TypeSignature { args: vec![A::jni(), B::jni()], @@ -376,17 +360,15 @@ where } impl Type for fn(A, B, C) -> R -where - R: Type, - A: Type, - B: Type, - C: Type, + where R: Type, + A: Type, + B: Type, + C: Type { - const SIG: Signature = Signature::function() - .concat(A::SIG) - .concat(B::SIG) - .concat(C::SIG) - .ret(R::SIG); + const SIG: Signature = Signature::function().concat(A::SIG) + .concat(B::SIG) + .concat(C::SIG) + .ret(R::SIG); fn jni() -> jni::signature::JavaType { jni::signature::JavaType::Method(Box::new(jni::signature::TypeSignature { args: vec![A::jni(), B::jni(), C::jni()], @@ -396,19 +378,17 @@ where } impl Type for fn(A, B, C, D) -> R -where - R: Type, - A: Type, - B: Type, - C: Type, - D: Type, + where R: Type, + A: Type, + B: Type, + C: Type, + D: Type { - const SIG: Signature = Signature::function() - .concat(A::SIG) - .concat(B::SIG) - .concat(C::SIG) - .concat(D::SIG) - .ret(R::SIG); + const SIG: Signature = Signature::function().concat(A::SIG) + .concat(B::SIG) + .concat(C::SIG) + .concat(D::SIG) + .ret(R::SIG); fn jni() -> jni::signature::JavaType { jni::signature::JavaType::Method(Box::new(jni::signature::TypeSignature { args: vec![A::jni(), B::jni(), C::jni(), D::jni()], @@ -418,21 +398,19 @@ where } impl Type for fn(A, B, C, D, E) -> R -where - R: Type, - A: Type, - B: Type, - C: Type, - D: Type, - E: Type, + where R: Type, + A: Type, + B: Type, + C: Type, + D: Type, + E: Type { - const SIG: Signature = Signature::function() - .concat(A::SIG) - .concat(B::SIG) - .concat(C::SIG) - .concat(D::SIG) - .concat(E::SIG) - .ret(R::SIG); + const SIG: Signature = Signature::function().concat(A::SIG) + .concat(B::SIG) + .concat(C::SIG) + .concat(D::SIG) + .concat(E::SIG) + .ret(R::SIG); fn jni() -> jni::signature::JavaType { jni::signature::JavaType::Method(Box::new(jni::signature::TypeSignature { args: vec![A::jni(), B::jni(), C::jni(), D::jni(), E::jni()], @@ -451,39 +429,23 @@ pub mod test { use jni::signature::ReturnType::*; assert_eq!(Signature::of::().return_type(), Primitive(Void)); - assert_eq!( - Signature::of:: String>().return_type(), - Object - ); - assert_eq!( - Signature::of:: Vec>().return_type(), - Array - ); - assert_eq!( - Signature::of:: u16>().return_type(), - Primitive(Char) - ); - assert_eq!( - Signature::of:: bool>().return_type(), - Primitive(Boolean) - ); + assert_eq!(Signature::of:: String>().return_type(), + Object); + assert_eq!(Signature::of:: Vec>().return_type(), + Array); + assert_eq!(Signature::of:: u16>().return_type(), + Primitive(Char)); + assert_eq!(Signature::of:: bool>().return_type(), + Primitive(Boolean)); assert_eq!(Signature::of:: i8>().return_type(), Primitive(Byte)); - assert_eq!( - Signature::of:: i16>().return_type(), - Primitive(Short) - ); + assert_eq!(Signature::of:: i16>().return_type(), + Primitive(Short)); assert_eq!(Signature::of:: i32>().return_type(), Primitive(Int)); - assert_eq!( - Signature::of:: i64>().return_type(), - Primitive(Long) - ); - assert_eq!( - Signature::of:: f32>().return_type(), - Primitive(Float) - ); - assert_eq!( - Signature::of:: f64>().return_type(), - Primitive(Double) - ); + assert_eq!(Signature::of:: i64>().return_type(), + Primitive(Long)); + assert_eq!(Signature::of:: f32>().return_type(), + Primitive(Float)); + assert_eq!(Signature::of:: f64>().return_type(), + Primitive(Double)); } } diff --git a/toad-jni/src/java/util/list.rs b/toad-jni/src/java/util/list.rs index 494ce159..406a9743 100644 --- a/toad-jni/src/java/util/list.rs +++ b/toad-jni/src/java/util/list.rs @@ -8,16 +8,12 @@ use crate::java; /// java/util/ArrayList pub struct ArrayList(java::lang::Object, PhantomData); -impl java::Class for ArrayList -where - T: java::Object, +impl java::Class for ArrayList where T: java::Object { const PATH: &'static str = "java/util/ArrayList"; } -impl java::Object for ArrayList -where - T: java::Object, +impl java::Object for ArrayList where T: java::Object { fn upcast(_e: &mut java::Env, jobj: java::lang::Object) -> Self { Self(jobj, PhantomData) @@ -32,9 +28,7 @@ where } } -impl ArrayList -where - T: java::Object, +impl ArrayList where T: java::Object { /// java.util.ArrayList.get(int) pub fn get(&self, e: &mut java::Env, ix: i32) -> T { @@ -98,22 +92,18 @@ where } } -impl Extend for ArrayList -where - T: java::Object, +impl Extend for ArrayList where T: java::Object { fn extend>(&mut self, iter: I) { let mut e = java::env(); let e = &mut e; iter.into_iter().for_each(|t| { - self.append(e, t); - }) + self.append(e, t); + }) } } -impl Len for ArrayList -where - T: java::Object, +impl Len for ArrayList where T: java::Object { const CAPACITY: Option = None; @@ -126,9 +116,7 @@ where } } -impl Trunc for ArrayList -where - T: java::Object, +impl Trunc for ArrayList where T: java::Object { fn trunc(&mut self, desired_len: usize) -> () { let mut e = java::env(); @@ -151,25 +139,19 @@ where } } -impl IntoIterator for ArrayList -where - T: java::Object, +impl IntoIterator for ArrayList where T: java::Object { type Item = T; type IntoIter = ArrayListIter; fn into_iter(self) -> Self::IntoIter { - ArrayListIter { - ix: 0, - len: self.len(), - list: self, - } + ArrayListIter { ix: 0, + len: self.len(), + list: self } } } -impl FromIterator for ArrayList -where - T: java::Object, +impl FromIterator for ArrayList where T: java::Object { fn from_iter>(iter: I) -> Self { let mut e = java::env(); @@ -185,22 +167,17 @@ where } } -impl Default for ArrayList -where - T: java::Object, +impl Default for ArrayList where T: java::Object { fn default() -> Self { Self::new(&mut java::env()) } } -impl Filled for ArrayList -where - T: java::Object, +impl Filled for ArrayList where T: java::Object { fn filled_using(_: F) -> Option - where - F: Fn() -> T, + where F: Fn() -> T { None } @@ -215,9 +192,7 @@ pub struct ArrayListIter { len: usize, } -impl Iterator for ArrayListIter -where - T: java::Object, +impl Iterator for ArrayListIter where T: java::Object { type Item = T; diff --git a/toad-jni/src/java/util/logging/level.rs b/toad-jni/src/java/util/logging/level.rs index 9930cd2e..4d0204f5 100644 --- a/toad-jni/src/java/util/logging/level.rs +++ b/toad-jni/src/java/util/logging/level.rs @@ -102,17 +102,15 @@ impl java::Object for Level { finest: F, } - static FIELD: Field = Field { - all: F::new("ALL"), - off: F::new("OFF"), - cfg: F::new("CONFIG"), - info: F::new("INFO"), - warning: F::new("WARNING"), - severe: F::new("SEVERE"), - fine: F::new("FINE"), - finer: F::new("FINER"), - finest: F::new("FINEST"), - }; + static FIELD: Field = Field { all: F::new("ALL"), + off: F::new("OFF"), + cfg: F::new("CONFIG"), + info: F::new("INFO"), + warning: F::new("WARNING"), + severe: F::new("SEVERE"), + fine: F::new("FINE"), + finer: F::new("FINER"), + finest: F::new("FINEST") }; match self { | All => &FIELD.all, @@ -124,9 +122,8 @@ impl java::Object for Level { | Off => &FIELD.off, | Warning => &FIELD.warning, | Severe => &FIELD.severe, - } - .get(e) - .object() + }.get(e) + .object() } } diff --git a/toad-jni/src/java/util/optional.rs b/toad-jni/src/java/util/optional.rs index b0727707..bae035bb 100644 --- a/toad-jni/src/java/util/optional.rs +++ b/toad-jni/src/java/util/optional.rs @@ -5,9 +5,7 @@ use crate::java; /// java/util/Optional pub struct Optional(java::lang::Object, PhantomData); -impl Optional -where - T: java::Object, +impl Optional where T: java::Object { fn cast(self) -> Optional { Optional(self.0, PhantomData) @@ -24,20 +22,18 @@ where /// java.util.Optional$of pub fn of(e: &mut java::Env, t: T) -> Self { #[allow(clippy::type_complexity)] - static OF: java::StaticMethod< - Optional, - fn(java::lang::Object) -> Optional, - > = java::StaticMethod::new("of"); + static OF: java::StaticMethod, + fn(java::lang::Object) -> Optional> = + java::StaticMethod::new("of"); let t = t.downcast(e); OF.invoke(e, t).cast() } /// Create an empty instance of `Optional` pub fn empty(e: &mut java::Env) -> Self { - static EMPTY: java::StaticMethod< - Optional, - fn() -> Optional, - > = java::StaticMethod::new("empty"); + static EMPTY: java::StaticMethod, + fn() -> Optional> = + java::StaticMethod::new("empty"); EMPTY.invoke(e).cast() } @@ -72,16 +68,12 @@ where } } -impl java::Class for Optional -where - T: java::Object, +impl java::Class for Optional where T: java::Object { const PATH: &'static str = "java/util/Optional"; } -impl java::Object for Optional -where - T: java::Object, +impl java::Object for Optional where T: java::Object { fn upcast(_e: &mut java::Env, jobj: java::lang::Object) -> Self { Self(jobj, PhantomData) diff --git a/toad-jni/src/lib.rs b/toad-jni/src/lib.rs index 973fe69d..d4fe32c9 100644 --- a/toad-jni/src/lib.rs +++ b/toad-jni/src/lib.rs @@ -168,10 +168,10 @@ mod test { pub fn init<'a>() -> java::Env<'a> { static INIT: Once = Once::new(); INIT.call_once(|| { - std::env::set_var("FOO", "bar"); - let args = InitArgsBuilder::new().build().unwrap(); - toad_jni::global::init_with(JavaVM::new(args).unwrap()); - }); + std::env::set_var("FOO", "bar"); + let args = InitArgsBuilder::new().build().unwrap(); + toad_jni::global::init_with(JavaVM::new(args).unwrap()); + }); let jvm = toad_jni::global::jvm(); jvm.attach_current_thread_permanently().unwrap() @@ -195,14 +195,11 @@ mod test { #[test] fn test_arraylist() { init(); - assert_eq!( - vec![1i8, 2, 3, 4] - .into_iter() - .collect::>() - .into_iter() - .collect::>(), - vec![1, 2, 3, 4] - ) + assert_eq!(vec![1i8, 2, 3, 4].into_iter() + .collect::>() + .into_iter() + .collect::>(), + vec![1, 2, 3, 4]) } #[test] @@ -241,10 +238,9 @@ mod test { assert_eq!(System::set_property(e, "foo.bar", "baz"), None); assert_eq!(System::get_property(e, "foo.bar"), Some("baz".to_string())); - let args = vec![8329i32, 3281, 8329 + 3281] - .into_iter() - .map(|i| i.to_primitive_wrapper(e).downcast(e)) - .collect(); + let args = vec![8329i32, 3281, 8329 + 3281].into_iter() + .map(|i| i.to_primitive_wrapper(e).downcast(e)) + .collect(); match System::console(e).into_option(e) { | Some(c) => { c.printf(e, "%d + %d = %d", args); @@ -262,24 +258,18 @@ mod test { let mut env = init(); let e = &mut env; - assert_eq!( - InetSocketAddress::new_wildcard_address(e, 1234).to_std(e), - "0.0.0.0:1234".parse().unwrap() - ); + assert_eq!(InetSocketAddress::new_wildcard_address(e, 1234).to_std(e), + "0.0.0.0:1234".parse().unwrap()); let local = InetAddress::from_std(e, IpAddr::from(Ipv4Addr::LOCALHOST)); assert_eq!(local.to_std(e), "127.0.0.1".parse::().unwrap()); - assert_eq!( - InetSocketAddress::new(e, local, 1234).to_std(e), - "127.0.0.1:1234".parse::().unwrap() - ); + assert_eq!(InetSocketAddress::new(e, local, 1234).to_std(e), + "127.0.0.1:1234".parse::().unwrap()); let local = InetAddress::from_std(e, IpAddr::from(Ipv6Addr::LOCALHOST)); assert_eq!(local.to_std(e), "::1".parse::().unwrap()); - assert_eq!( - InetSocketAddress::new(e, local, 1234).to_std(e), - "[::1]:1234".parse::().unwrap() - ); + assert_eq!(InetSocketAddress::new(e, local, 1234).to_std(e), + "[::1]:1234".parse::().unwrap()); } #[test] diff --git a/toad-len/Cargo.toml b/toad-len/Cargo.toml index fc0e77f5..84bfb1dc 100644 --- a/toad-len/Cargo.toml +++ b/toad-len/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-len" version = "0.1.3" edition = "2021" +rust-version = "1.70" description = "a `Len` trait that provides capacity and runtime length for collections" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -22,4 +23,4 @@ test = [] docs = [] [dependencies] -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} diff --git a/toad-macros/Cargo.toml b/toad-macros/Cargo.toml index d6cc830a..59f08461 100644 --- a/toad-macros/Cargo.toml +++ b/toad-macros/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-macros" version = "0.2.1" edition = "2021" +rust-version = "1.70" description = "Macros used by toad for boilerplate reduction" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" diff --git a/toad-macros/src/lib.rs b/toad-macros/src/lib.rs index a9c7990a..62393873 100644 --- a/toad-macros/src/lib.rs +++ b/toad-macros/src/lib.rs @@ -51,9 +51,8 @@ pub fn rfc_7252_doc(input: TokenStream) -> TokenStream { let sec = section_literal.value(); let docstring = gen_docstring(sec, RFC7252); - LitStr::new(&docstring, section_literal.span()) - .to_token_stream() - .into() + LitStr::new(&docstring, section_literal.span()).to_token_stream() + .into() } fn gen_docstring(sec: String, rfc: &'static str) -> String { @@ -61,29 +60,27 @@ fn gen_docstring(sec: String, rfc: &'static str) -> String { let section_rx = Regex::new(format!(r"(?s)\n{}\.\s+(.*?)(\n\d|$)", sec.replace('.', "\\.")).as_str()) .unwrap_or_else(|e| panic!("Section {} invalid: {:?}", sec, e)); - let rfc_section = section_rx - .captures_iter(rfc) - .next() - .unwrap_or_else(|| panic!("Section {} not found", sec)) - .get(1) - .unwrap_or_else(|| panic!("Section {} is empty", sec)) - .as_str(); + let rfc_section = section_rx.captures_iter(rfc) + .next() + .unwrap_or_else(|| panic!("Section {} not found", sec)) + .get(1) + .unwrap_or_else(|| panic!("Section {} is empty", sec)) + .as_str(); let mut lines = trim_leading_ws(rfc_section); - let line1 = lines - .drain(0..1) - .next() - .unwrap_or_else(|| panic!("Section {} is empty", sec)); + let line1 = lines.drain(0..1) + .next() + .unwrap_or_else(|| panic!("Section {} is empty", sec)); let rest = lines.join("\n"); format!( - r"# {title} + r"# {title} [_generated from RFC7252 section {section}_](https://datatracker.ietf.org/doc/html/rfc7252#section-{section}) {body}", - title = line1, - section = sec, - body = rest + title = line1, + section = sec, + body = rest ) } @@ -103,37 +100,34 @@ fn trim_leading_ws(text: &str) -> Vec { let trim_start = Regex::new(r"^ +").unwrap(); let trim_indent = Regex::new(r"^ ").unwrap(); - text - .split('\n') - .fold( - (Vec::::new(), TrimStart::Yes), - |(mut lines, strip), s| { - let trimmed = trim_start.replace(s, "").to_string(); - let dedented = trim_indent.replace(s, "").to_string(); - - let is_fence = trimmed.starts_with("```"); - - match (is_fence, strip) { - | (false, TrimStart::Yes) => { - lines.push(trimmed); - (lines, strip) - }, - | (false, TrimStart::InCodeFence) => { - lines.push(dedented); - (lines, strip) - }, - | (true, TrimStart::Yes) => { - lines.push(trimmed); - (lines, TrimStart::InCodeFence) - }, - | (true, TrimStart::InCodeFence) => { - lines.push(trimmed); - (lines, TrimStart::Yes) - }, - } - }, - ) - .0 + text.split('\n') + .fold((Vec::::new(), TrimStart::Yes), + |(mut lines, strip), s| { + let trimmed = trim_start.replace(s, "").to_string(); + let dedented = trim_indent.replace(s, "").to_string(); + + let is_fence = trimmed.starts_with("```"); + + match (is_fence, strip) { + | (false, TrimStart::Yes) => { + lines.push(trimmed); + (lines, strip) + }, + | (false, TrimStart::InCodeFence) => { + lines.push(dedented); + (lines, strip) + }, + | (true, TrimStart::Yes) => { + lines.push(trimmed); + (lines, TrimStart::InCodeFence) + }, + | (true, TrimStart::InCodeFence) => { + lines.push(trimmed); + (lines, TrimStart::Yes) + }, + } + }) + .0 } #[cfg(test)] @@ -170,8 +164,8 @@ Table of Contents o poo"; // preserves whitespace, finds end of section that is not last assert_eq!( - gen_docstring("1".into(), rfc), - r"# Foo + gen_docstring("1".into(), rfc), + r"# Foo [_generated from RFC7252 section 1_](https://datatracker.ietf.org/doc/html/rfc7252#section-1) bar baz quux @@ -184,8 +178,8 @@ dingus bar // finds end of section that is last assert_eq!( - gen_docstring("2".into(), rfc), - r"# Bar + gen_docstring("2".into(), rfc), + r"# Bar [_generated from RFC7252 section 2_](https://datatracker.ietf.org/doc/html/rfc7252#section-2) bingus diff --git a/toad-map/Cargo.toml b/toad-map/Cargo.toml index 70034f1e..5288796d 100644 --- a/toad-map/Cargo.toml +++ b/toad-map/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-map" version = "0.2.3" edition = "2021" +rust-version = "1.70" description = "Map / Dictionary trait that is no_std and heap-allocator-optional" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -22,5 +23,5 @@ test = [] docs = [] [dependencies] -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} toad-len = {version = "^0.1.2", default_features = false} diff --git a/toad-map/src/lib.rs b/toad-map/src/lib.rs index 1d3b904e..0076118c 100644 --- a/toad-map/src/lib.rs +++ b/toad-map/src/lib.rs @@ -64,24 +64,20 @@ pub trait Map: /// See [`HashMap.remove`] fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, - Q: Hash + Eq + Ord; + where K: Borrow, + Q: Hash + Eq + Ord; /// See [`HashMap.get`] fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a; + where K: Borrow + 'a; /// See [`HashMap.get_mut`] fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a; + where K: Borrow + 'a; /// See [`HashMap.contains_key`] fn has(&self, key: &Q) -> bool - where - K: Borrow, + where K: Borrow { self.get(key).is_some() } @@ -103,73 +99,60 @@ impl Map for BTreeMap { } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { self.remove(key) } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get(key) } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get_mut(key) } fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - btreemap_iter: Some(self.iter()), - } + Iter { array_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None, + btreemap_iter: Some(self.iter()) } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - btreemap_iter: Some(self.iter_mut()), - } + IterMut { array_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None, + btreemap_iter: Some(self.iter_mut()) } } } #[cfg(feature = "std")] impl Map for HashMap { fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: None, - btreemap_iter: None, - hashmap_iter: Some(self.iter()), - } + Iter { array_iter: None, + btreemap_iter: None, + hashmap_iter: Some(self.iter()) } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: None, - btreemap_iter: None, - hashmap_iter: Some(self.iter_mut()), - } + IterMut { array_iter: None, + btreemap_iter: None, + hashmap_iter: Some(self.iter_mut()) } } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get(key) } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { self.get_mut(key) } @@ -182,8 +165,7 @@ impl Map for HashMap { } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { self.remove(key) } @@ -207,13 +189,11 @@ impl, K: Eq + Hash + Ord, V> Map for tiny } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, + where K: Borrow { - match self - .iter() - .enumerate() - .find(|(_, (k, _))| Borrow::::borrow(*k) == key) + match self.iter() + .enumerate() + .find(|(_, (k, _))| Borrow::::borrow(*k) == key) { | Some((ix, _)) => Some(self.remove(ix).1), | None => None, @@ -221,8 +201,7 @@ impl, K: Eq + Hash + Ord, V> Map for tiny } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { match self.iter().find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), @@ -231,12 +210,10 @@ impl, K: Eq + Hash + Ord, V> Map for tiny } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { - match self - .iter_mut() - .find(|(k, _)| Borrow::::borrow(*k) == key) + match self.iter_mut() + .find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), | None => None, @@ -244,30 +221,24 @@ impl, K: Eq + Hash + Ord, V> Map for tiny } fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + Iter { array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + IterMut { array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } } #[cfg(feature = "alloc")] -impl Map for std_alloc::vec::Vec<(K, V)> -where - K: Ord + Hash, +impl Map for std_alloc::vec::Vec<(K, V)> where K: Ord + Hash { fn insert(&mut self, key: K, mut val: V) -> Result<(), InsertError> { match self.iter_mut().find(|(k, _)| k == &&key) { @@ -286,14 +257,12 @@ where } fn remove(&mut self, key: &Q) -> Option - where - K: Borrow, - Q: Hash + Eq + Ord, + where K: Borrow, + Q: Hash + Eq + Ord { - match self - .iter() - .enumerate() - .find(|(_, (k, _))| Borrow::::borrow(*k) == key) + match self.iter() + .enumerate() + .find(|(_, (k, _))| Borrow::::borrow(*k) == key) { | Some((ix, _)) => Some(self.remove(ix).1), | None => None, @@ -301,8 +270,7 @@ where } fn get<'a, Q: Hash + Eq + Ord>(&'a self, key: &Q) -> Option<&'a V> - where - K: Borrow + 'a, + where K: Borrow + 'a { match self.iter().find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), @@ -311,12 +279,10 @@ where } fn get_mut<'a, Q: Hash + Eq + Ord>(&'a mut self, key: &Q) -> Option<&'a mut V> - where - K: Borrow + 'a, + where K: Borrow + 'a { - match self - .iter_mut() - .find(|(k, _)| Borrow::::borrow(*k) == key) + match self.iter_mut() + .find(|(k, _)| Borrow::::borrow(*k) == key) { | Some((_, v)) => Some(v), | None => None, @@ -324,23 +290,19 @@ where } fn iter(&self) -> Iter<'_, K, V> { - Iter { - array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + Iter { array_iter: Some(self.deref().iter().map(Iter::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } fn iter_mut(&mut self) -> IterMut<'_, K, V> { - IterMut { - array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), - #[cfg(feature = "alloc")] - btreemap_iter: None, - #[cfg(feature = "std")] - hashmap_iter: None, - } + IterMut { array_iter: Some(self.deref_mut().iter_mut().map(IterMut::coerce_array_iter)), + #[cfg(feature = "alloc")] + btreemap_iter: None, + #[cfg(feature = "std")] + hashmap_iter: None } } } @@ -390,20 +352,16 @@ impl<'a, K: Eq + Hash, V> Iter<'a, K, V> { fn get_iter(&mut self) -> &mut dyn Iterator { #[cfg(feature = "std")] { - let (a, b, c) = ( - self.hashmap_iter.as_mut().map(|a| a as &mut _), - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b, c) = (self.hashmap_iter.as_mut().map(|a| a as &mut _), + self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).or(c).unwrap(); }; #[cfg(feature = "alloc")] { - let (a, b) = ( - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b) = (self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).unwrap(); } @@ -459,20 +417,16 @@ impl<'a, K: Eq + Hash, V> IterMut<'a, K, V> { fn get_iter(&mut self) -> &mut dyn Iterator { #[cfg(feature = "std")] { - let (a, b, c) = ( - self.hashmap_iter.as_mut().map(|a| a as &mut _), - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b, c) = (self.hashmap_iter.as_mut().map(|a| a as &mut _), + self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).or(c).unwrap(); }; #[cfg(feature = "alloc")] { - let (a, b) = ( - self.array_iter.as_mut().map(|a| a as &mut _), - self.btreemap_iter.as_mut().map(|a| a as &mut _), - ); + let (a, b) = (self.array_iter.as_mut().map(|a| a as &mut _), + self.btreemap_iter.as_mut().map(|a| a as &mut _)); return a.or(b).unwrap(); } @@ -493,18 +447,17 @@ impl<'a, K: Eq + Hash, V> Iterator for IterMut<'a, K, V> { mod tests { use super::*; - fn impls() -> ( - impl Map, - impl Map, - impl Map, - impl Map, - ) { - ( - HashMap::::from([("foo".into(), "bar".into())]), - BTreeMap::::from([("foo".into(), "bar".into())]), - tinyvec::array_vec!([(String, String); 16] => ("foo".into(), "bar".into())), - vec![("foo".to_string(), "bar".to_string())], + fn impls( ) + -> (impl Map, + impl Map, + impl Map, + impl Map) + { + (HashMap::::from([("foo".into(), "bar".into())]), + BTreeMap::::from([("foo".into(), "bar".into())]), + tinyvec::array_vec!([(String, String); 16] => ("foo".into(), "bar".into())), + vec![("foo".to_string(), "bar".to_string())]) } macro_rules! each_impl { @@ -593,15 +546,11 @@ mod tests { let mut kvs = map.into_iter().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - ("a".into(), "a".into()), - ("b".into(), "b".into()), - ("c".into(), "c".into()), - ("foo".into(), "bar".into()), - ] - ); + assert_eq!(kvs, + vec![("a".into(), "a".into()), + ("b".into(), "b".into()), + ("c".into(), "c".into()), + ("foo".into(), "bar".into()),]); } each_impl!(test_into_iter); @@ -617,15 +566,11 @@ mod tests { let mut kvs = map.iter().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - (&"a".into(), &"a".into()), - (&"b".into(), &"b".into()), - (&"c".into(), &"c".into()), - (&"foo".into(), &"bar".into()), - ] - ); + assert_eq!(kvs, + vec![(&"a".into(), &"a".into()), + (&"b".into(), &"b".into()), + (&"c".into(), &"c".into()), + (&"foo".into(), &"bar".into()),]); } each_impl!(test_iter); @@ -641,15 +586,11 @@ mod tests { let mut kvs = map.iter_mut().collect::>(); kvs.sort(); - assert_eq!( - kvs, - vec![ - (&"a".into(), &mut "a".into()), - (&"b".into(), &mut "b".into()), - (&"c".into(), &mut "c".into()), - (&"foo".into(), &mut "bar".into()), - ] - ); + assert_eq!(kvs, + vec![(&"a".into(), &mut "a".into()), + (&"b".into(), &mut "b".into()), + (&"c".into(), &mut "c".into()), + (&"foo".into(), &mut "bar".into()),]); } each_impl!(test_iter_mut); diff --git a/toad-msg/Cargo.toml b/toad-msg/Cargo.toml index 44e15f4b..2e287e1d 100644 --- a/toad-msg/Cargo.toml +++ b/toad-msg/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-msg" version = "0.19.0" edition = "2021" +rust-version = "1.70" description = "Low-level CoAP message parsing & serialization" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -46,7 +47,7 @@ name = "collections" harness = false [dependencies] -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} toad-macros = "0.2.0" blake2 = "0.10" toad-map = {version = "0.2.3", default_features = false} diff --git a/toad-msg/benches/bench_input.rs b/toad-msg/benches/bench_input.rs index c2e5841e..209e7242 100644 --- a/toad-msg/benches/bench_input.rs +++ b/toad-msg/benches/bench_input.rs @@ -23,8 +23,8 @@ impl TestInput { self.into() } pub fn get_no_alloc_message( - &self, - ) -> StackMessage { + &self) + -> StackMessage { self.into() } pub fn get_coap_lite_packet(&self) -> coap_lite::Packet { @@ -34,31 +34,23 @@ impl TestInput { impl<'a> From<&'a TestInput> for alloc::Message { fn from(inp: &'a TestInput) -> alloc::Message { - let opts: BTreeMap<_, _> = (0..inp.n_opts) - .map(|n| { - ( - OptNumber(n as u32), - vec![OptValue(core::iter::repeat(1).take(inp.opt_size).collect())], - ) - }) - .collect(); + let opts: BTreeMap<_, _> = (0..inp.n_opts).map(|n| { + (OptNumber(n as u32), + vec![OptValue(core::iter::repeat(1).take(inp.opt_size).collect())]) + }) + .collect(); - let token = core::iter::repeat(1u8) - .take(inp.tkl as _) - .collect::>(); + let token = core::iter::repeat(1u8).take(inp.tkl as _) + .collect::>(); - alloc::Message { - id: Id(1), - ty: Type::Non, - ver: Default::default(), - token: Token(token), - code: Code { - class: 2, - detail: 5, - }, - opts, - payload: Payload(core::iter::repeat(1u8).take(inp.payload_size).collect()), - } + alloc::Message { id: Id(1), + ty: Type::Non, + ver: Default::default(), + token: Token(token), + code: Code { class: 2, + detail: 5 }, + opts, + payload: Payload(core::iter::repeat(1u8).take(inp.payload_size).collect()) } } } @@ -66,31 +58,24 @@ impl<'a, const P: usize, const N: usize, const O: usize> From<&'a TestInput> for StackMessage { fn from(inp: &'a TestInput) -> StackMessage { - let opts: ArrayVec<[_; N]> = (0..inp.n_opts) - .map(|n| { - ( - OptNumber(n as u32), - tinyvec::array_vec![_ => OptValue(core::iter::repeat(1).take(inp.opt_size) - .collect())], - ) - }) - .collect(); + let opts: ArrayVec<[_; N]> = + (0..inp.n_opts).map(|n| { + (OptNumber(n as u32), + tinyvec::array_vec![_ => OptValue(core::iter::repeat(1).take(inp.opt_size) + .collect())]) + }) + .collect(); - let token = core::iter::repeat(1u8) - .take(inp.tkl as _) - .collect::>(); + let token = core::iter::repeat(1u8).take(inp.tkl as _) + .collect::>(); - StackMessage { - id: Id(1), - ty: Type::Non, - ver: Default::default(), - token: Token(token), - code: Code { - class: 2, - detail: 5, - }, - opts, - payload: Payload(core::iter::repeat(1u8).take(inp.payload_size).collect()), - } + StackMessage { id: Id(1), + ty: Type::Non, + ver: Default::default(), + token: Token(token), + code: Code { class: 2, + detail: 5 }, + opts, + payload: Payload(core::iter::repeat(1u8).take(inp.payload_size).collect()) } } } diff --git a/toad-msg/benches/collections.rs b/toad-msg/benches/collections.rs index 6ec4be8b..7e55b265 100644 --- a/toad-msg/benches/collections.rs +++ b/toad-msg/benches/collections.rs @@ -6,93 +6,59 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; fn collections(c: &mut Criterion) { c.bench_function("array::alloc", |b| b.iter(|| [0u8; 2048])); c.bench_function("alloc::vec::Vec::alloc", |b| { - b.iter(|| std::vec::Vec::::with_capacity(2048)) - }); + b.iter(|| std::vec::Vec::::with_capacity(2048)) + }); c.bench_function("heapless::Vec::alloc", |b| { - b.iter(heapless::Vec::::new) - }); + b.iter(heapless::Vec::::new) + }); c.bench_function("arrayvec::ArrayVec::alloc", |b| { - b.iter(arrayvec::ArrayVec::::new) - }); + b.iter(arrayvec::ArrayVec::::new) + }); c.bench_function("tinyvec::ArrayVec::alloc", |b| { - b.iter(tinyvec::ArrayVec::<[u8; 2048]>::new) - }); + b.iter(tinyvec::ArrayVec::<[u8; 2048]>::new) + }); c.bench_function("std::vec::Vec::push", |b| { - b.iter_batched( - || std::vec::Vec::::with_capacity(16), - |mut vec| vec.push(255), - BatchSize::SmallInput, - ) - }); + b.iter_batched(|| std::vec::Vec::::with_capacity(16), + |mut vec| vec.push(255), + BatchSize::SmallInput) + }); c.bench_function("heapless::Vec::push", |b| { - b.iter_batched( - heapless::Vec::::new, - |mut vec| vec.push(255), - BatchSize::SmallInput, - ) - }); + b.iter_batched(heapless::Vec::::new, + |mut vec| vec.push(255), + BatchSize::SmallInput) + }); c.bench_function("arrayvec::ArrayVec::push", |b| { - b.iter_batched( - arrayvec::ArrayVec::::new, - |mut vec| vec.push(255), - BatchSize::SmallInput, - ) - }); + b.iter_batched(arrayvec::ArrayVec::::new, + |mut vec| vec.push(255), + BatchSize::SmallInput) + }); c.bench_function("tinyvec::ArrayVec::push", |b| { - b.iter_batched( - tinyvec::ArrayVec::<[u8; 16]>::new, - |mut vec| vec.push(255), - BatchSize::SmallInput, - ) - }); + b.iter_batched(tinyvec::ArrayVec::<[u8; 16]>::new, + |mut vec| vec.push(255), + BatchSize::SmallInput) + }); c.bench_function("std::vec::Vec::extend", |b| { - b.iter_batched( - || { - ( - std::vec::Vec::::with_capacity(2048), - core::iter::repeat(255).take(2048), - ) - }, - |(mut vec, other)| vec.extend(other), - BatchSize::SmallInput, - ) - }); + b.iter_batched(|| { + (std::vec::Vec::::with_capacity(2048), core::iter::repeat(255).take(2048)) + }, + |(mut vec, other)| vec.extend(other), + BatchSize::SmallInput) + }); c.bench_function("heapless::Vec::extend", |b| { - b.iter_batched( - || { - ( - heapless::Vec::::new(), - core::iter::repeat(255).take(2048), - ) - }, - |(mut vec, other)| vec.extend(other), - BatchSize::SmallInput, - ) - }); + b.iter_batched(|| (heapless::Vec::::new(), core::iter::repeat(255).take(2048)), + |(mut vec, other)| vec.extend(other), + BatchSize::SmallInput) + }); c.bench_function("arrayvec::ArrayVec::extend", |b| { - b.iter_batched( - || { - ( - arrayvec::ArrayVec::::new(), - core::iter::repeat(255).take(2048), - ) - }, - |(mut vec, other)| vec.extend(other), - BatchSize::SmallInput, - ) - }); + b.iter_batched(|| (arrayvec::ArrayVec::::new(), core::iter::repeat(255).take(2048)), + |(mut vec, other)| vec.extend(other), + BatchSize::SmallInput) + }); c.bench_function("tinyvec::ArrayVec::extend", |b| { - b.iter_batched( - || { - ( - tinyvec::ArrayVec::<[u8; 2048]>::new(), - core::iter::repeat(255).take(2048), - ) - }, - |(mut vec, other)| vec.extend(other), - BatchSize::SmallInput, - ) - }); + b.iter_batched(|| (tinyvec::ArrayVec::<[u8; 2048]>::new(), core::iter::repeat(255).take(2048)), + |(mut vec, other)| vec.extend(other), + BatchSize::SmallInput) + }); } criterion_group! { diff --git a/toad-msg/benches/common.rs b/toad-msg/benches/common.rs index 7da7f654..959b2198 100644 --- a/toad-msg/benches/common.rs +++ b/toad-msg/benches/common.rs @@ -2,12 +2,5 @@ use tinyvec::ArrayVec; use toad_msg::*; pub type StackMessage = - Message< - ArrayVec<[u8; PAYLOAD_BYTES]>, - ArrayVec< - [( - OptNumber, - ArrayVec<[OptValue>; 1]>, - ); OPTS_MAX], - >, - >; + Message, + ArrayVec<[(OptNumber, ArrayVec<[OptValue>; 1]>); OPTS_MAX]>>; diff --git a/toad-msg/benches/from_bytes.rs b/toad-msg/benches/from_bytes.rs index cb58b871..9651be46 100644 --- a/toad-msg/benches/from_bytes.rs +++ b/toad-msg/benches/from_bytes.rs @@ -13,115 +13,79 @@ fn message_from_bytes(c: &mut Criterion) { let mut group = c.benchmark_group("msg/from_bytes"); group.measurement_time(std::time::Duration::from_secs(5)); - let inputs = vec![ - TestInput { - tkl: 0, - n_opts: 0, - opt_size: 0, - payload_size: 0, - }, - TestInput { - tkl: 4, - n_opts: 4, - opt_size: 8, - payload_size: 16, - }, - TestInput { - tkl: 4, - n_opts: 4, - opt_size: 16, - payload_size: 16, - }, - TestInput { - tkl: 4, - n_opts: 8, - opt_size: 32, - payload_size: 16, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 16, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 32, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 128, - }, - TestInput { - tkl: 8, - n_opts: 16, - opt_size: 64, - payload_size: 128, - }, - TestInput { - tkl: 8, - n_opts: 16, - opt_size: 64, - payload_size: 512, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 64, - payload_size: 512, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 64, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 256, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 512, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 512, - payload_size: 4096, - }, - ]; + let inputs = vec![TestInput { tkl: 0, + n_opts: 0, + opt_size: 0, + payload_size: 0 }, + TestInput { tkl: 4, + n_opts: 4, + opt_size: 8, + payload_size: 16 }, + TestInput { tkl: 4, + n_opts: 4, + opt_size: 16, + payload_size: 16 }, + TestInput { tkl: 4, + n_opts: 8, + opt_size: 32, + payload_size: 16 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 16 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 32 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 128 }, + TestInput { tkl: 8, + n_opts: 16, + opt_size: 64, + payload_size: 128 }, + TestInput { tkl: 8, + n_opts: 16, + opt_size: 64, + payload_size: 512 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 64, + payload_size: 512 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 64, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 256, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 512, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 512, + payload_size: 4096 },]; type ArrayMessage = StackMessage<4096, 32, 512>; for inp in inputs.iter() { let bytes = inp.get_bytes(); - group.bench_with_input( - BenchmarkId::new("toad_msg/alloc/size", bytes.len()), - &bytes, - |b, bytes| b.iter(|| alloc::Message::try_from_bytes(bytes)), - ); + group.bench_with_input(BenchmarkId::new("toad_msg/alloc/size", bytes.len()), + &bytes, + |b, bytes| b.iter(|| alloc::Message::try_from_bytes(bytes))); - group.bench_with_input( - BenchmarkId::new("toad_msg/no_alloc/size", bytes.len()), - &bytes, - |b, bytes| b.iter(|| ArrayMessage::try_from_bytes(bytes)), - ); + group.bench_with_input(BenchmarkId::new("toad_msg/no_alloc/size", bytes.len()), + &bytes, + |b, bytes| b.iter(|| ArrayMessage::try_from_bytes(bytes))); - group.bench_with_input( - BenchmarkId::new("coap_lite/size", bytes.len()), - &bytes, - |b, bytes| b.iter(|| coap_lite::Packet::from_bytes(bytes)), - ); + group.bench_with_input(BenchmarkId::new("coap_lite/size", bytes.len()), + &bytes, + |b, bytes| b.iter(|| coap_lite::Packet::from_bytes(bytes))); } group.finish(); } diff --git a/toad-msg/benches/profile.rs b/toad-msg/benches/profile.rs index e06936df..3e4bb238 100644 --- a/toad-msg/benches/profile.rs +++ b/toad-msg/benches/profile.rs @@ -12,59 +12,41 @@ use common::*; fn profile(c: &mut Criterion) { type ArrayMessage = StackMessage<1024, 16, 128>; - let inp = TestInput { - tkl: 8, - n_opts: 16, - opt_size: 128, - payload_size: 1024, - }; + let inp = TestInput { tkl: 8, + n_opts: 16, + opt_size: 128, + payload_size: 1024 }; let bytes: Vec = inp.get_bytes(); let coap_lite_packet = coap_lite::Packet::from_bytes(&bytes).unwrap(); - c.bench_with_input( - BenchmarkId::new("msg/profile/to_bytes", "toad_msg/alloc"), - &inp, - |b, inp| { - b.iter_batched( - || alloc::Message::from(inp), - |m| m.try_into_bytes::>().unwrap(), - BatchSize::SmallInput, - ) - }, - ); - c.bench_with_input( - BenchmarkId::new("msg/profile/to_bytes", "toad_msg/no_alloc"), - &inp, - |b, inp| { - b.iter_batched( - || ArrayMessage::from(inp), - |msg| msg.try_into_bytes::>(), - BatchSize::SmallInput, - ) - }, - ); - c.bench_with_input( - BenchmarkId::new("msg/profile/to_bytes", "coap_lite"), - &coap_lite_packet, - |b, packet| b.iter(|| packet.to_bytes()), - ); + c.bench_with_input(BenchmarkId::new("msg/profile/to_bytes", "toad_msg/alloc"), + &inp, + |b, inp| { + b.iter_batched(|| alloc::Message::from(inp), + |m| m.try_into_bytes::>().unwrap(), + BatchSize::SmallInput) + }); + c.bench_with_input(BenchmarkId::new("msg/profile/to_bytes", "toad_msg/no_alloc"), + &inp, + |b, inp| { + b.iter_batched(|| ArrayMessage::from(inp), + |msg| msg.try_into_bytes::>(), + BatchSize::SmallInput) + }); + c.bench_with_input(BenchmarkId::new("msg/profile/to_bytes", "coap_lite"), + &coap_lite_packet, + |b, packet| b.iter(|| packet.to_bytes())); - c.bench_with_input( - BenchmarkId::new("msg/profile/from_bytes", "toad_msg/alloc"), - &bytes, - |b, bytes| b.iter(|| alloc::Message::try_from_bytes(bytes)), - ); - c.bench_with_input( - BenchmarkId::new("msg/profile/from_bytes", "toad_msg/no_alloc"), - &bytes, - |b, bytes| b.iter(|| ArrayMessage::try_from_bytes(bytes)), - ); - c.bench_with_input( - BenchmarkId::new("msg/profile/from_bytes", "coap_lite"), - &bytes, - |b, bytes| b.iter(|| coap_lite::Packet::from_bytes(bytes)), - ); + c.bench_with_input(BenchmarkId::new("msg/profile/from_bytes", "toad_msg/alloc"), + &bytes, + |b, bytes| b.iter(|| alloc::Message::try_from_bytes(bytes))); + c.bench_with_input(BenchmarkId::new("msg/profile/from_bytes", "toad_msg/no_alloc"), + &bytes, + |b, bytes| b.iter(|| ArrayMessage::try_from_bytes(bytes))); + c.bench_with_input(BenchmarkId::new("msg/profile/from_bytes", "coap_lite"), + &bytes, + |b, bytes| b.iter(|| coap_lite::Packet::from_bytes(bytes))); } criterion_group! { diff --git a/toad-msg/benches/some_vs_once.rs b/toad-msg/benches/some_vs_once.rs index 8cdbc091..197725ff 100644 --- a/toad-msg/benches/some_vs_once.rs +++ b/toad-msg/benches/some_vs_once.rs @@ -2,11 +2,11 @@ use criterion::{criterion_group, criterion_main, Criterion}; fn some_vs_once(c: &mut Criterion) { c.bench_function("core::iter::once", |b| { - b.iter(|| std::iter::once(0u8).collect::>()) - }); + b.iter(|| std::iter::once(0u8).collect::>()) + }); c.bench_function("Option::into_iter", |b| { - b.iter(|| Some(0u8).into_iter().collect::>()) - }); + b.iter(|| Some(0u8).into_iter().collect::>()) + }); } criterion_group! { diff --git a/toad-msg/benches/to_bytes.rs b/toad-msg/benches/to_bytes.rs index f2f7adfa..6cf37e53 100644 --- a/toad-msg/benches/to_bytes.rs +++ b/toad-msg/benches/to_bytes.rs @@ -10,126 +10,86 @@ fn message_to_bytes(c: &mut Criterion) { let mut group = c.benchmark_group("msg/to_bytes"); group.measurement_time(std::time::Duration::from_secs(5)); - let inputs = vec![ - TestInput { - tkl: 0, - n_opts: 0, - opt_size: 0, - payload_size: 0, - }, - TestInput { - tkl: 4, - n_opts: 4, - opt_size: 8, - payload_size: 16, - }, - TestInput { - tkl: 4, - n_opts: 4, - opt_size: 16, - payload_size: 16, - }, - TestInput { - tkl: 4, - n_opts: 8, - opt_size: 32, - payload_size: 16, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 16, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 32, - }, - TestInput { - tkl: 8, - n_opts: 8, - opt_size: 64, - payload_size: 128, - }, - TestInput { - tkl: 8, - n_opts: 16, - opt_size: 64, - payload_size: 128, - }, - TestInput { - tkl: 8, - n_opts: 16, - opt_size: 64, - payload_size: 512, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 64, - payload_size: 512, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 64, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 256, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 512, - payload_size: 2048, - }, - TestInput { - tkl: 8, - n_opts: 32, - opt_size: 512, - payload_size: 4096, - }, - ]; + let inputs = vec![TestInput { tkl: 0, + n_opts: 0, + opt_size: 0, + payload_size: 0 }, + TestInput { tkl: 4, + n_opts: 4, + opt_size: 8, + payload_size: 16 }, + TestInput { tkl: 4, + n_opts: 4, + opt_size: 16, + payload_size: 16 }, + TestInput { tkl: 4, + n_opts: 8, + opt_size: 32, + payload_size: 16 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 16 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 32 }, + TestInput { tkl: 8, + n_opts: 8, + opt_size: 64, + payload_size: 128 }, + TestInput { tkl: 8, + n_opts: 16, + opt_size: 64, + payload_size: 128 }, + TestInput { tkl: 8, + n_opts: 16, + opt_size: 64, + payload_size: 512 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 64, + payload_size: 512 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 64, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 256, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 512, + payload_size: 2048 }, + TestInput { tkl: 8, + n_opts: 32, + opt_size: 512, + payload_size: 4096 },]; for inp in inputs.iter() { let bytes = inp.get_bytes(); - group.bench_with_input( - BenchmarkId::new("toad_msg/alloc/size", bytes.len()), - inp, - |b, inp| { - b.iter_batched( - || inp.get_alloc_message(), - |m| m.try_into_bytes::>().unwrap(), - BatchSize::SmallInput, - ) - }, - ); + group.bench_with_input(BenchmarkId::new("toad_msg/alloc/size", bytes.len()), + inp, + |b, inp| { + b.iter_batched(|| inp.get_alloc_message(), + |m| m.try_into_bytes::>().unwrap(), + BatchSize::SmallInput) + }); - group.bench_with_input( - BenchmarkId::new("toad_msg/no_alloc/size", bytes.len()), - inp, - |b, inp| { - b.iter_batched( - || inp.get_no_alloc_message::<4096, 32, 512>(), - |msg| msg.try_into_bytes::>(), - BatchSize::SmallInput, - ) - }, - ); + group.bench_with_input(BenchmarkId::new("toad_msg/no_alloc/size", bytes.len()), + inp, + |b, inp| { + b.iter_batched(|| inp.get_no_alloc_message::<4096, 32, 512>(), + |msg| msg.try_into_bytes::>(), + BatchSize::SmallInput) + }); let cl_packet = inp.get_coap_lite_packet(); - group.bench_with_input( - BenchmarkId::new("coap_lite/size", bytes.len()), - &cl_packet, - |b, inp| b.iter(|| inp.to_bytes()), - ); + group.bench_with_input(BenchmarkId::new("coap_lite/size", bytes.len()), + &cl_packet, + |b, inp| b.iter(|| inp.to_bytes())); } group.finish(); } diff --git a/toad-msg/examples/server.rs b/toad-msg/examples/server.rs index 0defe5c2..603742f5 100644 --- a/toad-msg/examples/server.rs +++ b/toad-msg/examples/server.rs @@ -29,11 +29,9 @@ fn main() { let n = sock.recv(&mut buf).unwrap(); let rep = Message::try_from_bytes(&buf[0..n]).unwrap(); - println!( - "client: 📨 received {} {}", - rep.code.to_string(), - String::from_utf8(rep.payload.0).unwrap() - ); + println!("client: 📨 received {} {}", + rep.code.to_string(), + String::from_utf8(rep.payload.0).unwrap()); } fn spawn_server(b: Arc) -> JoinHandle<()> { @@ -65,11 +63,10 @@ fn spawn_server(b: Arc) -> JoinHandle<()> { | 4 => "DELETE", | _ => unreachable!(), }; - let (_, path_opt) = req - .opts - .iter() - .find(|(n, _)| n.0 == 11) - .ok_or_else(|| err("no Uri-Path"))?; + let (_, path_opt) = req.opts + .iter() + .find(|(n, _)| n.0 == 11) + .ok_or_else(|| err("no Uri-Path"))?; let path = String::from_utf8(path_opt[0].0.clone()).map_err(err)?; let rep = match path.as_str() { @@ -77,16 +74,13 @@ fn spawn_server(b: Arc) -> JoinHandle<()> { | _ => not_found(req.token), }; - println!( - "server: 📨 got {} {}, sending {}", - method, - path, - rep.code.to_string() - ); + println!("server: 📨 got {} {}, sending {}", + method, + path, + rep.code.to_string()); - sock - .send_to(&rep.try_into_bytes::>().unwrap(), addr) - .map_err(err)?; + sock.send_to(&rep.try_into_bytes::>().unwrap(), addr) + .map_err(err)?; } }(); @@ -98,51 +92,37 @@ fn spawn_server(b: Arc) -> JoinHandle<()> { fn get_hello() -> Message { use toad_msg::*; - Message { - id: Id(1), - ty: Type::Con, - ver: Default::default(), - token: Token(Default::default()), - code: Code { - class: 0, - detail: 1, - }, // GET - opts: BTreeMap::from([( - OptNumber(11), // Uri-Path - vec![OptValue("hello".as_bytes().to_vec())], - )]), - payload: Payload(Vec::new()), - } + Message { id: Id(1), + ty: Type::Con, + ver: Default::default(), + token: Token(Default::default()), + code: Code { class: 0, + detail: 1 }, // GET + opts: BTreeMap::from([(OptNumber(11), // Uri-Path + vec![OptValue("hello".as_bytes().to_vec())])]), + payload: Payload(Vec::new()) } } fn ok_hello(token: toad_msg::Token) -> Message { use toad_msg::*; - Message { - id: Id(1), - ty: Type::Ack, // ACK - ver: Default::default(), - token, - code: Code { - class: 2, - detail: 5, - }, // 2.05 OK - opts: Default::default(), - payload: Payload("hi there!".as_bytes().to_vec()), - } + Message { id: Id(1), + ty: Type::Ack, // ACK + ver: Default::default(), + token, + code: Code { class: 2, + detail: 5 }, // 2.05 OK + opts: Default::default(), + payload: Payload("hi there!".as_bytes().to_vec()) } } fn not_found(token: toad_msg::Token) -> Message { use toad_msg::*; - Message { - id: Id(1), - ty: Type::Ack, // ACK - ver: Default::default(), - token, - code: Code { - class: 4, - detail: 4, - }, // 4.04 NOT FOUND - opts: Default::default(), - payload: Payload("not found :(".as_bytes().to_vec()), - } + Message { id: Id(1), + ty: Type::Ack, // ACK + ver: Default::default(), + token, + code: Code { class: 4, + detail: 4 }, // 4.04 NOT FOUND + opts: Default::default(), + payload: Payload("not found :(".as_bytes().to_vec()) } } diff --git a/toad-msg/src/cache_key.rs b/toad-msg/src/cache_key.rs index 3bb80f2e..f68d15dd 100644 --- a/toad-msg/src/cache_key.rs +++ b/toad-msg/src/cache_key.rs @@ -32,16 +32,15 @@ impl CacheKey for DefaultCacheKey { } fn add_cache_key(&mut self, msg: &Message) - where - P: Array + AppendCopy, - O: OptionMap, + where P: Array + AppendCopy, + O: OptionMap { msg.code.hash(&mut self.0); msg.opts.iter().for_each(|(num, vals)| { - if num.include_in_cache_key() { - vals.iter().for_each(|v| v.hash(&mut self.0)) - } - }); + if num.include_in_cache_key() { + vals.iter().for_each(|v| v.hash(&mut self.0)) + } + }); } } @@ -55,8 +54,7 @@ impl CacheKey for DefaultCacheKey { /// /// [`DefaultCacheKey`] Provides a default implementation. pub trait CacheKey -where - Self: Sized + Debug, + where Self: Sized + Debug { /// Type used to generate hashes type Hasher: Hasher; @@ -70,9 +68,8 @@ where /// /// Alternately, use [`CacheKey::cache_key`] to go directly to the [`u64`] hash. fn add_cache_key(&mut self, msg: &Message) - where - P: Array + AppendCopy, - O: OptionMap; + where P: Array + AppendCopy, + O: OptionMap; /// Add this message's cache key to the hasher's internal state and yield the [`u64`] hash. /// @@ -98,18 +95,15 @@ where /// assert_eq!(ha.hasher().finish(), hb.hasher().finish()); /// ``` fn cache_key(&mut self, msg: &Message) -> u64 - where - P: Array + AppendCopy, - O: OptionMap, + where P: Array + AppendCopy, + O: OptionMap { self.add_cache_key(msg); self.hasher().finish() } } -impl CacheKey for &mut T -where - T: CacheKey, +impl CacheKey for &mut T where T: CacheKey { type Hasher = T::Hasher; @@ -118,9 +112,8 @@ where } fn add_cache_key(&mut self, msg: &Message) - where - P: Array + AppendCopy, - O: OptionMap, + where P: Array + AppendCopy, + O: OptionMap { ::add_cache_key(self, msg) } @@ -136,8 +129,7 @@ mod test { #[test] pub fn cache_key() { fn req(stuff: F) -> u64 - where - F: FnOnce(&mut Message), + where F: FnOnce(&mut Message) { let mut req = Message::new(Type::Con, Code::GET, Id(1), Token(Default::default())); stuff(&mut req); @@ -147,52 +139,42 @@ mod test { h.hasher().finish() } - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - }), - req(|_| {}) - ); - assert_eq!( - req(|r| { - r.set_path("a/b/c").ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - }) - ); - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - }) - ); - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Text).ok(); - }) - ); - assert_eq!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }) - ); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + }), + req(|_| {})); + assert_eq!(req(|r| { + r.set_path("a/b/c").ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + })); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + })); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Text).ok(); + })); + assert_eq!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + })); } } diff --git a/toad-msg/src/lib.rs b/toad-msg/src/lib.rs index 906658ec..fff7f5bf 100644 --- a/toad-msg/src/lib.rs +++ b/toad-msg/src/lib.rs @@ -125,31 +125,26 @@ pub(crate) fn test_msg() -> (alloc::Message, Vec) { let content_format: &[u8] = b"application/json"; let options: [&[u8]; 2] = [&[0b_1100_1101u8, 0b00000011u8], content_format]; let payload: [&[u8]; 2] = [&[0b1111_1111_u8], b"hello, world!"]; - let bytes = [ - header.as_ref(), - token.as_ref(), - options.concat().as_ref(), - payload.concat().as_ref(), - ] - .concat(); + let bytes = [header.as_ref(), + token.as_ref(), + options.concat().as_ref(), + payload.concat().as_ref()].concat(); - let msg = alloc::Message { - id: Id(1), - ty: Type::Con, - ver: Version(1), - token: Token(tinyvec::array_vec!([u8; 8] => 254)), - opts: BTreeMap::from([(OptNumber(12), vec![OptValue(content_format.to_vec())])]), - code: Code { - class: 2, - detail: 5, - }, - payload: Payload(b"hello, world!".to_vec()), - }; + let msg = alloc::Message { id: Id(1), + ty: Type::Con, + ver: Version(1), + token: Token(tinyvec::array_vec!([u8; 8] => 254)), + opts: BTreeMap::from([(OptNumber(12), + vec![OptValue(content_format.to_vec())])]), + code: Code { class: 2, + detail: 5 }, + payload: Payload(b"hello, world!".to_vec()) }; (msg, bytes) } #[cfg(test)] pub(crate) mod tests { + /// Assert two byte values are equal, printing binary representations on failure. #[macro_export] macro_rules! assert_eqb { ($actual:expr, $expected:expr) => { @@ -159,21 +154,18 @@ pub(crate) mod tests { }; } + /// Assert two byte iterables are equal, printing binary representations on failure. #[macro_export] macro_rules! assert_eqb_iter { ($actual:expr, $expected:expr) => { if $actual.iter().ne($expected.iter()) { - panic!( - "expected {:?} to equal {:?}", - $actual - .into_iter() - .map(|b| format!("{:08b}", b)) - .collect::>(), - $expected - .into_iter() - .map(|b| format!("{:08b}", b)) - .collect::>() - ) + panic!("expected {:?} to equal {:?}", + $actual.into_iter() + .map(|b| format!("{:08b}", b)) + .collect::>(), + $expected.into_iter() + .map(|b| format!("{:08b}", b)) + .collect::>()) } }; } diff --git a/toad-msg/src/msg/code.rs b/toad-msg/src/msg/code.rs index 7f4dcfaf..e9563403 100644 --- a/toad-msg/src/msg/code.rs +++ b/toad-msg/src/msg/code.rs @@ -78,12 +78,10 @@ impl Code { /// ``` pub fn to_human(&self) -> [char; 4] { let to_char = |d: u8| char::from_digit(d.into(), 10).unwrap(); - [ - to_char(self.class), - '.', - to_char(self.detail / 10), - to_char(self.detail % 10), - ] + [to_char(self.class), + '.', + to_char(self.detail / 10), + to_char(self.detail % 10)] } /// Get whether this code is for a request, response, or empty message @@ -164,21 +162,15 @@ mod tests { fn parse_code() { let byte = 0b01000101_u8; let code = Code::from(byte); - assert_eq!( - code, - Code { - class: 2, - detail: 5 - } - ) + assert_eq!(code, + Code { class: 2, + detail: 5 }) } #[test] fn serialize_code() { - let code = Code { - class: 2, - detail: 5, - }; + let code = Code { class: 2, + detail: 5 }; let actual: u8 = code.into(); let expected = 0b01000101_u8; assert_eqb!(actual, expected) diff --git a/toad-msg/src/msg/mod.rs b/toad-msg/src/msg/mod.rs index d82f8f40..48889e74 100644 --- a/toad-msg/src/msg/mod.rs +++ b/toad-msg/src/msg/mod.rs @@ -47,27 +47,21 @@ use crate::{CacheKey, DefaultCacheKey, TryFromBytes}; #[derive(Default, Clone, Debug)] pub struct Payload(pub C); -impl PartialOrd for Payload -where - C: Array, +impl PartialOrd for Payload where C: Array { fn partial_cmp(&self, other: &Self) -> Option { self.0.iter().partial_cmp(other.0.iter()) } } -impl PartialEq for Payload -where - C: Array, +impl PartialEq for Payload where C: Array { fn eq(&self, other: &Self) -> bool { self.0.iter().eq(other.0.iter()) } } -impl Ord for Payload -where - C: Array, +impl Ord for Payload where C: Array { fn cmp(&self, other: &Self) -> Ordering { self.0.iter().cmp(other.0.iter()) @@ -76,18 +70,14 @@ where impl Eq for Payload where C: Array {} -impl Hash for Payload -where - C: Array, +impl Hash for Payload where C: Array { fn hash(&self, state: &mut H) { state.write(&self.0) } } -impl Payload -where - C: Array, +impl Payload where C: Array { /// Convert a reference to a Payload to a byte slice pub fn as_bytes(&self) -> &[u8] { @@ -122,11 +112,9 @@ impl TryFrom for Byte1 { let ty = b >> 4 & 0b11; // bits 2 & 3 let tkl = b & 0b1111u8; // last 4 bits - Ok(Byte1 { - ver: Version(ver), - ty: Type::try_from(ty)?, - tkl, - }) + Ok(Byte1 { ver: Version(ver), + ty: Type::try_from(ty)?, + tkl }) } } @@ -211,60 +199,51 @@ pub struct Message { } impl PartialOrd for Message -where - O: OptionMap + PartialOrd, - C: Array, + where O: OptionMap + PartialOrd, + C: Array { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Message -where - O: OptionMap + PartialEq, - C: Array, + where O: OptionMap + PartialEq, + C: Array { fn eq(&self, other: &Self) -> bool { self.id == other.id - && self.ver == other.ver - && self.code == other.code - && self.token == other.token - && self.payload == other.payload - && self.opts == other.opts + && self.ver == other.ver + && self.code == other.code + && self.token == other.token + && self.payload == other.payload + && self.opts == other.opts } } impl Ord for Message -where - O: OptionMap + PartialOrd, - C: Array, + where O: OptionMap + PartialOrd, + C: Array { fn cmp(&self, other: &Self) -> Ordering { - self - .id - .cmp(&other.id) - .then(self.ver.cmp(&other.ver)) - .then(self.code.cmp(&other.code)) - .then(self.token.cmp(&other.token)) - .then(self.payload.cmp(&other.payload)) - .then( - self - .opts - .partial_cmp(&other.opts) - .unwrap_or(Ordering::Equal), - ) + self.id + .cmp(&other.id) + .then(self.ver.cmp(&other.ver)) + .then(self.code.cmp(&other.code)) + .then(self.token.cmp(&other.token)) + .then(self.payload.cmp(&other.payload)) + .then(self.opts + .partial_cmp(&other.opts) + .unwrap_or(Ordering::Equal)) } } impl Eq for Message -where - O: OptionMap + PartialEq, - C: Array, + where O: OptionMap + PartialEq, + C: Array { } impl Hash for Message -where - O: OptionMap + PartialEq + Hash, - C: Array, + where O: OptionMap + PartialEq + Hash, + C: Array { fn hash(&self, state: &mut H) { self.id.hash(state); @@ -286,9 +265,8 @@ pub enum SetOptionError { } impl MessageOptions for Message -where - P: Array + AppendCopy, - O: OptionMap, + where P: Array + AppendCopy, + O: OptionMap { type OptValues = O::OptValues; type OptValueBytes = O::OptValue; @@ -298,11 +276,10 @@ where self.add(n, v) } - fn set( - &mut self, - n: OptNumber, - v: OptValue, - ) -> Result, Self::SetError> { + fn set(&mut self, + n: OptNumber, + v: OptValue) + -> Result, Self::SetError> { self.set(n, v) } @@ -323,8 +300,7 @@ where } fn get_strs<'a, F>(&'a self, n: OptNumber) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { self.get_strs(n) } @@ -368,11 +344,10 @@ pub trait MessageOptions { /// Replace any / all existing values with a new one, /// yielding the previous value(s) - fn set( - &mut self, - n: OptNumber, - v: OptValue, - ) -> Result, Self::SetError>; + fn set(&mut self, + n: OptNumber, + v: OptValue) + -> Result, Self::SetError>; /// Get the number of values for a given option fn count(&self, n: OptNumber) -> usize; @@ -391,8 +366,7 @@ pub trait MessageOptions { /// Get all values for an option, and interpret them as UTF-8 strings fn get_strs<'a, F>(&'a self, n: OptNumber) -> Result - where - F: FromIterator<&'a str>; + where F: FromIterator<&'a str>; /// Get the value of an option, and interpret it /// as a u8 @@ -428,51 +402,39 @@ pub trait MessageOptions { /// ``` #[doc = rfc_7252_doc!("5.10.1")] fn set_host(&mut self, host: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self - .set( - opt::known::no_repeat::HOST, - host.as_ref().as_bytes().iter().copied().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::HOST, + host.as_ref().as_bytes().iter().copied().collect()) + .map(|_| ()) } /// [`opt::known::no_repeat::BLOCK1`] fn block1(&self) -> Option { - self - .get_u32(opt::known::no_repeat::BLOCK1) - .map(block::Block::from) + self.get_u32(opt::known::no_repeat::BLOCK1) + .map(block::Block::from) } /// [`opt::known::no_repeat::BLOCK1`] fn set_block1(&mut self, size: u16, num: u32, more: bool) -> Result<(), Self::SetError> { let block = block::Block::new(size, num, more); - self - .set( - opt::known::no_repeat::BLOCK1, - OptValue(u32::from(block).to_be_bytes().iter().copied().collect()), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::BLOCK1, + OptValue(u32::from(block).to_be_bytes().iter().copied().collect())) + .map(|_| ()) } /// [`opt::known::no_repeat::BLOCK2`] fn block2(&self) -> Option { - self - .get_u32(opt::known::no_repeat::BLOCK2) - .map(block::Block::from) + self.get_u32(opt::known::no_repeat::BLOCK2) + .map(block::Block::from) } /// [`opt::known::no_repeat::BLOCK2`] fn set_block2(&mut self, size: u16, num: u32, more: bool) -> Result<(), Self::SetError> { let block = block::Block::new(size, num, more); - self - .set( - opt::known::no_repeat::BLOCK2, - OptValue(u32::from(block).to_be_bytes().iter().copied().collect()), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::BLOCK2, + OptValue(u32::from(block).to_be_bytes().iter().copied().collect())) + .map(|_| ()) } /// Get the value for the [Uri-Host](opt::known::no_repeat::HOST) option @@ -495,12 +457,9 @@ pub trait MessageOptions { /// assert_eq!(msg.port(), Some(1234)); /// ``` fn set_port(&mut self, port: u16) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::PORT, - port.to_be_bytes().into_iter().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::PORT, + port.to_be_bytes().into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Uri-Port](opt::known::no_repeat::PORT) option @@ -526,25 +485,20 @@ pub trait MessageOptions { /// Ok("cheese/havarti/suggestions".to_string())); /// ``` fn set_path(&mut self, path: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - path - .as_ref() - .split('/') - .try_for_each(|segment| { - self.add( - opt::known::repeat::PATH, - segment.as_bytes().iter().copied().collect(), - ) - }) - .map(|_| ()) + path.as_ref() + .split('/') + .try_for_each(|segment| { + self.add(opt::known::repeat::PATH, + segment.as_bytes().iter().copied().collect()) + }) + .map(|_| ()) } /// Get an iterator over the [Uri-Path](opt::known::repeat::PATH) segments fn path<'a, F>(&'a self) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { self.get_strs(opt::known::repeat::PATH) } @@ -552,27 +506,22 @@ pub trait MessageOptions { /// Get the fully built path, joining segments with '/'. #[cfg(feature = "std")] fn path_string<'a>(&'a self) -> Result { - self - .get_strs::>(opt::known::repeat::PATH) - .map(|segs| { - let mut s = segs - .into_iter() - .fold(String::new(), |s, seg| format!("{s}{seg}/")); - s.pop(); - s - }) + self.get_strs::>(opt::known::repeat::PATH) + .map(|segs| { + let mut s = segs.into_iter() + .fold(String::new(), |s, seg| format!("{s}{seg}/")); + s.pop(); + s + }) } /// Insert a new value for the [Uri-Query](opt::known::repeat::QUERY) option, /// alongside any existing values. fn add_query(&mut self, query: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self.add( - opt::known::repeat::QUERY, - query.as_ref().as_bytes().iter().copied().collect(), - ) + self.add(opt::known::repeat::QUERY, + query.as_ref().as_bytes().iter().copied().collect()) } /// Get all query parameters for this request @@ -589,8 +538,7 @@ pub trait MessageOptions { /// Ok(vec!["id[eq]=123", "price[lt]=333"])); /// ``` fn query<'a, F>(&'a self) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { self.get_strs(opt::known::repeat::QUERY) } @@ -599,12 +547,9 @@ pub trait MessageOptions { /// discarding any existing values. #[doc = rfc_7252_doc!("5.10.3")] fn set_content_format(&mut self, format: ContentFormat) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::CONTENT_FORMAT, - format.into_iter().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::CONTENT_FORMAT, + format.into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Content-Format](opt::known::no_repeat::CONTENT_FORMAT) option @@ -620,55 +565,45 @@ pub trait MessageOptions { /// assert_eq!(msg.content_format(), Some(Json)); /// ``` fn content_format(&self) -> Option { - self - .get_u16(opt::known::no_repeat::CONTENT_FORMAT) - .map(ContentFormat::from) + self.get_u16(opt::known::no_repeat::CONTENT_FORMAT) + .map(ContentFormat::from) } /// Set the value for the [Observe](opt::known::no_repeat::OBSERVE) option, /// discarding any existing values. fn set_observe(&mut self, a: observe::Action) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::OBSERVE, - core::iter::once(u8::from(a)).collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::OBSERVE, + core::iter::once(u8::from(a)).collect()) + .map(|_| ()) } /// Get the value for the [Observe](opt::known::no_repeat::OBSERVE) option fn observe(&self) -> Option { - self - .get_u8(opt::known::no_repeat::OBSERVE) - .and_then(observe::Action::from_byte) + self.get_u8(opt::known::no_repeat::OBSERVE) + .and_then(observe::Action::from_byte) } /// Update the value for the [Accept](opt::known::no_repeat::ACCEPT) option, /// discarding any existing values. #[doc = rfc_7252_doc!("5.10.4")] fn set_accept(&mut self, format: ContentFormat) -> Result<(), Self::SetError> { - self - .set(opt::known::no_repeat::ACCEPT, format.into_iter().collect()) - .map(|_| ()) + self.set(opt::known::no_repeat::ACCEPT, format.into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Accept](opt::known::no_repeat::ACCEPT) option fn accept(&self) -> Option { - self - .get_u16(opt::known::no_repeat::ACCEPT) - .map(ContentFormat::from) + self.get_u16(opt::known::no_repeat::ACCEPT) + .map(ContentFormat::from) } /// Update the value for the [Size1](opt::known::no_repeat::SIZE1) option, /// discarding any existing values. #[doc = rfc_7252_doc!("5.10.9")] fn set_size1(&mut self, size_bytes: u64) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::SIZE1, - size_bytes.to_be_bytes().into_iter().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::SIZE1, + size_bytes.to_be_bytes().into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Size1](opt::known::no_repeat::SIZE1) option @@ -679,12 +614,9 @@ pub trait MessageOptions { /// Update the value for the [Size2](opt::known::no_repeat::SIZE2) option, /// discarding any existing values. fn set_size2(&mut self, size_bytes: u64) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::SIZE2, - size_bytes.to_be_bytes().into_iter().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::SIZE2, + size_bytes.to_be_bytes().into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Size2](opt::known::no_repeat::SIZE2) option @@ -699,17 +631,15 @@ pub trait MessageOptions { /// a resource that exists (e.g. this ensures PUT only updates and will never insert) #[doc = rfc_7252_doc!("5.10.8.1")] fn set_if_exists(&mut self) -> Result<(), Self::SetError> { - self - .set(opt::known::repeat::IF_MATCH, Default::default()) - .map(|_| ()) + self.set(opt::known::repeat::IF_MATCH, Default::default()) + .map(|_| ()) } /// Get whether or not [`Message::set_if_exists`] applies fn if_exists_flag_enabled(&self) -> bool { - self - .get(opt::known::repeat::IF_MATCH) - .map(|vs| vs.iter().any(|v| v.0.len() == 0)) - .unwrap_or(false) + self.get(opt::known::repeat::IF_MATCH) + .map(|vs| vs.iter().any(|v| v.0.len() == 0)) + .unwrap_or(false) } /// Enable the [If-None-Match](opt::known::no_repeat::IF_NONE_MATCH) flag @@ -718,29 +648,24 @@ pub trait MessageOptions { /// a resource that does not exist (e.g. this ensures PUT only inserts and will never update) #[doc = rfc_7252_doc!("5.10.8.2")] fn set_if_not_exists(&mut self) -> Result<(), Self::SetError> { - self - .set(opt::known::no_repeat::IF_NONE_MATCH, Default::default()) - .map(|_| ()) + self.set(opt::known::no_repeat::IF_NONE_MATCH, Default::default()) + .map(|_| ()) } /// Get whether or not [`Message::set_if_not_exists`] applies fn if_not_exists_flag_enabled(&self) -> bool { - self - .get_first(opt::known::no_repeat::IF_NONE_MATCH) - .map(|_| true) - .unwrap_or(false) + self.get_first(opt::known::no_repeat::IF_NONE_MATCH) + .map(|_| true) + .unwrap_or(false) } /// Update the value for the [Max-Age](opt::known::no_repeat::MAX_AGE) option, /// discarding any existing values. #[doc = rfc_7252_doc!("5.10.5")] fn set_max_age(&mut self, max_age_seconds: u32) -> Result<(), Self::SetError> { - self - .set( - opt::known::no_repeat::MAX_AGE, - max_age_seconds.to_be_bytes().into_iter().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::MAX_AGE, + max_age_seconds.to_be_bytes().into_iter().collect()) + .map(|_| ()) } /// Get the value for the [Max-Age](opt::known::no_repeat::MAX_AGE) option, in seconds @@ -752,15 +677,11 @@ pub trait MessageOptions { /// discarding any existing values. #[doc = rfc_7252_doc!("5.10.2")] fn set_proxy_uri(&mut self, uri: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self - .set( - opt::known::no_repeat::PROXY_URI, - uri.as_ref().as_bytes().iter().copied().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::PROXY_URI, + uri.as_ref().as_bytes().iter().copied().collect()) + .map(|_| ()) } /// Get the value for the [Proxy-Uri](opt::known::no_repeat::PROXY_URI) option @@ -771,15 +692,11 @@ pub trait MessageOptions { /// Update the value for the [Proxy-Scheme](opt::known::no_repeat::PROXY_SCHEME) option, /// discarding any existing values. fn set_proxy_scheme(&mut self, scheme: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self - .set( - opt::known::no_repeat::PROXY_SCHEME, - scheme.as_ref().as_bytes().iter().copied().collect(), - ) - .map(|_| ()) + self.set(opt::known::no_repeat::PROXY_SCHEME, + scheme.as_ref().as_bytes().iter().copied().collect()) + .map(|_| ()) } /// Get the value for the [Proxy-Scheme](opt::known::no_repeat::PROXY_SCHEME) option @@ -791,21 +708,17 @@ pub trait MessageOptions { /// alongside any existing values. #[doc = rfc_7252_doc!("5.10.8.1")] fn add_if_match(&mut self, tag: B) -> Result<(), Self::SetError> - where - B: AsRef<[u8]>, + where B: AsRef<[u8]> { if let Some(others) = self.remove(opt::known::repeat::IF_MATCH) { - others - .into_iter() - .filter(|v| v.0.len() > 0) - .map(|v| self.add(opt::known::repeat::IF_MATCH, v)) - .collect::>()?; + others.into_iter() + .filter(|v| v.0.len() > 0) + .map(|v| self.add(opt::known::repeat::IF_MATCH, v)) + .collect::>()?; } - self.add( - opt::known::repeat::IF_MATCH, - tag.as_ref().iter().copied().collect(), - ) + self.add(opt::known::repeat::IF_MATCH, + tag.as_ref().iter().copied().collect()) } /// Get all values for the [If-Match](opt::known::repeat::IF_MATCH) option @@ -817,19 +730,15 @@ pub trait MessageOptions { /// alongside any existing values. #[doc = rfc_7252_doc!("5.10.7")] fn add_location_path(&mut self, path: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self.add( - opt::known::repeat::LOCATION_PATH, - path.as_ref().as_bytes().iter().copied().collect(), - ) + self.add(opt::known::repeat::LOCATION_PATH, + path.as_ref().as_bytes().iter().copied().collect()) } /// Get all values for the [Location-Path](opt::known::repeat::LOCATION_PATH) option fn location_path<'a, F>(&'a self) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { self.get_strs(opt::known::repeat::LOCATION_PATH) } @@ -838,19 +747,15 @@ pub trait MessageOptions { /// alongside any existing values. #[doc = rfc_7252_doc!("5.10.7")] fn add_location_query(&mut self, query: S) -> Result<(), Self::SetError> - where - S: AsRef, + where S: AsRef { - self.add( - opt::known::repeat::LOCATION_QUERY, - query.as_ref().as_bytes().iter().copied().collect(), - ) + self.add(opt::known::repeat::LOCATION_QUERY, + query.as_ref().as_bytes().iter().copied().collect()) } /// Get all values for the [Location-Query](opt::known::repeat::LOCATION_QUERY) option fn location_query<'a, F>(&'a self) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { self.get_strs(opt::known::repeat::LOCATION_QUERY) } @@ -859,13 +764,10 @@ pub trait MessageOptions { /// alongside any existing values. #[doc = rfc_7252_doc!("5.10.7")] fn add_etag(&mut self, tag: B) -> Result<(), Self::SetError> - where - B: AsRef<[u8]>, + where B: AsRef<[u8]> { - self.add( - opt::known::repeat::ETAG, - tag.as_ref().iter().copied().collect(), - ) + self.add(opt::known::repeat::ETAG, + tag.as_ref().iter().copied().collect()) } /// Get all values for the [ETag](opt::known::repeat::ETAG) option @@ -879,15 +781,13 @@ impl + AppendCopy, Options: OptionMap> { /// Create a new message pub fn new(ty: Type, code: Code, id: Id, token: Token) -> Self { - Self { - id, - token, - ty, - code, - ver: Version::default(), - payload: Payload(PayloadBytes::default()), - opts: Options::default(), - } + Self { id, + token, + ty, + code, + ver: Version::default(), + payload: Payload(PayloadBytes::default()), + opts: Options::default() } } /// Using [`DefaultCacheKey`], get the cache key for @@ -953,22 +853,19 @@ impl + AppendCopy, Options: OptionMap> /// server_send_msg(addr, ack).unwrap(); /// ``` pub fn ack(&self, id: Id) -> Self { - Self { - id, - token: self.token, - ver: Default::default(), - ty: Type::Ack, - code: Code::new(0, 0), - payload: Payload(Default::default()), - opts: Default::default(), - } - } - - fn add( - &mut self, - n: OptNumber, - v: OptValue, - ) -> Result<(), SetOptionError, Options::OptValues>> { + Self { id, + token: self.token, + ver: Default::default(), + ty: Type::Ack, + code: Code::new(0, 0), + payload: Payload(Default::default()), + opts: Default::default() } + } + + fn add(&mut self, + n: OptNumber, + v: OptValue) + -> Result<(), SetOptionError, Options::OptValues>> { match (self.remove(n).unwrap_or_default(), &mut self.opts) { | (vals, _) if vals.is_full() => Err(SetOptionError::RepeatedTooManyTimes(v)), | (vals, opts) if opts.is_full() => Err(SetOptionError::TooManyOptions(n, vals)), @@ -983,11 +880,9 @@ impl + AppendCopy, Options: OptionMap> fn set( &mut self, n: OptNumber, - v: OptValue, - ) -> Result< - Option, - SetOptionError, Options::OptValues>, - > { + v: OptValue) + -> Result, + SetOptionError, Options::OptValues>> { Ok(self.remove(n)).and_then(|old| self.add(n, v).map(|_| old)) } @@ -1011,8 +906,7 @@ impl + AppendCopy, Options: OptionMap> } fn get_strs<'a, F>(&'a self, n: OptNumber) -> Result - where - F: FromIterator<&'a str>, + where F: FromIterator<&'a str> { match self.get(n) { | Some(vs) if vs.len() >= 1 => vs.iter().map(|s| from_utf8(&s.0)).collect(), @@ -1021,36 +915,30 @@ impl + AppendCopy, Options: OptionMap> } fn get_u8(&self, n: OptNumber) -> Option { - self - .get_first(n) - .filter(|bytes| bytes.0.len() == 1) - .map(|bytes| bytes.0[0]) + self.get_first(n) + .filter(|bytes| bytes.0.len() == 1) + .map(|bytes| bytes.0[0]) } fn get_u16(&self, n: OptNumber) -> Option { - self - .get_first(n) - .filter(|bytes| bytes.0.len() == 2) - .map(|bytes| u16::from_be_bytes([bytes.0[0], bytes.0[1]])) + self.get_first(n) + .filter(|bytes| bytes.0.len() == 2) + .map(|bytes| u16::from_be_bytes([bytes.0[0], bytes.0[1]])) } fn get_u32(&self, n: OptNumber) -> Option { - self - .get_first(n) - .filter(|bytes| bytes.0.len() == 4) - .map(|bytes| u32::from_be_bytes([bytes.0[0], bytes.0[1], bytes.0[2], bytes.0[3]])) + self.get_first(n) + .filter(|bytes| bytes.0.len() == 4) + .map(|bytes| u32::from_be_bytes([bytes.0[0], bytes.0[1], bytes.0[2], bytes.0[3]])) } fn get_u64(&self, n: OptNumber) -> Option { - self - .get_first(n) - .filter(|bytes| bytes.0.len() == 8) - .map(|bytes| { - u64::from_be_bytes([ - bytes.0[0], bytes.0[1], bytes.0[2], bytes.0[3], bytes.0[4], bytes.0[5], bytes.0[6], - bytes.0[7], - ]) - }) + self.get_first(n) + .filter(|bytes| bytes.0.len() == 8) + .map(|bytes| { + u64::from_be_bytes([bytes.0[0], bytes.0[1], bytes.0[2], bytes.0[3], bytes.0[4], + bytes.0[5], bytes.0[6], bytes.0[7]]) + }) } fn remove(&mut self, n: OptNumber) -> Option { @@ -1066,10 +954,9 @@ impl, PayloadBytes: Array + AppendCopy, Option fn try_from_bytes(bytes: Bytes) -> Result { let mut bytes = Cursor::new(bytes); - let Byte1 { tkl, ty, ver } = bytes - .next() - .ok_or_else(MessageParseError::eof)? - .try_into()?; + let Byte1 { tkl, ty, ver } = bytes.next() + .ok_or_else(MessageParseError::eof)? + .try_into()?; if tkl > 8 { return Err(Self::Error::InvalidTokenLength(tkl)); @@ -1078,9 +965,8 @@ impl, PayloadBytes: Array + AppendCopy, Option let code: Code = bytes.next().ok_or_else(MessageParseError::eof)?.into(); let id: Id = Id::try_consume_bytes(&mut bytes)?; - let token = bytes - .take_exact(tkl as usize) - .ok_or_else(MessageParseError::eof)?; + let token = bytes.take_exact(tkl as usize) + .ok_or_else(MessageParseError::eof)?; let token = tinyvec::ArrayVec::<[u8; 8]>::try_from(token).expect("tkl was checked to be <= 8"); let token = Token(token); @@ -1090,15 +976,13 @@ impl, PayloadBytes: Array + AppendCopy, Option payload.append_copy(bytes.take_until_end()); let payload = Payload(payload); - Ok(Message { - id, - ty, - ver, - code, - token, - opts, - payload, - }) + Ok(Message { id, + ty, + ver, + code, + token, + opts, + payload }) } } @@ -1117,14 +1001,10 @@ mod tests { fn parse_byte1() { let byte = 0b_01_10_0011u8; let byte = Byte1::try_from(byte).unwrap(); - assert_eq!( - byte, - Byte1 { - ver: Version(1), - ty: Type::Ack, - tkl: 3 - } - ) + assert_eq!(byte, + Byte1 { ver: Version(1), + ty: Type::Ack, + tkl: 3 }) } #[test] diff --git a/toad-msg/src/msg/opt/known/mod.rs b/toad-msg/src/msg/opt/known/mod.rs index fd26bc35..1c407701 100644 --- a/toad-msg/src/msg/opt/known/mod.rs +++ b/toad-msg/src/msg/opt/known/mod.rs @@ -31,38 +31,24 @@ pub mod no_repeat { opt!(rfc7252("5.10.1") HOST = 3); opt!(rfc7252("5.10.8.2") IF_NONE_MATCH = 5); - opt!( - #[doc = ""] - OBSERVE = 6 - ); - opt!( - #[doc = "See [`HOST`]"] - PORT = 7 - ); + opt!(#[doc = ""] + OBSERVE = 6); + opt!(#[doc = "See [`HOST`]"] + PORT = 7); opt!(rfc7252("5.10.3") CONTENT_FORMAT = 12); opt!(rfc7252("5.10.5") MAX_AGE = 14); opt!(rfc7252("5.10.4") ACCEPT = 17); - opt!( - #[doc = include_str!("../../../../docs/Block2.md")] - BLOCK2 = 23 - ); - opt!( - #[doc = include_str!("../../../../docs/Block1.md")] - BLOCK1 = 27 - ); - opt!( - #[doc = concat!(toad_macros::rfc_7252_doc!("5.10.9"), include_str!("../../../../docs/Size.md"))] - SIZE2 = 28 - ); + opt!(#[doc = include_str!("../../../../docs/Block2.md")] + BLOCK2 = 23); + opt!(#[doc = include_str!("../../../../docs/Block1.md")] + BLOCK1 = 27); + opt!(#[doc = concat!(toad_macros::rfc_7252_doc!("5.10.9"), include_str!("../../../../docs/Size.md"))] + SIZE2 = 28); opt!(rfc7252("5.10.2") PROXY_URI = 35); - opt!( - #[doc = "See [`PROXY_URI`]"] - PROXY_SCHEME = 39 - ); - opt!( - #[doc = concat!(toad_macros::rfc_7252_doc!("5.10.9"), include_str!("../../../../docs/Size.md"))] - SIZE1 = 60 - ); + opt!(#[doc = "See [`PROXY_URI`]"] + PROXY_SCHEME = 39); + opt!(#[doc = concat!(toad_macros::rfc_7252_doc!("5.10.9"), include_str!("../../../../docs/Size.md"))] + SIZE1 = 60); } /// Repeatable options @@ -71,20 +57,13 @@ pub mod repeat { opt!(rfc7252("5.10.8.1") IF_MATCH = 1); opt!(rfc7252("5.10.7") LOCATION_PATH = 8); - opt!( - #[doc = "See [`super::no_repeat::HOST`]"] - PATH = 11 - ); - opt!( - #[doc = "See [`super::no_repeat::HOST`]"] - QUERY = 15 - ); - opt!( - #[doc = "See [`LOCATION_PATH`]"] - LOCATION_QUERY = 20 - ); - opt!( - #[doc = concat!( + opt!(#[doc = "See [`super::no_repeat::HOST`]"] + PATH = 11); + opt!(#[doc = "See [`super::no_repeat::HOST`]"] + QUERY = 15); + opt!(#[doc = "See [`LOCATION_PATH`]"] + LOCATION_QUERY = 20); + opt!(#[doc = concat!( toad_macros::rfc_7252_doc!("5.10.6"), "\n
ETag as a Request Option\n\n", toad_macros::rfc_7252_doc!("5.10.6.2"), @@ -92,6 +71,5 @@ pub mod repeat { toad_macros::rfc_7252_doc!("5.10.6.1"), "
" )] - ETAG = 4 - ); + ETAG = 4); } diff --git a/toad-msg/src/msg/opt/mod.rs b/toad-msg/src/msg/opt/mod.rs index 44f0bced..be981746 100644 --- a/toad-msg/src/msg/opt/mod.rs +++ b/toad-msg/src/msg/opt/mod.rs @@ -27,8 +27,7 @@ use self::no_repeat::{BLOCK1, BLOCK2}; /// An iterator over owned [`Opt`]s #[derive(Debug, Clone)] pub struct OptIter -where - M: OptionMap, + where M: OptionMap { iter: I, last_seen_num: OptNumber, @@ -39,8 +38,7 @@ where /// An iterator over [`OptRef`]s #[derive(Debug, Clone)] pub struct OptRefIter<'a, M, I> -where - M: OptionMap, + where M: OptionMap { iter: I, last_seen_num: OptNumber, @@ -49,9 +47,8 @@ where } impl Iterator for OptIter -where - I: Iterator, - M: OptionMap, + where I: Iterator, + M: OptionMap { type Item = Opt; @@ -64,10 +61,8 @@ where let delta = OptDelta(delta as u16); self.last_seen_num = num; - Some(Opt { - value: values.into_iter().next().unwrap(), - delta, - }) + Some(Opt { value: values.into_iter().next().unwrap(), + delta }) }, | _ => { let mut values = values.into_iter(); @@ -89,17 +84,15 @@ where } impl<'a, M, I> Iterator for OptRefIter<'a, M, I> -where - I: Iterator, - Self: 'a, - M: 'a + OptionMap, + where I: Iterator, + Self: 'a, + M: 'a + OptionMap { type Item = OptRef<'a, M::OptValue>; fn next(&mut self) -> Option { - let (num, values, ix) = self - .repeated - .or_else(|| self.iter.next().map(|(a, b)| (*a, b, 0)))?; + let (num, values, ix) = self.repeated + .or_else(|| self.iter.next().map(|(a, b)| (*a, b, 0)))?; match values.len() { | 1 => { @@ -107,10 +100,8 @@ where let delta = OptDelta(delta as u16); self.last_seen_num = num; - Some(OptRef { - value: &values[0], - delta, - }) + Some(OptRef { value: &values[0], + delta }) }, | _ => { if let Some(value) = values.get(ix) { @@ -132,8 +123,7 @@ where /// Generalization of `HashMap>>` pub trait OptionMap -where - Self: Map, + where Self: Map { /// Byte array for option values type OptValue: Array + AppendCopy; @@ -145,22 +135,18 @@ where /// Iterate over the map, yielding raw option structures fn opts(self) -> OptIter { - OptIter { - iter: self.into_iter(), - last_seen_num: OptNumber(0), - __p: PhantomData, - repeated: None, - } + OptIter { iter: self.into_iter(), + last_seen_num: OptNumber(0), + __p: PhantomData, + repeated: None } } /// Iterate over the map, yielding raw option structures fn opt_refs(&self) -> OptRefIter<'_, Self, toad_map::Iter<'_, OptNumber, Self::OptValues>> { - OptRefIter { - iter: self.iter(), - last_seen_num: OptNumber(0), - __p: PhantomData, - repeated: None, - } + OptRefIter { iter: self.iter(), + last_seen_num: OptNumber(0), + __p: PhantomData, + repeated: None } } } @@ -174,11 +160,9 @@ type ArrayVecMap = ArrayVec<[(K, V); N]>; impl OptionMap - for ArrayVecMap< - MAX_OPTS, - OptNumber, - ArrayVec<[OptValue>; MAX_INSTANCES]>, - > + for ArrayVecMap>; MAX_INSTANCES]>> { type OptValue = ArrayVec<[u8; MAX_BYTES_PER_INSTANCE]>; type OptValues = ArrayVec<[OptValue; MAX_INSTANCES]>; @@ -215,11 +199,10 @@ impl, M: OptionMap> TryConsumeBytes for M { } } -pub(crate) fn parse_opt_len_or_delta>( - head: u8, - bytes: &mut Cursor
, - reserved_err: OptParseError, -) -> Result { +pub(crate) fn parse_opt_len_or_delta>(head: u8, + bytes: &mut Cursor, + reserved_err: OptParseError) + -> Result { match head { | 13 => { let n = bytes.next().ok_or_else(OptParseError::eof)?; @@ -253,33 +236,26 @@ pub struct Opt { pub value: OptValue, } -impl PartialOrd for Opt -where - C: Array, +impl PartialOrd for Opt where C: Array { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl PartialEq for Opt -where - C: Array, +impl PartialEq for Opt where C: Array { fn eq(&self, other: &Self) -> bool { self.delta.eq(&other.delta) && self.value.eq(&other.value) } } -impl Ord for Opt -where - C: Array, +impl Ord for Opt where C: Array { fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self - .delta - .cmp(&other.delta) - .then_with(|| self.value.cmp(&other.value)) + self.delta + .cmp(&other.delta) + .then_with(|| self.value.cmp(&other.value)) } } @@ -293,33 +269,26 @@ pub struct OptRef<'a, C> { pub value: &'a OptValue, } -impl<'a, C> PartialOrd for OptRef<'a, C> -where - C: Array, +impl<'a, C> PartialOrd for OptRef<'a, C> where C: Array { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl<'a, C> PartialEq for OptRef<'a, C> -where - C: Array, +impl<'a, C> PartialEq for OptRef<'a, C> where C: Array { fn eq(&self, other: &Self) -> bool { self.delta.eq(&other.delta) && self.value.eq(other.value) } } -impl<'a, C> Ord for OptRef<'a, C> -where - C: Array, +impl<'a, C> Ord for OptRef<'a, C> where C: Array { fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self - .delta - .cmp(&other.delta) - .then_with(|| self.value.cmp(other.value)) + self.delta + .cmp(&other.delta) + .then_with(|| self.value.cmp(other.value)) } } @@ -352,10 +321,8 @@ impl<'a, C: Array> Len for OptRef<'a, C> { impl<'a, V> From<&'a Opt> for OptRef<'a, V> { fn from(o: &'a Opt) -> Self { - Self { - value: &o.value, - delta: o.delta, - } + Self { value: &o.value, + delta: o.delta } } } @@ -508,8 +475,8 @@ impl OptNumber { /// Whether this option should be included in the [`Message::cache_key`] pub fn include_in_cache_key(&self) -> bool { self.when_option_changes() == WhenOptionChanges::ResponseChanges - && self != &BLOCK1 - && self != &BLOCK2 + && self != &BLOCK1 + && self != &BLOCK2 } } @@ -517,27 +484,21 @@ impl OptNumber { #[derive(Default, Clone, Debug)] pub struct OptValue(pub C); -impl PartialOrd for OptValue -where - C: Array, +impl PartialOrd for OptValue where C: Array { fn partial_cmp(&self, other: &Self) -> Option { self.0.iter().partial_cmp(other.0.iter()) } } -impl PartialEq for OptValue -where - C: Array, +impl PartialEq for OptValue where C: Array { fn eq(&self, other: &Self) -> bool { self.0.iter().eq(other.0.iter()) } } -impl Ord for OptValue -where - C: Array, +impl Ord for OptValue where C: Array { fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.0.iter().cmp(other.0.iter()) @@ -546,18 +507,14 @@ where impl Eq for OptValue where C: Array {} -impl Hash for OptValue -where - C: Array, +impl Hash for OptValue where C: Array { fn hash(&self, state: &mut H) { state.write(&self.0) } } -impl OptValue -where - C: Array, +impl OptValue where C: Array { /// Convert a reference to a OptValue to a byte slice pub fn as_bytes(&self) -> &[u8] { @@ -565,9 +522,7 @@ where } } -impl FromIterator for OptValue -where - C: FromIterator, +impl FromIterator for OptValue where C: FromIterator { fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect::()) @@ -578,30 +533,26 @@ impl, V: Array + AppendCopy> TryConsumeBytes) -> Result { - let byte1 = bytes - .next() - .ok_or(OptParseError::OptionsExhausted) - .and_then(|b| { - if b == 0b11111111 { - Err(OptParseError::OptionsExhausted) - } else { - Ok(b) - } - })?; + let byte1 = bytes.next() + .ok_or(OptParseError::OptionsExhausted) + .and_then(|b| { + if b == 0b11111111 { + Err(OptParseError::OptionsExhausted) + } else { + Ok(b) + } + })?; // NOTE: Delta **MUST** be consumed before Value. see comment on `opt_len_or_delta` for more info - let delta = parse_opt_len_or_delta( - byte1 >> 4, - bytes, - OptParseError::OptionDeltaReservedValue(15), - )?; + let delta = parse_opt_len_or_delta(byte1 >> 4, + bytes, + OptParseError::OptionDeltaReservedValue(15))?; let delta = OptDelta(delta); - let len = parse_opt_len_or_delta( - byte1 & 0b00001111, - bytes, - OptParseError::ValueLengthReservedValue(15), - )? as usize; + let len = parse_opt_len_or_delta(byte1 & 0b00001111, + bytes, + OptParseError::ValueLengthReservedValue(15))? + as usize; let mut value = V::reserve(len); value.append_copy(bytes.take(len)); @@ -626,54 +577,34 @@ mod tests { fn parse_opt() { let mut opt_bytes = Cursor::new([0b00010001, 0b00000001]); let opt = Opt::try_consume_bytes(&mut opt_bytes).unwrap(); - assert_eq!( - opt, - Opt { - delta: OptDelta(1), - value: OptValue(vec![1]) - } - ); + assert_eq!(opt, + Opt { delta: OptDelta(1), + value: OptValue(vec![1]) }); let mut opt_bytes = Cursor::new([0b11010001, 0b00000001, 0b00000001]); let opt = Opt::try_consume_bytes(&mut opt_bytes).unwrap(); - assert_eq!( - opt, - Opt { - delta: OptDelta(14), - value: OptValue(vec![1]) - } - ); + assert_eq!(opt, + Opt { delta: OptDelta(14), + value: OptValue(vec![1]) }); let mut opt_bytes = Cursor::new([0b11100001, 0b00000000, 0b00000001, 0b00000001]); let opt = Opt::try_consume_bytes(&mut opt_bytes).unwrap(); - assert_eq!( - opt, - Opt { - delta: OptDelta(270), - value: OptValue(vec![1]) - } - ); + assert_eq!(opt, + Opt { delta: OptDelta(270), + value: OptValue(vec![1]) }); let mut opt_bytes = Cursor::new([0b00000001, 0b00000001]); let opt = Opt::try_consume_bytes(&mut opt_bytes).unwrap(); - assert_eq!( - opt, - Opt { - delta: OptDelta(0), - value: OptValue(vec![1]) - } - ); + assert_eq!(opt, + Opt { delta: OptDelta(0), + value: OptValue(vec![1]) }); let mut opt_bytes = Cursor::new([0b00000001, 0b00000001, 0b00010001, 0b00000011, 0b11111111]); let opt = BTreeMap::>>>::try_consume_bytes(&mut opt_bytes).unwrap(); - assert_eq!( - opt, - BTreeMap::from([ - (OptNumber(0), vec![OptValue(vec![1])]), - (OptNumber(1), vec![OptValue(vec![3])]) - ]) - ); + assert_eq!(opt, + BTreeMap::from([(OptNumber(0), vec![OptValue(vec![1])]), + (OptNumber(1), vec![OptValue(vec![3])])])); } #[test] @@ -690,40 +621,33 @@ mod tests { // elective, safe-to-fwd, no-cache-key let size1 = OptNumber(60); - [&if_match, &uri_host].into_iter().for_each(|num| { - assert_eq!(num.must_be_processed(), OptionMustBeProcessed::Yes); - }); + [&if_match, &uri_host].into_iter() + .for_each(|num| { + assert_eq!(num.must_be_processed(), OptionMustBeProcessed::Yes); + }); [&etag, &size1].into_iter().for_each(|num| { - assert_eq!(num.must_be_processed(), OptionMustBeProcessed::No); - }); + assert_eq!(num.must_be_processed(), OptionMustBeProcessed::No); + }); [&if_match, &etag, &size1].into_iter().for_each(|num| { - assert_eq!( - num.when_unsupported_by_proxy(), - WhenOptionUnsupportedByProxy::Forward - ); - }); + assert_eq!(num.when_unsupported_by_proxy(), + WhenOptionUnsupportedByProxy::Forward); + }); [&uri_host].into_iter().for_each(|num| { - assert_eq!( - num.when_unsupported_by_proxy(), - WhenOptionUnsupportedByProxy::Error - ); - }); + assert_eq!(num.when_unsupported_by_proxy(), + WhenOptionUnsupportedByProxy::Error); + }); [&if_match, &uri_host, &etag].into_iter().for_each(|num| { - assert_eq!( - num.when_option_changes(), - WhenOptionChanges::ResponseChanges - ); - }); + assert_eq!(num.when_option_changes(), + WhenOptionChanges::ResponseChanges); + }); [&size1].into_iter().for_each(|num| { - assert_eq!( - num.when_option_changes(), - WhenOptionChanges::ResponseDoesNotChange - ); - }); + assert_eq!(num.when_option_changes(), + WhenOptionChanges::ResponseDoesNotChange); + }); } } diff --git a/toad-msg/src/to_bytes.rs b/toad-msg/src/to_bytes.rs index b5740b0c..86f728cb 100644 --- a/toad-msg/src/to_bytes.rs +++ b/toad-msg/src/to_bytes.rs @@ -65,19 +65,14 @@ impl, Options: OptionMap> TryIntoBytes if let Some(max) = C::CAPACITY { if max < size { - return Err(Self::Error::TooLong { - capacity: max, - size, - }); + return Err(Self::Error::TooLong { capacity: max, + size }); } } - let byte1: u8 = Byte1 { - tkl: self.token.0.len() as u8, - ver: self.ver, - ty: self.ty, - } - .into(); + let byte1: u8 = Byte1 { tkl: self.token.0.len() as u8, + ver: self.ver, + ty: self.ty }.into(); let code: u8 = self.code.into(); let id: [u8; 2] = self.id.into(); let token: ArrayVec<[u8; 8]> = self.token.0; @@ -160,17 +155,13 @@ mod tests { macro_rules! assert_eqb_iter { ($actual:expr, $expected:expr) => { if $actual.iter().ne($expected.iter()) { - panic!( - "expected {:?} to equal {:?}", - $actual - .into_iter() - .map(|b| format!("{:08b}", b)) - .collect::>(), - $expected - .into_iter() - .map(|b| format!("{:08b}", b)) - .collect::>() - ) + panic!("expected {:?} to equal {:?}", + $actual.into_iter() + .map(|b| format!("{:08b}", b)) + .collect::>(), + $expected.into_iter() + .map(|b| format!("{:08b}", b)) + .collect::>()) } }; } @@ -184,11 +175,9 @@ mod tests { #[test] fn byte_1() { - let byte = Byte1 { - ver: Version(1), - ty: Type::Ack, - tkl: 3, - }; + let byte = Byte1 { ver: Version(1), + ty: Type::Ack, + tkl: 3 }; let actual: u8 = byte.into(); let expected = 0b_01_10_0011u8; assert_eqb!(actual, expected) @@ -196,10 +185,8 @@ mod tests { #[test] fn code() { - let code = Code { - class: 2, - detail: 5, - }; + let code = Code { class: 2, + detail: 5 }; let actual: u8 = code.into(); let expected = 0b0100_0101_u8; assert_eqb!(actual, expected) @@ -215,59 +202,40 @@ mod tests { #[test] fn opt() { use core::iter::repeat; - let cases: [(u16, Vec, Vec); 4] = [ - ( - 24, + let cases: [(u16, Vec, Vec); 4] = + [(24, repeat(1).take(100).collect(), - [ - [0b1101_1101u8, 24 - 13, 100 - 13].as_ref(), - repeat(1).take(100).collect::>().as_ref(), - ] - .concat(), - ), - (1, vec![1], vec![0b0001_0001, 1]), - (24, vec![1], vec![0b1101_0001, 11, 1]), - ( - 24, + [[0b1101_1101u8, 24 - 13, 100 - 13].as_ref(), + repeat(1).take(100).collect::>().as_ref()].concat()), + (1, vec![1], vec![0b0001_0001, 1]), + (24, vec![1], vec![0b1101_0001, 11, 1]), + (24, repeat(1).take(300).collect(), - [ - [0b1101_1110, 24 - 13].as_ref(), - (300u16 - 269).to_be_bytes().as_ref(), - repeat(1).take(300).collect::>().as_ref(), - ] - .concat(), - ), - ]; + [[0b1101_1110, 24 - 13].as_ref(), + (300u16 - 269).to_be_bytes().as_ref(), + repeat(1).take(300).collect::>().as_ref()].concat())]; cases.into_iter().for_each(|(delta, values, expected)| { - let opt = Opt::> { - delta: OptDelta(delta), - value: OptValue(values.into_iter().collect()), - }; - let mut actual = Vec::::new(); - opt.extend_bytes(&mut actual); - assert_eqb_iter!(actual, expected) - }); + let opt = Opt::> { delta: OptDelta(delta), + value: OptValue(values.into_iter().collect()) }; + let mut actual = Vec::::new(); + opt.extend_bytes(&mut actual); + assert_eqb_iter!(actual, expected) + }); } #[test] fn no_payload_marker() { - let msg = alloc::Message { - id: Id(0), - ty: Type::Con, - ver: Default::default(), - code: Code { - class: 2, - detail: 5, - }, - token: Token(Default::default()), - opts: Default::default(), - payload: Payload(Default::default()), - }; - - assert_ne!( - msg.try_into_bytes::>().unwrap().last(), - Some(&0b11111111) - ); + let msg = alloc::Message { id: Id(0), + ty: Type::Con, + ver: Default::default(), + code: Code { class: 2, + detail: 5 }, + token: Token(Default::default()), + opts: Default::default(), + payload: Payload(Default::default()) }; + + assert_ne!(msg.try_into_bytes::>().unwrap().last(), + Some(&0b11111111)); } } diff --git a/toad-stem/Cargo.toml b/toad-stem/Cargo.toml index 34f2347c..90e9cc12 100644 --- a/toad-stem/Cargo.toml +++ b/toad-stem/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-stem" version = "0.1.0" edition = "2021" +rust-version = "1.70" description = "This microcrate provides a mutable memory wrapper that is thread-safe and usable on `no_std` platforms." authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" diff --git a/toad-stem/src/lib.rs b/toad-stem/src/lib.rs index 576dfdbb..75685d1f 100644 --- a/toad-stem/src/lib.rs +++ b/toad-stem/src/lib.rs @@ -57,8 +57,7 @@ impl Stem { /// There can be any number of concurrent `map_ref` /// sections running at a given time. pub fn map_ref(&self, f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { self.0.map_ref(f) } @@ -67,8 +66,7 @@ impl Stem { /// /// This will block if called concurrently with `map_ref` or `map_mut`. pub fn map_mut(&self, f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { self.0.map_mut(f) } @@ -85,24 +83,21 @@ impl Stem { pub trait StemCellInternal { /// Create an instance of `Self` fn new(t: T) -> Self - where - Self: Sized; + where Self: Sized; /// Map a reference to `T` to a new type /// /// Implementors may choose to panic or block /// if `map_mut` called concurrently. fn map_ref(&self, f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R; + where F: for<'a> FnMut(&'a T) -> R; /// Map a mutable reference to `T` to a new type /// /// Implementors may choose to panic or block /// if `map_ref` or `map_mut` called concurrently. fn map_mut(&self, f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R; + where F: for<'a> FnMut(&'a mut T) -> R; } #[cfg(feature = "std")] @@ -112,15 +107,13 @@ impl StemCellInternal for std::sync::RwLock { } fn map_ref(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { f(self.read().unwrap().deref()) } fn map_mut(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { f(self.write().unwrap().deref_mut()) } @@ -132,15 +125,13 @@ impl StemCellInternal for core::cell::RefCell { } fn map_ref(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a T) -> R, + where F: for<'a> FnMut(&'a T) -> R { f(self.borrow().deref()) } fn map_mut(&self, mut f: F) -> R - where - F: for<'a> FnMut(&'a mut T) -> R, + where F: for<'a> FnMut(&'a mut T) -> R { f(self.borrow_mut().deref_mut()) } @@ -203,10 +194,10 @@ mod test { std::thread::spawn(|| { wait!(START); VEC.map_ref(|v| { - assert!(v.is_empty()); - wait!(READING); - wait!(READING_DONE); - }); + assert!(v.is_empty()); + wait!(READING); + wait!(READING_DONE); + }); wait!(MODIFY_DONE); }); diff --git a/toad-string/Cargo.toml b/toad-string/Cargo.toml index f812dbe9..8cc7ddf5 100644 --- a/toad-string/Cargo.toml +++ b/toad-string/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-string" version = "0.2.0" edition = "2021" +rust-version = "1.70" description = "Stack-allocated string" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -25,4 +26,4 @@ docs = [] toad-len = { version = "0.1.3", default_features = false } toad-array = { version = "0.2.3", default_features = false } toad-writable = { version = "0.1.1", default_features = false } -tinyvec = {version = "1.5", default_features = false, features = ["rustc_1_55"]} +tinyvec = {version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"]} diff --git a/toad-string/src/lib.rs b/toad-string/src/lib.rs index 889388df..51aedc46 100644 --- a/toad-string/src/lib.rs +++ b/toad-string/src/lib.rs @@ -82,9 +82,7 @@ impl String { pub fn resize(&mut self) -> String { let mut bytes = self.0.unwrap(); bytes.truncate(M); - String(Writable::from( - self.as_writable().drain(..).collect::>(), - )) + String(Writable::from(self.as_writable().drain(..).collect::>())) } /// Alias for [`AsRef`] @@ -283,9 +281,8 @@ impl String { pub fn push(&mut self, ch: char) { match ch.len_utf8() { | 1 => self.0.push(ch as u8), - | _ => self - .0 - .extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()), + | _ => self.0 + .extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()), } } diff --git a/toad-writable/Cargo.toml b/toad-writable/Cargo.toml index 26531d0c..e4af973d 100644 --- a/toad-writable/Cargo.toml +++ b/toad-writable/Cargo.toml @@ -2,6 +2,7 @@ name = "toad-writable" version = "0.1.1" edition = "2021" +rust-version = "1.70" description = "This microcrate provides a struct implementing [`core::fmt::Write`] for all [`toad_array::Array`]s" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" diff --git a/toad-writable/src/lib.rs b/toad-writable/src/lib.rs index 94a7f4bc..6d546118 100644 --- a/toad-writable/src/lib.rs +++ b/toad-writable/src/lib.rs @@ -68,9 +68,7 @@ impl> Writable { } } -impl Display for Writable -where - A: Array, +impl Display for Writable where A: Array { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.as_str()) diff --git a/toad/Cargo.toml b/toad/Cargo.toml index 5aa66315..a0ad3bf3 100644 --- a/toad/Cargo.toml +++ b/toad/Cargo.toml @@ -2,6 +2,7 @@ name = "toad" version = "0.19.1" edition = "2021" +rust-version = "1.70" description = "Universal implementation of the CoAP networking protocol" authors = ["Orion Kindel "] license = "MIT OR Apache-2.0" @@ -48,7 +49,7 @@ toad-string = {version = "0.2.0", default_features = false} toad-msg = "0.18.1" toad-macros = "0.2.0" log = "0.4" -tinyvec = { version = "1.5", default_features = false, features = ["rustc_1_55"] } +tinyvec = { version = "1.5", default_features = false, features = ["alloc", "rustc_1_55"] } no-std-net = "0.6" embedded-time = "0.12" nb = "1" @@ -62,8 +63,7 @@ serde_json = { version = "1.0", optional = true, default_features = false } serde-json-core = { version = "0.5.0", optional = true } [dev-dependencies] -simple_logger = "2" -lazycell = "1.3.0" +simple_logger = "5" paste = "1.0.9" serde = {version = "1.0", features = ["derive"]} serde-json-core = { version = "0.5.0" } diff --git a/toad/examples/server.rs b/toad/examples/server.rs index 813ef69d..4d1e696d 100644 --- a/toad/examples/server.rs +++ b/toad/examples/server.rs @@ -1,8 +1,7 @@ use std::io; -use std::sync::Barrier; +use std::sync::{Barrier, OnceLock}; use std::time::Duration; -use lazycell::AtomicLazyCell; use toad::config::Config; use toad::net::Addrd; use toad::platform::Platform as _; @@ -14,43 +13,40 @@ use toad::step::{runtime, Step}; fn start_server(addr: &'static str) { // 5 worker threads + main thread - static STARTED: AtomicLazyCell = AtomicLazyCell::NONE; - STARTED.fill(Barrier::new(6)).unwrap(); + static STARTED: OnceLock = OnceLock::new(); + STARTED.set(Barrier::new(6)).unwrap(); log::info!("[1] starting server"); std::thread::spawn(move || { - static SERVER: AtomicLazyCell

= AtomicLazyCell::NONE; - SERVER - .fill(P::try_new(addr, Config::default()).unwrap()) - .unwrap(); + static SERVER: OnceLock

= OnceLock::new(); + SERVER.set(P::try_new(addr, Config::default()).unwrap()) + .unwrap(); std::thread::spawn(|| loop { - SERVER.borrow().unwrap().notify("time").unwrap(); + SERVER.get().unwrap().notify("time").unwrap(); std::thread::sleep(Duration::from_millis(500)); }); for _ in 1..=5 { std::thread::spawn(|| { let init = Init(Some(|| { - STARTED.borrow().unwrap().wait(); - })); - - SERVER - .borrow() - .unwrap() - .run(init, |run| { - run - .maybe(route::done) - .maybe(route::hello) - .maybe(route::time) - .maybe(route::not_found) - }) - .unwrap(); + STARTED.get().unwrap().wait(); + })); + + SERVER.get() + .unwrap() + .run(init, |run| { + run.maybe(route::done) + .maybe(route::hello) + .maybe(route::time) + .maybe(route::not_found) + }) + .unwrap(); }); } }); - STARTED.borrow().unwrap().wait(); + STARTED.get().unwrap().wait(); } mod route { @@ -60,9 +56,8 @@ mod route { use super::*; - pub fn done( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn done(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { #![allow(unreachable_code)] ap.pipe(method::post) @@ -70,66 +65,54 @@ mod route { .bind(|_| Ap::respond(panic!("shutting down..."))) } - pub fn hello( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn hello(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { ap.pipe(method::get) .pipe(path::segment::check::next_equals("hello")) .pipe(path::segment::next(|_, name| { - name - .map(String::from) - .map(Ap::ok) - .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) - })) + name.map(String::from) + .map(Ap::ok) + .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) + })) .bind(|name| respond::ok(format!("Hello, {name}!").into())) } - pub fn time( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn time(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { ap.pipe(method::get) .pipe(path::segment::check::next_equals("time")) .bind_hydrated(|_, req| { let query = req.data().msg().query::>().unwrap(); - let (duration_unit, duration_unit_fn) = query - .into_iter() - .find(|q| q.starts_with("unit=")) - .map(|s| { - s.split('=') - .collect::>() - .get(1) - .map(|s| s.to_string()) - .unwrap_or_default() - }) - .and_then(|unit| match unit.as_str() { - | "millis" => Some(( - unit, - Box::new(|dur: Duration| dur.as_millis()) as Box u128>, - )), - | "seconds" => Some((unit, Box::new(|dur: Duration| dur.as_secs() as u128))), - | _ => None, - }) - .unwrap_or_else(|| { - ( - "millis".to_string(), - Box::new(|dur: Duration| dur.as_millis()), - ) - }); - respond::ok( - format!( - r#"{{ "you_are": {}, "unix_time": {}, "units": "{}" }}"#, - req.addr(), - duration_unit_fn(SystemTime::now().duration_since(UNIX_EPOCH).unwrap()), - duration_unit - ) - .into(), - ) + let (duration_unit, duration_unit_fn) = + query.into_iter() + .find(|q| q.starts_with("unit=")) + .map(|s| { + s.split('=') + .collect::>() + .get(1) + .map(|s| s.to_string()) + .unwrap_or_default() + }) + .and_then(|unit| match unit.as_str() { + | "millis" => Some((unit, + Box::new(|dur: Duration| dur.as_millis()) + as Box u128>)), + | "seconds" => Some((unit, Box::new(|dur: Duration| dur.as_secs() as u128))), + | _ => None, + }) + .unwrap_or_else(|| { + ("millis".to_string(), Box::new(|dur: Duration| dur.as_millis())) + }); + respond::ok(format!(r#"{{ "you_are": {}, "unix_time": {}, "units": "{}" }}"#, + req.addr(), + duration_unit_fn(SystemTime::now().duration_since(UNIX_EPOCH) + .unwrap()), + duration_unit).into()) }) } - pub fn not_found( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn not_found(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { ap.pipe(path::rest(|_, r| Ap::ok(r.to_string()))) .bind(|path| respond::not_found(format!("resource {path} not found").into())) } @@ -141,60 +124,46 @@ mod test { use super::*; pub fn not_found(client: &P, addr: &str) { - let (_, token) = client - .send_msg(Addrd( - Req::>::get("foobar").into(), - addr.parse().unwrap(), - )) - .unwrap(); + let (_, token) = client.send_msg(Addrd(Req::>::get("foobar").into(), + addr.parse().unwrap())) + .unwrap(); log::info!("[4] GET /foobar sent"); // UX: why do i have to nb::block? let resp = nb::block!(client.poll_resp(token, addr.parse().unwrap())).unwrap(); - assert_eq!( - resp.data().payload_string().unwrap(), - "resource foobar not found".to_string() - ); + assert_eq!(resp.data().payload_string().unwrap(), + "resource foobar not found".to_string()); log::info!("[5] got 'resource foobar not found'"); } pub fn hello(client: &P, addr: &str) { - let (_, token) = client - .send_msg(Addrd( - Req::>::get("hello/ethan").into(), - addr.parse().unwrap(), - )) - .unwrap(); + let (_, token) = client.send_msg(Addrd(Req::>::get("hello/ethan").into(), + addr.parse().unwrap())) + .unwrap(); log::info!("[2] GET /hello/ethan sent"); let resp = nb::block!(client.poll_resp(token, addr.parse().unwrap())).unwrap(); - assert_eq!( - resp.data().payload_string().unwrap(), - "Hello, ethan!".to_string() - ); + assert_eq!(resp.data().payload_string().unwrap(), + "Hello, ethan!".to_string()); log::info!("[3] got 'Hello, ethan!'"); } pub fn observe(client: &P, addr: &str, unit: &str) { let mut register = Req::>::get("time"); - register - .msg_mut() - .set_observe(toad_msg::opt::observe::Action::Register) - .unwrap(); - register - .msg_mut() - .add_query(format!("unit={unit}")) - .unwrap(); + register.msg_mut() + .set_observe(toad_msg::opt::observe::Action::Register) + .unwrap(); + register.msg_mut() + .add_query(format!("unit={unit}")) + .unwrap(); let mut deregister = Req::>::get("time"); - deregister - .msg_mut() - .set_observe(toad_msg::opt::observe::Action::Deregister) - .unwrap(); - - let (_, token) = client - .send_msg(Addrd(register.into(), addr.parse().unwrap())) - .unwrap(); + deregister.msg_mut() + .set_observe(toad_msg::opt::observe::Action::Deregister) + .unwrap(); + + let (_, token) = client.send_msg(Addrd(register.into(), addr.parse().unwrap())) + .unwrap(); log::info!("[6] sent GET Observe=1 /time"); for n in 0..=2 { @@ -202,9 +171,8 @@ mod test { log::info!("[{}] got {}", 7 + n, resp.data().payload_string().unwrap()); } - client - .send_msg(Addrd(deregister.into(), addr.parse().unwrap())) - .unwrap(); + client.send_msg(Addrd(deregister.into(), addr.parse().unwrap())) + .unwrap(); log::info!("[10] sent GET Observe=0 /time"); } } @@ -215,12 +183,8 @@ pub fn main() { std::env::set_var("RUST_LOG", "trace,toad=trace"); simple_logger::init_with_env().unwrap(); - let (server_addr, client_a_addr, client_b_addr, client_c_addr) = ( - "127.0.0.1:1111", - "127.0.0.1:2222", - "127.0.0.1:3333", - "127.0.0.1:4444", - ); + let (server_addr, client_a_addr, client_b_addr, client_c_addr) = + ("127.0.0.1:1111", "127.0.0.1:2222", "127.0.0.1:3333", "127.0.0.1:4444"); start_server(&server_addr); let client_a = P::try_new(client_a_addr, Config::default()).unwrap(); @@ -228,11 +192,9 @@ pub fn main() { let client_c = P::try_new(client_c_addr, Config::default()).unwrap(); let (client_a, client_b, client_c): (&'static P, &'static P, &'static P) = unsafe { - ( - core::mem::transmute(&client_a), - core::mem::transmute(&client_b), - core::mem::transmute(&client_c), - ) + (core::mem::transmute(&client_a), + core::mem::transmute(&client_b), + core::mem::transmute(&client_c)) }; test::hello(client_a, server_addr); @@ -254,11 +216,8 @@ pub fn main() { b.join().unwrap(); c.join().unwrap(); - client_a - .send_msg(Addrd( - Req::>::post("done").into(), - server_addr.parse().unwrap(), - )) - .unwrap(); + client_a.send_msg(Addrd(Req::>::post("done").into(), + server_addr.parse().unwrap())) + .unwrap(); log::info!("[10] done"); } diff --git a/toad/examples/server_minimal.rs b/toad/examples/server_minimal.rs index 0f55f992..610c9424 100644 --- a/toad/examples/server_minimal.rs +++ b/toad/examples/server_minimal.rs @@ -15,12 +15,9 @@ pub fn main() { let server = P::try_new(server_addr, Config::default()).unwrap(); let client = P::try_new(client_addr, Config::default()).unwrap(); - client - .send_msg(Addrd( - Req::>::get("hello").into(), - server_addr.parse().unwrap(), - )) - .unwrap(); + client.send_msg(Addrd(Req::>::get("hello").into(), + server_addr.parse().unwrap())) + .unwrap(); let req = nb::block!(server.poll_req()).unwrap(); assert_eq!(req.data().path().ok().flatten(), Some("hello")); diff --git a/toad/examples/server_traffic.rs b/toad/examples/server_traffic.rs index 1e6b20d2..8edc9713 100644 --- a/toad/examples/server_traffic.rs +++ b/toad/examples/server_traffic.rs @@ -1,7 +1,6 @@ use std::io; -use std::sync::Barrier; +use std::sync::{Barrier, OnceLock}; -use lazycell::AtomicLazyCell; use toad::config::Config; use toad::net::Addrd; use toad::platform::Platform as _; @@ -13,67 +12,60 @@ use toad::step::runtime; fn start_server(addr: &'static str) { const WORKER_THREAD_COUNT: usize = 10; - static STARTED: AtomicLazyCell = AtomicLazyCell::NONE; - STARTED.fill(Barrier::new(WORKER_THREAD_COUNT + 1)).unwrap(); + static STARTED: OnceLock = OnceLock::new(); + STARTED.set(Barrier::new(WORKER_THREAD_COUNT + 1)).unwrap(); log::info!("[1] starting server"); std::thread::spawn(move || { - static SERVER: AtomicLazyCell

= AtomicLazyCell::NONE; - SERVER - .fill(P::try_new(addr, Config::default()).unwrap()) - .unwrap(); + static SERVER: OnceLock

= OnceLock::new(); + SERVER.set(P::try_new(addr, Config::default()).unwrap()) + .unwrap(); for _ in 1..=WORKER_THREAD_COUNT { std::thread::spawn(|| { let init = Init(Some(|| { - STARTED.borrow().unwrap().wait(); - })); - - SERVER - .borrow() - .unwrap() - .run(init, |run| { - run - .maybe(route::done) - .maybe(route::hello) - .maybe(route::not_found) - }) - .unwrap(); + STARTED.get().unwrap().wait(); + })); + + SERVER.get() + .unwrap() + .run(init, |run| { + run.maybe(route::done) + .maybe(route::hello) + .maybe(route::not_found) + }) + .unwrap(); }); } }); - STARTED.borrow().unwrap().wait(); + STARTED.get().unwrap().wait(); } mod route { use super::*; - pub fn done( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn done(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { #![allow(unreachable_code)] ap.pipe(path::check::rest_equals("done")) .bind(|_| Ap::respond(panic!("shutting down..."))) } - pub fn hello( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn hello(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { ap.pipe(path::segment::check::next_equals("hello")) .pipe(path::segment::next(|_, name| { - name - .map(String::from) - .map(Ap::ok) - .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) - })) + name.map(String::from) + .map(Ap::ok) + .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) + })) .bind(|name| respond::ok(format!("Hello, {name}!").into())) } - pub fn not_found( - ap: Ap, (), io::Error>, - ) -> Ap, (), io::Error> { + pub fn not_found(ap: Ap, (), io::Error>) + -> Ap, (), io::Error> { ap.pipe(path::rest(|_, r| Ap::ok(r.to_string()))) .bind(|path| respond::not_found(format!("resource {path} not found").into())) } @@ -83,23 +75,17 @@ mod test { use super::*; pub fn hello(client: &P, name: &str, addr: &str) { - let (_, token) = client - .send_msg(Addrd( - Req::>::get(format!("hello/{}", name)).into(), - addr.parse().unwrap(), - )) - .unwrap(); - log::info!( - "{} -> GET /hello/{}", - client.socket().local_addr().unwrap(), - name - ); + let (_, token) = + client.send_msg(Addrd(Req::>::get(format!("hello/{}", name)).into(), + addr.parse().unwrap())) + .unwrap(); + log::info!("{} -> GET /hello/{}", + client.socket().local_addr().unwrap(), + name); let resp = nb::block!(client.poll_resp(token, addr.parse().unwrap())).unwrap(); - assert_eq!( - resp.data().payload_string().unwrap(), - format!("Hello, {}!", name) - ); + assert_eq!(resp.data().payload_string().unwrap(), + format!("Hello, {}!", name)); log::info!("<- 'Hello, {}!'", name); } } @@ -114,13 +100,12 @@ pub fn main() { start_server(&server_addr); const N_CLIENTS: usize = 4; - static FINISHED: AtomicLazyCell = AtomicLazyCell::NONE; - FINISHED.fill(Barrier::new(N_CLIENTS + 1)).unwrap(); + static FINISHED: OnceLock = OnceLock::new(); + FINISHED.set(Barrier::new(N_CLIENTS + 1)).unwrap(); - let names = include_str!("./names.txt") - .split("\n") - .filter(|s| !s.is_empty()) - .collect::>(); + let names = include_str!("./names.txt").split("\n") + .filter(|s| !s.is_empty()) + .collect::>(); let n_names = names.len(); let mut names = names.into_iter(); let names_mut = &mut names; @@ -132,22 +117,18 @@ pub fn main() { std::thread::spawn(move || { let addr = format!("127.0.0.1:22{n:02}"); let client = P::try_new(addr, Config::default()).unwrap(); - names - .into_iter() - .for_each(|name| test::hello(&client, name.trim(), server_addr)); - FINISHED.borrow().unwrap().wait(); + names.into_iter() + .for_each(|name| test::hello(&client, name.trim(), server_addr)); + FINISHED.get().unwrap().wait(); }); } - FINISHED.borrow().unwrap().wait(); + FINISHED.get().unwrap().wait(); - let done = Addrd( - Req::>::get("done").into(), - server_addr.parse().unwrap(), - ); + let done = Addrd(Req::>::get("done").into(), + server_addr.parse().unwrap()); - P::try_new("127.0.0.1:8888", Config::default()) - .unwrap() - .send_msg(done) - .unwrap(); + P::try_new("127.0.0.1:8888", Config::default()).unwrap() + .send_msg(done) + .unwrap(); } diff --git a/toad/src/config.rs b/toad/src/config.rs index fc409445..71b095f7 100644 --- a/toad/src/config.rs +++ b/toad/src/config.rs @@ -157,41 +157,29 @@ pub struct Msg { impl Default for Con { fn default() -> Self { - Con { - unacked_retry_strategy: Strategy::Exponential { - init_min: Milliseconds(500), - init_max: Milliseconds(1_000), - }, - acked_retry_strategy: Strategy::Exponential { - init_min: Milliseconds(1_000), - init_max: Milliseconds(2_000), - }, - max_attempts: Attempts(4), - } + Con { unacked_retry_strategy: Strategy::Exponential { init_min: Milliseconds(500), + init_max: Milliseconds(1_000) }, + acked_retry_strategy: Strategy::Exponential { init_min: Milliseconds(1_000), + init_max: Milliseconds(2_000) }, + max_attempts: Attempts(4) } } } impl Default for Non { fn default() -> Self { - Non { - retry_strategy: Strategy::Exponential { - init_min: Milliseconds(250), - init_max: Milliseconds(500), - }, - max_attempts: Attempts(4), - } + Non { retry_strategy: Strategy::Exponential { init_min: Milliseconds(250), + init_max: Milliseconds(500) }, + max_attempts: Attempts(4) } } } impl Default for Msg { fn default() -> Self { - Msg { - token_seed: 0, - probing_rate: BytesPerSecond(1000), - con: Con::default(), - non: Non::default(), - multicast_response_leisure: Milliseconds(5000), - } + Msg { token_seed: 0, + probing_rate: BytesPerSecond(1000), + con: Con::default(), + non: Non::default(), + multicast_response_leisure: Milliseconds(5000) } } } @@ -215,60 +203,52 @@ pub struct Config { impl Default for Config { fn default() -> Self { - Config { - msg: Msg::default(), - max_concurrent_requests: 1, - } + Config { msg: Msg::default(), + max_concurrent_requests: 1 } } } impl Config { pub(crate) fn max_transmit_span_millis(&self) -> u64 { - let acked_con = self - .msg - .con - .acked_retry_strategy - .max_time(self.msg.con.max_attempts - Attempts(1)) - .0 as u64; + let acked_con = self.msg + .con + .acked_retry_strategy + .max_time(self.msg.con.max_attempts - Attempts(1)) + .0 as u64; - let unacked_con = self - .msg - .con - .unacked_retry_strategy - .max_time(self.msg.con.max_attempts - Attempts(1)) - .0 as u64; + let unacked_con = self.msg + .con + .unacked_retry_strategy + .max_time(self.msg.con.max_attempts - Attempts(1)) + .0 as u64; - let non = self - .msg - .non - .retry_strategy - .max_time(self.msg.non.max_attempts - Attempts(1)) - .0 as u64; + let non = self.msg + .non + .retry_strategy + .max_time(self.msg.non.max_attempts - Attempts(1)) + .0 as u64; acked_con.max(unacked_con).max(non) } pub(crate) fn max_transmit_wait_millis(&self) -> u64 { - let acked_con = self - .msg - .con - .acked_retry_strategy - .max_time(self.msg.con.max_attempts) - .0 as u64; + let acked_con = self.msg + .con + .acked_retry_strategy + .max_time(self.msg.con.max_attempts) + .0 as u64; - let unacked_con = self - .msg - .con - .unacked_retry_strategy - .max_time(self.msg.con.max_attempts) - .0 as u64; + let unacked_con = self.msg + .con + .unacked_retry_strategy + .max_time(self.msg.con.max_attempts) + .0 as u64; - let non = self - .msg - .non - .retry_strategy - .max_time(self.msg.non.max_attempts) - .0 as u64; + let non = self.msg + .non + .retry_strategy + .max_time(self.msg.non.max_attempts) + .0 as u64; acked_con.max(unacked_con).max(non) } @@ -284,7 +264,7 @@ impl Config { pub(crate) fn exchange_lifetime_millis(&self) -> u64 { self.max_transmit_span_millis() - + (2 * self.max_latency_millis()) - + self.expected_processing_delay_millis() + + (2 * self.max_latency_millis()) + + self.expected_processing_delay_millis() } } diff --git a/toad/src/net.rs b/toad/src/net.rs index 2098e3e6..e7bf1595 100644 --- a/toad/src/net.rs +++ b/toad/src/net.rs @@ -109,9 +109,9 @@ pub trait Socket: Sized { let addr = addr.to_socket_addrs().unwrap().next().unwrap(); Self::bind_raw(addr).discard(|sock: &Self| match addr.ip() { - | ip if ip.is_multicast() => sock.join_multicast(ip), - | _ => Ok(()), - }) + | ip if ip.is_multicast() => sock.join_multicast(ip), + | _ => Ok(()), + }) } /// Send a message to a remote address diff --git a/toad/src/option.rs b/toad/src/option.rs index cbb3a0d9..3872e0f5 100644 --- a/toad/src/option.rs +++ b/toad/src/option.rs @@ -248,4 +248,5 @@ macro_rules! common_options { }; } -pub(crate) use {builder_method, common_options}; +pub(crate) use builder_method; +pub(crate) use common_options; diff --git a/toad/src/platform.rs b/toad/src/platform.rs index 63659f1c..e6bf6b9d 100644 --- a/toad/src/platform.rs +++ b/toad/src/platform.rs @@ -27,9 +27,8 @@ pub enum Error { } impl PlatformError for Error -where - Step: core::fmt::Debug, - Socket: core::fmt::Debug, + where Step: core::fmt::Debug, + Socket: core::fmt::Debug { fn msg_to_bytes(e: ::toad_msg::to_bytes::MessageToBytesError) -> Self { Self::MessageToBytes(e) @@ -74,8 +73,8 @@ pub trait PlatformError: Sized + core::fmt::Debug { /// * [`Platform::Types`] /// * [`Platform::Error`] pub trait Platform -where - Steps: Step>, PollResp = Addrd>>, + where Steps: + Step>, PollResp = Addrd>> { /// See [`PlatformTypes`] type Types: PlatformTypes; @@ -83,10 +82,8 @@ where /// Slot for any error type that impls [`PlatformError`]. /// /// If no custom behavior is needed, [`self::Error`] is a sensible default. - type Error: PlatformError< - >::Error, - <::Socket as Socket>::Error, - >; + type Error: PlatformError<>::Error, + <::Socket as Socket>::Error>; /// Take a snapshot of the platform's state right now, /// including the system time and datagrams currently @@ -94,43 +91,36 @@ where fn snapshot(&self) -> Result, Self::Error> { use embedded_time::Clock; - self - .socket() - .poll() - .map_err(Self::Error::socket) - .and_then(|recvd_dgram| { - self - .clock() - .try_now() - .map_err(Self::Error::clock) - .map(|time| Snapshot { - recvd_dgram, - config: self.config(), - time, - }) - }) + self.socket() + .poll() + .map_err(Self::Error::socket) + .and_then(|recvd_dgram| { + self.clock() + .try_now() + .map_err(Self::Error::clock) + .map(|time| Snapshot { recvd_dgram, + config: self.config(), + time }) + }) } /// Poll for an incoming request, and pass it through `Steps` /// for processing. fn poll_req(&self) -> nb::Result>, Self::Error> { let mut effects = ::Effects::default(); - let res = self - .snapshot() - .map_err(nb::Error::Other) - .and_then(|snapshot| { - self - .steps() - .poll_req(&snapshot, &mut effects) - .unwrap_or(Err(nb::Error::WouldBlock)) - .map_err(|e: nb::Error<_>| e.map(Self::Error::step)) - }); + let res = self.snapshot() + .map_err(nb::Error::Other) + .and_then(|snapshot| { + self.steps() + .poll_req(&snapshot, &mut effects) + .unwrap_or(Err(nb::Error::WouldBlock)) + .map_err(|e: nb::Error<_>| e.map(Self::Error::step)) + }); // NOTE: exec effects even if the above blocks - self - .exec_many(effects) - .map_err(|(_, e)| e) - .map_err(nb::Error::Other)?; + self.exec_many(effects) + .map_err(|(_, e)| e) + .map_err(nb::Error::Other)?; res } @@ -138,42 +128,36 @@ where /// Notify Observe subscribers that a new representation of the resource /// at `path` is available fn notify

(&self, path: P) -> Result<(), Self::Error> - where - P: AsRef + Clone, + where P: AsRef + Clone { let mut effects = ::Effects::default(); - self - .steps() - .notify(path, &mut effects) - .map_err(Self::Error::step)?; + self.steps() + .notify(path, &mut effects) + .map_err(Self::Error::step)?; self.exec_many(effects).map_err(|(_, e)| e) } /// Poll for a response to a sent request, and pass it through `Steps` /// for processing. - fn poll_resp( - &self, - token: Token, - addr: SocketAddr, - ) -> nb::Result>, Self::Error> { + fn poll_resp(&self, + token: Token, + addr: SocketAddr) + -> nb::Result>, Self::Error> { let mut effects = ::Effects::default(); - let res = self - .snapshot() - .map_err(nb::Error::Other) - .and_then(|snapshot| { - self - .steps() - .poll_resp(&snapshot, &mut effects, token, addr) - .unwrap_or(Err(nb::Error::WouldBlock)) - .map_err(|e: nb::Error<_>| e.map(Self::Error::step)) - }); + let res = self.snapshot() + .map_err(nb::Error::Other) + .and_then(|snapshot| { + self.steps() + .poll_resp(&snapshot, &mut effects, token, addr) + .unwrap_or(Err(nb::Error::WouldBlock)) + .map_err(|e: nb::Error<_>| e.map(Self::Error::step)) + }); // NOTE: exec effects even if the above blocks - self - .exec_many(effects) - .map_err(|(_, e)| e) - .map_err(nb::Error::Other)?; + self.exec_many(effects) + .map_err(|(_, e)| e) + .map_err(nb::Error::Other)?; res } @@ -184,10 +168,9 @@ where fn log(&self, level: log::Level, msg: String<1000>) -> Result<(), Self::Error>; /// Send a [`toad_msg::Message`] - fn send_msg( - &self, - mut addrd_msg: Addrd>, - ) -> nb::Result<(Id, Token), Self::Error> { + fn send_msg(&self, + mut addrd_msg: Addrd>) + -> nb::Result<(Id, Token), Self::Error> { type Dgram

= <

::Socket as Socket>::Dgram; let mut effs = ::Effects::default(); @@ -260,23 +243,22 @@ where /// /// If executing an effect errors, the erroring effect and all remaining effects are /// returned along with the error. - fn exec_many( - &self, - effects: ::Effects, - ) -> Result<(), (::Effects, Self::Error)> { - effects - .into_iter() - .fold(Ok(()), |so_far, eff| match so_far { - | Ok(()) => nb::block!(self.exec_1(&eff)).map_err(|e| { - let mut effs: ::Effects = Default::default(); - effs.push(eff); - (effs, e) - }), - | Err((mut effs, e)) => { - effs.push(eff); - Err((effs, e)) - }, - }) + fn exec_many(&self, + effects: ::Effects) + -> Result<(), (::Effects, Self::Error)> { + effects.into_iter() + .fold(Ok(()), |so_far, eff| match so_far { + | Ok(()) => nb::block!(self.exec_1(&eff)).map_err(|e| { + let mut effs: ::Effects = + Default::default(); + effs.push(eff); + (effs, e) + }), + | Err((mut effs, e)) => { + effs.push(eff); + Err((effs, e)) + }, + }) } /// Copy of runtime behavior [`Config`] to be used @@ -351,20 +333,18 @@ pub struct Snapshot { impl core::fmt::Debug for Snapshot

{ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Snapshot") - .field("time", &self.time) - .field("recvd_dgram", &self.recvd_dgram) - .field("config", &self.config) - .finish() + .field("time", &self.time) + .field("recvd_dgram", &self.recvd_dgram) + .field("config", &self.config) + .finish() } } impl Clone for Snapshot

{ fn clone(&self) -> Self { - Self { - time: self.time, - recvd_dgram: self.recvd_dgram.clone(), - config: self.config, - } + Self { time: self.time, + recvd_dgram: self.recvd_dgram.clone(), + config: self.config } } } @@ -373,17 +353,14 @@ impl Clone for Snapshot

{ /// to perform. #[allow(missing_docs)] pub enum Effect

-where - P: PlatformTypes, + where P: PlatformTypes { Send(Addrd>), Log(log::Level, String<1000>), Nop, } -impl

Default for Effect

-where - P: PlatformTypes, +impl

Default for Effect

where P: PlatformTypes { fn default() -> Self { Self::Nop @@ -444,9 +421,8 @@ impl Retryable { #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] #[derive(Copy)] pub struct Alloc(core::marker::PhantomData<(Clk, Sock)>) -where - Clk: Clock + 'static, - Sock: Socket + 'static; + where Clk: Clock + 'static, + Sock: Socket + 'static; #[cfg(feature = "alloc")] impl core::fmt::Debug for Alloc { diff --git a/toad/src/req/builder.rs b/toad/src/req/builder.rs index fc58564c..e8c4032e 100644 --- a/toad/src/req/builder.rs +++ b/toad/src/req/builder.rs @@ -10,10 +10,9 @@ use crate::ToCoapValue; /// Errors encounterable while using ReqBuilder #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error

-where - P: PlatformTypes, - platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, - platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq, + where P: PlatformTypes, + platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, + platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq { /// Ran out of storage space for options SetOptionError(platform::toad_msg::opt::SetError

), @@ -57,24 +56,20 @@ where /// ``` #[derive(Clone, Debug)] pub struct ReqBuilder

-where - P: PlatformTypes, - platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, - platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq, + where P: PlatformTypes, + platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, + platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq { inner: Result, Error

>, } impl

ReqBuilder

-where - P: PlatformTypes, - platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, - platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq, + where P: PlatformTypes, + platform::toad_msg::opt::OptValue

: Clone + Eq + core::fmt::Debug, + platform::toad_msg::opt::SetError

: Clone + core::fmt::Debug + Eq { fn new(method: Method, path: impl AsRef) -> Self { - Self { - inner: Ok(Req::new(method, path)), - } + Self { inner: Ok(Req::new(method, path)) } } /// Creates a GET request @@ -101,21 +96,21 @@ where /// /// If the option has already been set, this will yield `Err(Error::OptionNotRepeatable)`. pub fn option(mut self, number: OptNumber, value: V) -> Self { - self.inner = self.inner.and_then(|mut req| { - let val = OptValue(value.to_coap_value::>()); - match req.as_mut().remove(number) { - | Some(existing) => Err(Error::OptionNotRepeatable { - number, - old: existing.into_iter().next().unwrap(), - new: val, - }), - | None => req - .msg_mut() - .set(number, val) - .map_err(Error::SetOptionError) - .map(|_| req), - } - }); + self.inner = + self.inner.and_then(|mut req| { + let val = OptValue(value.to_coap_value::>()); + match req.as_mut().remove(number) { + | Some(existing) => { + Err(Error::OptionNotRepeatable { number, + old: existing.into_iter().next().unwrap(), + new: val }) + }, + | None => req.msg_mut() + .set(number, val) + .map_err(Error::SetOptionError) + .map(|_| req), + } + }); self } @@ -123,24 +118,23 @@ where /// pub fn add_option(mut self, number: OptNumber, value: V) -> Self { self.inner = self.inner.and_then(|mut req| { - let val = OptValue(value.to_coap_value::>()); - req - .msg_mut() - .set(number, val) - .map_err(Error::SetOptionError) - .map(|_| req) - }); + let val = + OptValue(value.to_coap_value::>()); + req.msg_mut() + .set(number, val) + .map_err(Error::SetOptionError) + .map(|_| req) + }); self } /// Set the payload of the request pub fn payload(mut self, value: V) -> Self { - self - .inner - .as_mut() - .discard_mut(|i: &mut &mut Req

| Ok(i.set_payload(value))) - .ok(); + self.inner + .as_mut() + .discard_mut(|i: &mut &mut Req

| Ok(i.set_payload(value))) + .ok(); self } diff --git a/toad/src/req/method.rs b/toad/src/req/method.rs index 418fcfe5..46b11e8c 100644 --- a/toad/src/req/method.rs +++ b/toad/src/req/method.rs @@ -27,26 +27,16 @@ impl core::fmt::Display for Method { use std_alloc::string::ToString; let string = match self.0 { - | Code { - class: 0, - detail: 0, - } => "EMPTY".to_string(), - | Code { - class: 0, - detail: 1, - } => "GET".to_string(), - | Code { - class: 0, - detail: 2, - } => "PUT".to_string(), - | Code { - class: 0, - detail: 3, - } => "POST".to_string(), - | Code { - class: 0, - detail: 4, - } => "DELETE".to_string(), + | Code { class: 0, + detail: 0, } => "EMPTY".to_string(), + | Code { class: 0, + detail: 1, } => "GET".to_string(), + | Code { class: 0, + detail: 2, } => "PUT".to_string(), + | Code { class: 0, + detail: 3, } => "POST".to_string(), + | Code { class: 0, + detail: 4, } => "DELETE".to_string(), | c => c.to_string(), }; diff --git a/toad/src/req/mod.rs b/toad/src/req/mod.rs index 30bf9c8c..cad299f1 100644 --- a/toad/src/req/mod.rs +++ b/toad/src/req/mod.rs @@ -1,8 +1,14 @@ use toad_array::Array; use toad_map::Map; -use toad_msg::{ - Id, Message, MessageOptions, OptNumber, OptionMap, Payload, Token, TryIntoBytes, Type, -}; +use toad_msg::{Id, + Message, + MessageOptions, + OptNumber, + OptionMap, + Payload, + Token, + TryIntoBytes, + Type}; use crate::ToCoapValue; @@ -76,15 +82,13 @@ impl Clone for Req

{ impl Req

{ /// Create a request pub fn new(method: Method, path: impl AsRef) -> Self { - let msg = Message { - ty: Type::Con, - ver: Default::default(), - code: method.0, - id: Id(Default::default()), - opts: Default::default(), - payload: Payload(Default::default()), - token: Token(Default::default()), - }; + let msg = Message { ty: Type::Con, + ver: Default::default(), + code: method.0, + id: Id(Default::default()), + opts: Default::default(), + payload: Payload(Default::default()), + token: Token(Default::default()) }; let mut self_ = Self(msg); @@ -109,11 +113,10 @@ impl Req

{ /// Get the request path (Uri-Path option) pub fn path(&self) -> Result, core::str::Utf8Error> { - self - .get_option(toad_msg::opt::known::repeat::PATH) - .and_then(|o| o.get(0)) - .map(|o| core::str::from_utf8(&o.0).map(Some)) - .unwrap_or(Ok(None)) + self.get_option(toad_msg::opt::known::repeat::PATH) + .and_then(|o| o.get(0)) + .map(|o| core::str::from_utf8(&o.0).map(Some)) + .unwrap_or(Ok(None)) } /// Get the request type (confirmable, non-confirmable) @@ -221,12 +224,11 @@ impl Req

{ /// assert_eq!(path.get(0).unwrap(), &OptValue("hello".as_bytes().to_vec())); /// ``` pub fn get_option(&self, n: OptNumber) -> Option<&::OptValues> { - self - .0 - .opts - .iter() - .find(|(num, _)| **num == n) - .map(|(_, v)| v) + self.0 + .opts + .iter() + .find(|(num, _)| **num == n) + .map(|(_, v)| v) } /// Get the payload and attempt to interpret it as an ASCII string @@ -246,24 +248,20 @@ impl Req

{ /// Iterate over the options attached to this request pub fn opts( - &self, - ) -> impl Iterator::OptValues)> { + &self) + -> impl Iterator::OptValues)> { self.0.opts.iter() } } -impl

AsRef> for Req

-where - P: platform::PlatformTypes, +impl

AsRef> for Req

where P: platform::PlatformTypes { fn as_ref(&self) -> &platform::Message

{ &self.0 } } -impl

AsMut> for Req

-where - P: platform::PlatformTypes, +impl

AsMut> for Req

where P: platform::PlatformTypes { fn as_mut(&mut self) -> &mut platform::Message

{ &mut self.0 diff --git a/toad/src/resp/mod.rs b/toad/src/resp/mod.rs index bf539bba..d846c212 100644 --- a/toad/src/resp/mod.rs +++ b/toad/src/resp/mod.rs @@ -40,49 +40,37 @@ pub mod code; /// # f(toad::req::Req::get( "")); /// } /// ``` -pub struct Resp

(platform::Message

) -where - P: PlatformTypes; +pub struct Resp

(platform::Message

) where P: PlatformTypes; -impl

AsRef> for Resp

-where - P: PlatformTypes, +impl

AsRef> for Resp

where P: PlatformTypes { fn as_ref(&self) -> &platform::Message

{ &self.0 } } -impl

AsMut> for Resp

-where - P: PlatformTypes, +impl

AsMut> for Resp

where P: PlatformTypes { fn as_mut(&mut self) -> &mut platform::Message

{ &mut self.0 } } -impl

core::fmt::Debug for Resp

-where - P: PlatformTypes, +impl

core::fmt::Debug for Resp

where P: PlatformTypes { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Resp").field(&self.0).finish() } } -impl

Clone for Resp

-where - P: PlatformTypes, +impl

Clone for Resp

where P: PlatformTypes { fn clone(&self) -> Self { Self(self.0.clone()) } } -impl

PartialEq for Resp

-where - P: PlatformTypes, +impl

PartialEq for Resp

where P: PlatformTypes { fn eq(&self, other: &Self) -> bool { self.0 == other.0 @@ -149,15 +137,13 @@ impl Resp

{ /// If you do need to ensure they receive your response, /// you pub fn ack(req: &Req

) -> Self { - let msg = Message { - ty: Type::Ack, - id: req.msg().id, - opts: P::MessageOptions::default(), - code: code::CONTENT, - ver: Default::default(), - payload: Payload(Default::default()), - token: req.msg().token, - }; + let msg = Message { ty: Type::Ack, + id: req.msg().id, + opts: P::MessageOptions::default(), + code: code::CONTENT, + ver: Default::default(), + payload: Payload(Default::default()), + token: req.msg().token }; Self(msg) } @@ -175,15 +161,13 @@ impl Resp

{ /// The `toad` runtime will continually retry sending this until /// an ACKnowledgement from the client is received. pub fn con(req: &Req

) -> Self { - let msg = Message { - ty: Type::Con, - id: Id(Default::default()), - opts: P::MessageOptions::default(), - code: code::CONTENT, - ver: Default::default(), - payload: Payload(Default::default()), - token: req.msg().token, - }; + let msg = Message { ty: Type::Con, + id: Id(Default::default()), + opts: P::MessageOptions::default(), + code: code::CONTENT, + ver: Default::default(), + payload: Payload(Default::default()), + token: req.msg().token }; Self(msg) } @@ -194,15 +178,13 @@ impl Resp

{ /// - you receive a NON request and don't need to ensure the client received the response /// - you receive a CON request and don't need to ensure the client received the response (**you _must_ ACK this type of request separately**) pub fn non(req: &Req

) -> Self { - let msg = Message { - ty: Type::Non, - id: Id(Default::default()), - opts: P::MessageOptions::default(), - code: code::CONTENT, - ver: Default::default(), - payload: Payload(Default::default()), - token: req.msg().token, - }; + let msg = Message { ty: Type::Non, + id: Id(Default::default()), + opts: P::MessageOptions::default(), + code: code::CONTENT, + ver: Default::default(), + payload: Payload(Default::default()), + token: req.msg().token }; Self(msg) } diff --git a/toad/src/retry.rs b/toad/src/retry.rs index a57715a4..2b04d48a 100644 --- a/toad/src/retry.rs +++ b/toad/src/retry.rs @@ -56,29 +56,27 @@ pub struct RetryTimer { max_attempts: Attempts, } -impl RetryTimer -where - C: Clock, +impl RetryTimer where C: Clock { /// Create a new retrier pub fn new(start: Instant, strategy: Strategy, max_attempts: Attempts) -> Self { - Self { - start, - strategy, - last_attempted_at: None, - init: if strategy.has_jitter() { - let mut rand = Ok(start.duration_since_epoch()) - .bind(Millis::try_from) - .map(|Milliseconds(ms)| rand_chacha::ChaCha8Rng::seed_from_u64(ms)) - .unwrap(); - - Milliseconds(rand.random_range(strategy.range())) - } else { - Milliseconds(*strategy.range().start()) - }, - max_attempts, - attempts: Attempts(1), - } + Self { start, + strategy, + last_attempted_at: None, + init: if strategy.has_jitter() { + let mut rand = + Ok(start.duration_since_epoch()).bind(Millis::try_from) + .map(|Milliseconds(ms)| { + rand_chacha::ChaCha8Rng::seed_from_u64(ms) + }) + .unwrap(); + + Milliseconds(rand.random_range(strategy.range())) + } else { + Milliseconds(*strategy.range().start()) + }, + max_attempts, + attempts: Attempts(1) } } /// When the thing we keep trying fails, invoke this to @@ -86,10 +84,9 @@ where /// /// Returns `nb::Error::WouldBlock` when we have not yet /// waited the appropriate amount of time to retry. - pub fn what_should_i_do( - &mut self, - now: Instant, - ) -> nb::Result { + pub fn what_should_i_do(&mut self, + now: Instant) + -> nb::Result { if self.attempts >= self.max_attempts { Ok(YouShould::Cry) } else { @@ -110,9 +107,8 @@ where /// Get the instant this retry timer was last attempted (if at all) pub fn last_attempted_at(&self) -> Instant { - self - .last_attempted_at - .unwrap_or_else(|| self.first_attempted_at()) + self.last_attempted_at + .unwrap_or_else(|| self.first_attempted_at()) } /// Get the next time at which this should be retried @@ -129,33 +125,27 @@ where } impl Copy for RetryTimer where C: Clock {} -impl Clone for RetryTimer -where - C: Clock, +impl Clone for RetryTimer where C: Clock { fn clone(&self) -> Self { - Self { - start: self.start, - init: self.init, - last_attempted_at: self.last_attempted_at, - strategy: self.strategy, - attempts: self.attempts, - max_attempts: self.max_attempts, - } + Self { start: self.start, + init: self.init, + last_attempted_at: self.last_attempted_at, + strategy: self.strategy, + attempts: self.attempts, + max_attempts: self.max_attempts } } } -impl PartialEq for RetryTimer -where - C: Clock, +impl PartialEq for RetryTimer where C: Clock { fn eq(&self, other: &Self) -> bool { self.start == other.start - && self.init == other.init - && self.last_attempted_at == other.last_attempted_at - && self.strategy == other.strategy - && self.attempts == other.attempts - && self.max_attempts == other.max_attempts + && self.init == other.init + && self.last_attempted_at == other.last_attempted_at + && self.strategy == other.strategy + && self.attempts == other.attempts + && self.max_attempts == other.max_attempts } } @@ -234,27 +224,23 @@ impl Strategy { /// Get the min & max durations as an inclusive range pub fn range(&self) -> RangeInclusive { match self { - | &Self::Delay { - min: Milliseconds(min), - max: Milliseconds(max), - } => min..=max, - - | &Self::Exponential { - init_min: Milliseconds(min), - init_max: Milliseconds(max), - } => min..=max, + | &Self::Delay { min: Milliseconds(min), + max: Milliseconds(max), } => min..=max, + + | &Self::Exponential { init_min: Milliseconds(min), + init_max: Milliseconds(max), } => min..=max, } } /// Get the amount of time this strategy will take if all attempts fail pub fn max_time(&self, max_attempts: Attempts) -> Millis { Milliseconds(match self { - | Self::Exponential { init_max, .. } => Self::total_delay_exp(*init_max, max_attempts.0), - | Self::Delay { - max: Milliseconds(max), - .. - } => max * max_attempts.0 as u64, - }) + | Self::Exponential { init_max, .. } => { + Self::total_delay_exp(*init_max, max_attempts.0) + }, + | Self::Delay { max: Milliseconds(max), + .. } => max * max_attempts.0 as u64, + }) } /// Given the initial delay and number of attempts that have been performed, @@ -302,32 +288,24 @@ mod test { let mut time_millis = 0u64; let clock = FakeClock::new(&time_millis as *const _); let now = || clock.try_now().unwrap(); - let mut retry = RetryTimer::new( - now(), - Strategy::Delay { - min: Milliseconds(1000), - max: Milliseconds(1000), - }, - Attempts(5), - ); + let mut retry = RetryTimer::new(now(), + Strategy::Delay { min: Milliseconds(1000), + max: Milliseconds(1000) }, + Attempts(5)); // attempt 1 happens before asking what_should_i_do time_millis = 999; - assert_eq!( - retry.what_should_i_do(now()).unwrap_err(), - nb::Error::WouldBlock - ); + assert_eq!(retry.what_should_i_do(now()).unwrap_err(), + nb::Error::WouldBlock); time_millis = 1000; assert_eq!(retry.what_should_i_do(now()).unwrap(), YouShould::Retry); // Fails again (attempt 2) time_millis = 1999; - assert_eq!( - retry.what_should_i_do(now()).unwrap_err(), - nb::Error::WouldBlock - ); + assert_eq!(retry.what_should_i_do(now()).unwrap_err(), + nb::Error::WouldBlock); time_millis = 2000; @@ -355,23 +333,17 @@ mod test { let mut time_millis = 0u64; let clock = FakeClock::new(&time_millis as *const _); let now = || clock.try_now().unwrap(); - let mut retry = RetryTimer::new( - now(), - Strategy::Exponential { - init_min: Milliseconds(1000), - init_max: Milliseconds(1000), - }, - Attempts(6), - ); + let mut retry = RetryTimer::new(now(), + Strategy::Exponential { init_min: Milliseconds(1000), + init_max: Milliseconds(1000) }, + Attempts(6)); // attempt 1 happens before asking what_should_i_do time_millis = 999; println!("{}", time_millis); - assert_eq!( - retry.what_should_i_do(now()).unwrap_err(), - nb::Error::WouldBlock - ); + assert_eq!(retry.what_should_i_do(now()).unwrap_err(), + nb::Error::WouldBlock); time_millis = 1000; println!("{}", time_millis); @@ -379,10 +351,8 @@ mod test { time_millis = 1999; println!("{}", time_millis); - assert_eq!( - retry.what_should_i_do(now()).unwrap_err(), - nb::Error::WouldBlock - ); + assert_eq!(retry.what_should_i_do(now()).unwrap_err(), + nb::Error::WouldBlock); time_millis = 2000; println!("{}", time_millis); @@ -390,10 +360,8 @@ mod test { time_millis = 3999; println!("{}", time_millis); - assert_eq!( - retry.what_should_i_do(now()).unwrap_err(), - nb::Error::WouldBlock - ); + assert_eq!(retry.what_should_i_do(now()).unwrap_err(), + nb::Error::WouldBlock); time_millis = 4000; println!("{}", time_millis); diff --git a/toad/src/server/ap/inner.rs b/toad/src/server/ap/inner.rs index 20fcafe7..fe729d92 100644 --- a/toad/src/server/ap/inner.rs +++ b/toad/src/server/ap/inner.rs @@ -5,9 +5,8 @@ use crate::platform::PlatformTypes; use crate::req::Req; pub(crate) enum ApInner -where - S: ApState, - P: PlatformTypes, + where S: ApState, + P: PlatformTypes { #[allow(dead_code)] Phantom(S), @@ -29,40 +28,36 @@ where } impl core::fmt::Debug for ApInner -where - S: ApState, - P: PlatformTypes, - E: core::fmt::Debug, - T: core::fmt::Debug, + where S: ApState, + P: PlatformTypes, + E: core::fmt::Debug, + T: core::fmt::Debug { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { | ApInner::Phantom(_) => unreachable!(), | ApInner::Ok(t) => f.debug_tuple("ApInner::Ok").field(&t).finish(), - | ApInner::OkHydrated(t, hy) => f - .debug_tuple("ApInner::OkHydrated") - .field(&t) - .field(&hy) - .finish(), + | ApInner::OkHydrated(t, hy) => f.debug_tuple("ApInner::OkHydrated") + .field(&t) + .field(&hy) + .finish(), | ApInner::Reject => f.debug_struct("ApInner::Reject").finish(), | ApInner::Respond(r) => f.debug_tuple("ApInner::Respond").field(&r).finish(), | ApInner::Err(e) => f.debug_tuple("ApInner::Err").field(&e).finish(), | ApInner::RejectHydrated(r) => f.debug_tuple("ApInner::RejectHydrated").field(&r).finish(), - | ApInner::RespondHydrated(req, rep) => f - .debug_tuple("ApInner::RespondHydrated") - .field(&req) - .field(&rep) - .finish(), + | ApInner::RespondHydrated(req, rep) => f.debug_tuple("ApInner::RespondHydrated") + .field(&req) + .field(&rep) + .finish(), } } } impl PartialEq for ApInner -where - S: ApState, - P: PlatformTypes, - E: PartialEq, - T: PartialEq, + where S: ApState, + P: PlatformTypes, + E: PartialEq, + T: PartialEq { fn eq(&self, other: &Self) -> bool { match (self, other) { @@ -81,11 +76,10 @@ where } impl Clone for ApInner -where - S: ApState, - P: PlatformTypes, - E: Clone, - T: Clone, + where S: ApState, + P: PlatformTypes, + E: Clone, + T: Clone { fn clone(&self) -> Self { match self { diff --git a/toad/src/server/ap/mod.rs b/toad/src/server/ap/mod.rs index 437b7461..2b451d01 100644 --- a/toad/src/server/ap/mod.rs +++ b/toad/src/server/ap/mod.rs @@ -16,46 +16,37 @@ pub(crate) use inner::*; #[non_exhaustive] #[allow(missing_docs)] pub struct Respond

-where - P: PlatformTypes, + where P: PlatformTypes { pub code: Code, pub payload: P::MessagePayload, pub etag: Option, } -impl

Clone for Respond

-where - P: PlatformTypes, +impl

Clone for Respond

where P: PlatformTypes { fn clone(&self) -> Self { - Respond { - code: self.code, - payload: self.payload.clone(), - etag: self.etag.clone(), - } + Respond { code: self.code, + payload: self.payload.clone(), + etag: self.etag.clone() } } } -impl

PartialEq for Respond

-where - P: PlatformTypes, +impl

PartialEq for Respond

where P: PlatformTypes { fn eq(&self, other: &Self) -> bool { self.code == other.code && self.payload == other.payload && self.etag == other.etag } } -impl

core::fmt::Debug for Respond

-where - P: PlatformTypes, +impl

core::fmt::Debug for Respond

where P: PlatformTypes { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Respond") - .field("code", &self.code) - .field("payload", &self.payload) - .field("etag", &self.etag) - .finish() + .field("code", &self.code) + .field("payload", &self.payload) + .field("etag", &self.etag) + .finish() } } @@ -63,59 +54,46 @@ where #[non_exhaustive] #[allow(missing_docs)] pub struct Hydrate

-where - P: PlatformTypes, + where P: PlatformTypes { pub req: Addrd>, pub path:

::MessageOptionMapOptionValues, pub path_ix: usize, } -impl

Hydrate

-where - P: PlatformTypes, +impl

Hydrate

where P: PlatformTypes { /// Construct a [`Hydrate`] from [`Addrd`]`<`[`Req`]`>` pub fn from_request(req: Addrd>) -> Self { - Self { - path: req.data().msg().get(PATH).cloned().unwrap_or_default(), - path_ix: 0, - req, - } + Self { path: req.data().msg().get(PATH).cloned().unwrap_or_default(), + path_ix: 0, + req } } } -impl

Clone for Hydrate

-where - P: PlatformTypes, +impl

Clone for Hydrate

where P: PlatformTypes { fn clone(&self) -> Self { - Hydrate { - req: self.req.clone(), - path_ix: self.path_ix, - path: self.path.clone(), - } + Hydrate { req: self.req.clone(), + path_ix: self.path_ix, + path: self.path.clone() } } } -impl

PartialEq for Hydrate

-where - P: PlatformTypes, +impl

PartialEq for Hydrate

where P: PlatformTypes { fn eq(&self, other: &Self) -> bool { self.req == other.req && self.path == other.path } } -impl

core::fmt::Debug for Hydrate

-where - P: PlatformTypes, +impl

core::fmt::Debug for Hydrate

where P: PlatformTypes { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Hydrate") - .field("req", &self.req) - .field("path", &self.path) - .finish() + .field("req", &self.req) + .field("path", &self.path) + .finish() } } @@ -232,16 +210,14 @@ where /// assert_eq!(reject_unchanged, Ap::reject_hydrated(Addrd(req(), addr))); /// ``` pub struct Ap(pub(crate) ApInner) -where - S: ApState, - P: PlatformTypes; + where S: ApState, + P: PlatformTypes; impl Clone for Ap -where - S: ApState, - P: PlatformTypes, - E: Clone, - T: Clone, + where S: ApState, + P: PlatformTypes, + E: Clone, + T: Clone { fn clone(&self) -> Self { Self(self.0.clone()) @@ -249,11 +225,10 @@ where } impl core::fmt::Debug for Ap -where - S: ApState, - P: PlatformTypes, - E: core::fmt::Debug, - T: core::fmt::Debug, + where S: ApState, + P: PlatformTypes, + E: core::fmt::Debug, + T: core::fmt::Debug { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Ap").field(&self.0).finish() @@ -261,11 +236,10 @@ where } impl PartialEq for Ap -where - S: ApState, - P: PlatformTypes, - E: PartialEq, - T: PartialEq, + where S: ApState, + P: PlatformTypes, + E: PartialEq, + T: PartialEq { fn eq(&self, other: &Self) -> bool { self.0 == other.0 @@ -273,9 +247,8 @@ where } impl Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { /// Construct an `Ap` in an `Ok` state pub fn ok(t: T) -> Self { @@ -292,9 +265,8 @@ where } impl Ap -where - P: PlatformTypes, - Error: core::fmt::Debug, + where P: PlatformTypes, + Error: core::fmt::Debug { /// Construct an `Ap` that will reject the incoming /// request. @@ -315,19 +287,17 @@ where } impl Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { /// Use a function `F` (`T -> Ap`) to transform the data contained in `Ap` /// and combine the result with self. /// /// The function will only be called if this is [`Ap::ok`] or [`Ap::ok_hydrated`]. pub fn bind_hydrated(self, f: F) -> Ap<>::Out, P, B, E> - where - F: FnOnce(T, &Addrd>) -> Ap, - S2: ApState, - Hydrated: state::Combine, + where F: FnOnce(T, &Addrd>) -> Ap, + S2: ApState, + Hydrated: state::Combine { match self.try_unwrap_ok_hydrated() { | Ok((t, Hydrate { req, .. })) => f(t, &req).hydrate(req).coerce_state(), @@ -347,14 +317,12 @@ where } impl Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { /// Coerce the state type to any other (this only applies to `Ap`s which are known to be [`Complete`].) pub fn pretend(self) -> Ap - where - S: ApState, + where S: ApState { self.coerce_state() } @@ -376,10 +344,9 @@ where } impl Ap -where - P: PlatformTypes, - S: ApState, - E: core::fmt::Debug, + where P: PlatformTypes, + S: ApState, + E: core::fmt::Debug { /// Is this [`Ap::ok`] or [`Ap::ok_hydrated`]? pub fn is_ok(&self) -> bool { @@ -497,8 +464,7 @@ where /// ok_to_err(ap()); /// ``` pub fn pipe(self, f: F) -> R - where - F: FnOnce(Self) -> R, + where F: FnOnce(Self) -> R { f(self) } @@ -507,28 +473,23 @@ where /// set the `etag` option for the response before sending. pub fn etag(self, etag: P::MessageOptionBytes) -> Self { match self.0 { - | ApInner::Respond(Respond { code, payload, .. }) => Ap::respond(Respond { - code, - payload, - etag: Some(etag), - }) - .coerce_state(), - | ApInner::RespondHydrated(Respond { code, payload, .. }, req) => Ap::respond_hydrated( - req, - Respond { - code, - payload, - etag: Some(etag), - }, - ) - .coerce_state(), + | ApInner::Respond(Respond { code, payload, .. }) => { + Ap::respond(Respond { code, + payload, + etag: Some(etag) }).coerce_state() + }, + | ApInner::RespondHydrated(Respond { code, payload, .. }, req) => { + Ap::respond_hydrated(req, + Respond { code, + payload, + etag: Some(etag) }).coerce_state() + }, | other => Self(other), } } pub(crate) fn coerce_state(self) -> Ap - where - S2: ApState, + where S2: ApState { let inner = match self.0 { | ApInner::Phantom(_) => unreachable!(), @@ -548,8 +509,7 @@ where /// /// The function will only be called if this is [`Ap::ok`] or [`Ap::ok_hydrated`]. pub fn map(self, f: F) -> Ap - where - F: FnOnce(T) -> B, + where F: FnOnce(T) -> B { let inner = match self.0 { | ApInner::Phantom(_) => unreachable!(), @@ -569,8 +529,7 @@ where /// /// The function will only be called if this is [`Ap::err`]. pub fn map_err(self, f: F) -> Ap - where - F: FnOnce(E) -> B, + where F: FnOnce(E) -> B { let inner = match self.0 { | ApInner::Phantom(_) => unreachable!(), @@ -591,10 +550,9 @@ where /// /// The function will only be called if this is [`Ap::ok`] or [`Ap::ok_hydrated`]. pub fn bind(self, f: F) -> Ap<>::Out, P, B, E> - where - F: FnOnce(T) -> Ap, - S2: ApState, - S: state::Combine, + where F: FnOnce(T) -> Ap, + S2: ApState, + S: state::Combine { let inner = match self.0 { | ApInner::Phantom(_) => unreachable!(), @@ -625,10 +583,9 @@ where /// ap.bind_discard(do_stuff) /// ``` pub fn bind_discard(self, f: F) -> Self - where - F: for<'a> FnOnce(&'a T) -> Ap, - S2: ApState, - S: Combine, + where F: for<'a> FnOnce(&'a T) -> Ap, + S2: ApState, + S: Combine { self.bind(|t| f(&t).map(|_| t)).coerce_state() } @@ -666,33 +623,23 @@ mod tests { let ok = || Ap::ok(()); let err = || Ap::err(()); let ok_hy = || { - Ap::ok_hydrated( - (), - Hydrate { - req: Addrd(req(), addr), - path: Default::default(), - path_ix: 0, - }, - ) + Ap::ok_hydrated((), + Hydrate { req: Addrd(req(), addr), + path: Default::default(), + path_ix: 0 }) }; let reject = || Ap::reject(); let respond = || { - Ap::respond(Respond { - code: code::CONTENT, - payload: "".into(), - etag: None, - }) + Ap::respond(Respond { code: code::CONTENT, + payload: "".into(), + etag: None }) }; let reject_hy = || Ap::reject_hydrated(Addrd(req(), addr)); let respond_hy = || { - Ap::respond_hydrated( - Addrd(req(), addr), - Respond { - code: code::CONTENT, - payload: "".into(), - etag: None, - }, - ) + Ap::respond_hydrated(Addrd(req(), addr), + Respond { code: code::CONTENT, + payload: "".into(), + etag: None }) }; macro_rules! case { diff --git a/toad/src/server/method.rs b/toad/src/server/method.rs index 52c469c7..ba78f39b 100644 --- a/toad/src/server/method.rs +++ b/toad/src/server/method.rs @@ -8,26 +8,22 @@ use crate::req::Method; /// Reject request if the code does not match `method` pub fn is(method: Method) -> impl Fn(Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { is_one_of(array_vec! {_ => method}) } /// Reject request if the code is not included in `methods` -pub fn is_one_of( - methods: ArrayVec<[Method; 5]>, -) -> impl Fn(Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, +pub fn is_one_of(methods: ArrayVec<[Method; 5]>) + -> impl Fn(Ap) -> Ap + where P: PlatformTypes, + E: core::fmt::Debug { move |ap| match ap.try_unwrap_ok_hydrated() { | Ok((t, h)) - if methods - .iter() - .any(|m| m.code() == h.req.data().as_ref().code) => + if methods.iter() + .any(|m| m.code() == h.req.data().as_ref().code) => { Ap::ok_hydrated(t, h) }, @@ -57,36 +53,32 @@ where /// assert!(post_request.pipe(method::get).is_rejected()); /// ``` pub fn get(ap: Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { ap.pipe(is(Method::GET)) } /// Reject non-POST requests pub fn post(ap: Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { ap.pipe(is(Method::POST)) } /// Reject non-PUT requests pub fn put(ap: Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { ap.pipe(is(Method::PUT)) } /// Reject non-DELETE requests pub fn delete(ap: Ap) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { ap.pipe(is(Method::DELETE)) } diff --git a/toad/src/server/mod.rs b/toad/src/server/mod.rs index 61bcc3c8..ce4816da 100644 --- a/toad/src/server/mod.rs +++ b/toad/src/server/mod.rs @@ -71,8 +71,7 @@ pub enum Error { /// ``` #[derive(Debug)] pub enum Run -where - P: PlatformTypes, + where P: PlatformTypes { /// Request has not been matched yet Unmatched(Addrd>), @@ -83,9 +82,8 @@ where } impl PartialEq for Run -where - P: PlatformTypes, - E: PartialEq, + where P: PlatformTypes, + E: PartialEq { fn eq(&self, other: &Self) -> bool { match (self, other) { @@ -98,22 +96,17 @@ where } impl Run -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { /// Lift an [`Ap`] to [`Run`] pub fn handle(ap: Ap) -> Self { match ap.0 { | ApInner::Err(e) => Self::Error(Error::Other(e)), - | ApInner::RespondHydrated( - Respond { - code, - payload, - etag, - }, - Addrd(req, addr), - ) => { + | ApInner::RespondHydrated(Respond { code, + payload, + etag, }, + Addrd(req, addr)) => { let mut resp = Resp::non(&req); resp.set_code(code); resp.set_payload(payload); @@ -137,8 +130,7 @@ where /// /// Each "maybe" branch corresponds roughly to a route / RESTful CoAP resource. pub fn maybe(self, mut f: F) -> Self - where - F: FnMut(Ap) -> Ap, + where F: FnMut(Ap) -> Ap { match self { | Run::Matched(m) => Run::Matched(m), @@ -168,19 +160,17 @@ impl Init { /// Servers are thread-safe, meaning that [`run`](BlockingServer::run) may /// be invoked concurrently by multiple worker threads. pub trait BlockingServer: Sized + Platform -where - S: Step>, PollResp = Addrd>>, + where S: Step>, PollResp = Addrd>> { #[allow(missing_docs)] fn run(&self, init: Init, mut handle_request: R) -> Result<(), Error> - where - I: FnMut(), - R: FnMut(Run) -> Run, + where I: FnMut(), + R: FnMut(Run) -> Run { let mut startup_msg = String::<1000>::default(); write!( - &mut startup_msg, - r#" + &mut startup_msg, + r#" ===================================== _ @@ -196,13 +186,11 @@ where listening on `{}`. ====================================="#, - self.socket().local_addr() - ) - .ok(); + self.socket().local_addr() + ).ok(); - self - .log(log::Level::Info, startup_msg) - .map_err(Error::Other)?; + self.log(log::Level::Info, startup_msg) + .map_err(Error::Other)?; init.0.map(|mut f| f()); @@ -211,30 +199,25 @@ where match handle_request(Run::Unmatched(req)) { | Run::Unmatched(req) => { let mut msg = String::<1000>::default(); - write!( - &mut msg, - "IGNORING Request, not handled by any routes! {:?}", - req - ) - .ok(); + write!(&mut msg, + "IGNORING Request, not handled by any routes! {:?}", + req).ok(); self.log(log::Level::Error, msg).map_err(Error::Other)?; let mut msg = String::<1000>::default(); write!( - &mut msg, - r#" + &mut msg, + r#" Do you need a fallback? server.run(|run| run.maybe(..) .maybe(..) .maybe(..) .maybe(|ap| ap.bind(|_| respond::not_found(\"Not found!\")))) )"# - ) - .ok(); + ).ok(); }, - | Run::Matched(rep) => nb::block!(self.send_msg(rep.clone())) - .map_err(Error::Other) - .map(|_| ())?, + | Run::Matched(rep) => nb::block!(self.send_msg(rep.clone())).map_err(Error::Other) + .map(|_| ())?, | Run::Error(e) => break Err(e), } } @@ -242,9 +225,8 @@ Do you need a fallback? } impl BlockingServer for T -where - S: Step>, PollResp = Addrd>>, - T: Sized + Platform, + where S: Step>, PollResp = Addrd>>, + T: Sized + Platform { } @@ -257,10 +239,10 @@ mod tests { #[allow(dead_code)] fn foo() { let _ = Run::, _>::Error(Error::Other(())).maybe(|a| { - a.pipe(path::segment::check::next_equals("user")) - .pipe(path::segment::param::u32) - .bind(|(_, user_id)| respond::ok(format!("hello, user ID {}!", user_id).into())) - }); + a.pipe(path::segment::check::next_equals("user")) + .pipe(path::segment::param::u32) + .bind(|(_, user_id)| respond::ok(format!("hello, user ID {}!", user_id).into())) + }); } } } diff --git a/toad/src/server/path.rs b/toad/src/server/path.rs index c6f587e8..3504376f 100644 --- a/toad/src/server/path.rs +++ b/toad/src/server/path.rs @@ -32,36 +32,29 @@ pub mod segment { /// .pipe(path::segment::next(|_, c| Ap::ok(assert_eq!(c.unwrap(), "c")))); /// ``` pub fn next( - f: F, - ) -> impl FnOnce(Ap) -> Ap<>::Out, P, R, E> - where - P: PlatformTypes, - F: for<'a> FnOnce(T, Option<&'a str>) -> Ap, - E: core::fmt::Debug, - SOut: ApState, - Hydrated: Combine, + f: F) + -> impl FnOnce(Ap) -> Ap<>::Out, P, R, E> + where P: PlatformTypes, + F: for<'a> FnOnce(T, Option<&'a str>) -> Ap, + E: core::fmt::Debug, + SOut: ApState, + Hydrated: Combine { |ap| match ap.try_unwrap_ok_hydrated() { | Ok((t, Hydrate { path, path_ix, req })) => { if path_ix >= path.len() { Ap::ok_hydrated(t, Hydrate { req, path_ix, path }).bind(|t| f(t, None)) } else { - let seg_str = path - .get(path_ix) - .map(|seg| core::str::from_utf8(&seg.0).unwrap()) - .unwrap_or(""); + let seg_str = path.get(path_ix) + .map(|seg| core::str::from_utf8(&seg.0).unwrap()) + .unwrap_or(""); let ap_r = f(t, Some(seg_str)); - Ap::ok_hydrated( - (), - Hydrate { - req, - path_ix: path_ix + 1, - path, - }, - ) - .bind(|_| ap_r) + Ap::ok_hydrated((), + Hydrate { req, + path_ix: path_ix + 1, + path }).bind(|_| ap_r) } }, | Err(other) => other.bind(|_| unreachable!()).coerce_state(), @@ -104,10 +97,9 @@ pub mod segment { /// .is_rejected()); /// ``` pub fn next_is(f: F) -> impl FnOnce(Ap) -> Ap - where - P: PlatformTypes, - E: core::fmt::Debug, - F: for<'a> FnOnce(&'a str) -> bool, + where P: PlatformTypes, + E: core::fmt::Debug, + F: for<'a> FnOnce(&'a str) -> bool { next(move |t, a| match a { | Some(a) if f(a) => Ap::ok(t), @@ -116,13 +108,11 @@ pub mod segment { } /// Reject the request if the next path segment does not equal `path` - pub fn next_equals( - path: A, - ) -> impl FnOnce(Ap) -> Ap - where - P: PlatformTypes, - E: core::fmt::Debug, - A: AsRef + 'static, + pub fn next_equals(path: A) + -> impl FnOnce(Ap) -> Ap + where P: PlatformTypes, + E: core::fmt::Debug, + A: AsRef + 'static { next_is(move |s| s == path.as_ref()) } @@ -165,19 +155,18 @@ pub mod segment { /// assert!(other_ap.pipe(path::segment::param::u32).is_rejected()); /// ``` pub fn u32(ap: Ap) -> Ap - where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { let parse = |s: &str| u32::from_str_radix(s, 10); next(|t, s| { s.map(Ap::ok) - .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) - .map(parse) - .bind(Ap::from_result) - .reject_on_err() - .map(|u| (t, u)) + .unwrap_or_else(|| Ap::reject().pretend_unhydrated()) + .map(parse) + .bind(Ap::from_result) + .reject_on_err() + .map(|u| (t, u)) })(ap) } } @@ -186,39 +175,33 @@ pub mod segment { /// Get the rest of the request path, skipping any /// consumed [`segment`]s. pub fn rest( - f: F, -) -> impl FnOnce(Ap) -> Ap<>::Out, P, R, E> -where - P: PlatformTypes, - F: for<'a> FnOnce(T, &'a str) -> Ap, - E: core::fmt::Debug, - SOut: ApState, - Hydrated: Combine, + f: F) + -> impl FnOnce(Ap) -> Ap<>::Out, P, R, E> + where P: PlatformTypes, + F: for<'a> FnOnce(T, &'a str) -> Ap, + E: core::fmt::Debug, + SOut: ApState, + Hydrated: Combine { |ap| match ap.try_unwrap_ok_hydrated() { | Ok((t, Hydrate { path, req, path_ix })) => { let mut s = match path.get(path_ix..) { | Some(segs) => segs.iter().fold(String::<1000>::default(), |mut s, seg| { - if let Ok(seg) = core::str::from_utf8(seg.as_bytes()) { - write!(&mut s, "{seg}/").ok(); - } - s - }), + if let Ok(seg) = core::str::from_utf8(seg.as_bytes()) { + write!(&mut s, "{seg}/").ok(); + } + s + }), | None => String::<1000>::default(), }; s.as_writable().pop(); let ap_r = f(t, s.as_str()); - Ap::ok_hydrated( - (), - Hydrate { - req, - path_ix: path.len(), - path, - }, - ) - .bind(|_| ap_r) + Ap::ok_hydrated((), + Hydrate { req, + path_ix: path.len(), + path }).bind(|_| ap_r) }, | Err(other) => other.bind(|_| unreachable!()).coerce_state(), } @@ -230,10 +213,9 @@ pub mod check { /// Reject the request if the rest of the path does not match a predicate `F: FnOnce(&str) -> bool` pub fn rest_is(f: F) -> impl FnOnce(Ap) -> Ap - where - P: PlatformTypes, - E: core::fmt::Debug, - F: for<'a> FnOnce(&'a str) -> bool, + where P: PlatformTypes, + E: core::fmt::Debug, + F: for<'a> FnOnce(&'a str) -> bool { rest(move |t, a| match a { | a if f(a) => Ap::ok(t), @@ -242,25 +224,21 @@ pub mod check { } /// Reject the request if the rest of the path does not equal `path` - pub fn rest_equals( - path: A, - ) -> impl FnOnce(Ap) -> Ap - where - P: PlatformTypes, - E: core::fmt::Debug, - A: AsRef + 'static, + pub fn rest_equals(path: A) + -> impl FnOnce(Ap) -> Ap + where P: PlatformTypes, + E: core::fmt::Debug, + A: AsRef + 'static { rest_is(move |a| a == path.as_ref()) } /// Reject the request if the rest of the path does not end with `path` - pub fn ends_with( - path: A, - ) -> impl FnOnce(Ap) -> Ap - where - P: PlatformTypes, - A: AsRef + 'static, - E: core::fmt::Debug, + pub fn ends_with(path: A) + -> impl FnOnce(Ap) -> Ap + where P: PlatformTypes, + A: AsRef + 'static, + E: core::fmt::Debug { rest_is(move |a| a.ends_with(path.as_ref())) } @@ -289,12 +267,9 @@ mod tests { assert_eq!(ap_path.clone().try_unwrap_ok(), Ok("foo/bar".to_string())); - assert_eq!( - ap_path - .pipe(path::rest(|_, s| Ap::ok(s.to_string()))) - .try_unwrap_ok(), - Ok("".to_string()) - ); + assert_eq!(ap_path.pipe(path::rest(|_, s| Ap::ok(s.to_string()))) + .try_unwrap_ok(), + Ok("".to_string())); } #[test] @@ -309,9 +284,8 @@ mod tests { let fail = Hydrate::from_request(req("foot/bart")); let check = |hy| { - Ap::<_, (), ()>::ok_hydrated((), hy) - .pipe(path::check::rest_is(|p| p == "foo/bar")) - .try_unwrap_ok() + Ap::<_, (), ()>::ok_hydrated((), hy).pipe(path::check::rest_is(|p| p == "foo/bar")) + .try_unwrap_ok() }; assert!(matches!(check(pass), Ok(_))); @@ -330,9 +304,8 @@ mod tests { let fail = Hydrate::from_request(req("foot/bart")); let check = |hy| { - Ap::<_, (), ()>::ok_hydrated((), hy) - .pipe(path::check::rest_equals("foo/bar")) - .try_unwrap_ok() + Ap::<_, (), ()>::ok_hydrated((), hy).pipe(path::check::rest_equals("foo/bar")) + .try_unwrap_ok() }; assert!(matches!(check(pass), Ok(_))); @@ -351,9 +324,8 @@ mod tests { let fail = Hydrate::from_request(req("foot/bart")); let check = |hy| { - Ap::<_, (), ()>::ok_hydrated((), hy) - .pipe(path::check::ends_with("bar")) - .try_unwrap_ok() + Ap::<_, (), ()>::ok_hydrated((), hy).pipe(path::check::ends_with("bar")) + .try_unwrap_ok() }; assert!(matches!(check(pass), Ok(_))); @@ -370,16 +342,15 @@ mod tests { let hy = Hydrate::from_request(req("foot/bart")); - let ap = Ap::<_, (), ()>::ok_hydrated((), hy) - .pipe(path::segment::next(|_, s| Ap::ok(s.unwrap().to_string()))); + let ap = Ap::<_, (), ()>::ok_hydrated((), hy).pipe(path::segment::next(|_, s| { + Ap::ok(s.unwrap().to_string()) + })); assert_eq!(ap.clone().try_unwrap_ok(), Ok("foot".to_string())); - assert_eq!( - ap.pipe(path::segment::next(|_, s| Ap::ok(s.unwrap().to_string()))) - .try_unwrap_ok(), - Ok("bart".to_string()) - ); + assert_eq!(ap.pipe(path::segment::next(|_, s| Ap::ok(s.unwrap().to_string()))) + .try_unwrap_ok(), + Ok("bart".to_string())); } #[test] @@ -392,10 +363,9 @@ mod tests { let hy = Hydrate::from_request(req("users/123")); - let ap = Ap::<_, (), ()>::ok_hydrated((), hy) - .pipe(path::segment::check::next_equals("users")) - .pipe(path::segment::param::u32) - .map(|(_, u)| u); + let ap = Ap::<_, (), ()>::ok_hydrated((), hy).pipe(path::segment::check::next_equals("users")) + .pipe(path::segment::param::u32) + .map(|(_, u)| u); assert_eq!(ap.clone().try_unwrap_ok(), Ok(123)); } diff --git a/toad/src/server/respond.rs b/toad/src/server/respond.rs index c8986b58..791ecfe0 100644 --- a/toad/src/server/respond.rs +++ b/toad/src/server/respond.rs @@ -6,31 +6,26 @@ use crate::platform::PlatformTypes; /// Respond to the incoming request, with a custom code and payload. pub fn respond(code: Code, payload: P::MessagePayload) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { - Ap::respond(Respond { - code, - payload, - etag: None, - }) + Ap::respond(Respond { code, + payload, + etag: None }) } /// [`respond`] with 2.05 CONTENT pub fn ok(payload: P::MessagePayload) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { respond(crate::resp::code::CONTENT, payload) } /// [`respond`] with 4.04 NOT FOUND pub fn not_found(payload: P::MessagePayload) -> Ap -where - P: PlatformTypes, - E: core::fmt::Debug, + where P: PlatformTypes, + E: core::fmt::Debug { respond(crate::resp::code::NOT_FOUND, payload) } @@ -69,23 +64,21 @@ pub mod json { #[cfg(any(test, feature = "unstable_serde_json"))] fn ok_no_std(t: T) -> Result - where - P: PlatformTypes, - T: Serialize, + where P: PlatformTypes, + T: Serialize { use toad_array::{Filled, Trunc}; let mut p = P::MessagePayload::filled(0u8).expect("cannot combine dynamically allocated collections with no_std crate feature `unstable_serde_json`. Use `std_serde_json` instead."); serde_json_core::to_slice(&t, &mut p).map(|ct| { - p.trunc(ct); - p - }) + p.trunc(ct); + p + }) } #[cfg(feature = "std_serde_json")] fn ok_std(t: T) -> Result - where - P: PlatformTypes, - T: Serialize, + where P: PlatformTypes, + T: Serialize { serde_json::to_vec(&t).map(|v| v.into_iter().collect::()) } @@ -147,10 +140,9 @@ pub mod json { /// } /// ``` pub fn ok(t: T) -> Ap - where - E: SerializeError, - P: PlatformTypes, - T: Serialize, + where E: SerializeError, + P: PlatformTypes, + T: Serialize { #[cfg(feature = "unstable_serde_json")] let ok = ok_no_std::(t); @@ -204,10 +196,9 @@ pub mod json { #[test] fn ok_no_std_happy() { let pizza = Pizza(vec![Topping::Pepperoni]); - let pizza_bytes = serde_json::to_vec(&pizza) - .unwrap() - .into_iter() - .collect::>(); + let pizza_bytes = serde_json::to_vec(&pizza).unwrap() + .into_iter() + .collect::>(); assert_eq!(super::ok_no_std::(pizza), Ok(pizza_bytes)); } diff --git a/toad/src/std/mod.rs b/toad/src/std/mod.rs index 22bf42bb..c6eff1fb 100644 --- a/toad/src/std/mod.rs +++ b/toad/src/std/mod.rs @@ -59,13 +59,9 @@ pub mod dtls { /// implementor of [`crate::platform::PlatformTypes`] for /// platforms that support `std`. #[derive(Clone, Copy, Debug)] -pub struct PlatformTypes(PhantomData) -where - Sec: Security; +pub struct PlatformTypes(PhantomData) where Sec: Security; -impl crate::platform::PlatformTypes for PlatformTypes -where - Sec: Security, +impl crate::platform::PlatformTypes for PlatformTypes where Sec: Security { type MessagePayload = Vec; type MessageOptionBytes = Vec; @@ -77,9 +73,8 @@ where } impl PlatformError for io::Error -where - StepError: Debug, - SocketError: Debug, + where StepError: Debug, + SocketError: Debug { fn msg_to_bytes(e: toad_msg::to_bytes::MessageToBytesError) -> Self { io::Error::new(io::ErrorKind::InvalidData, format!("{:?}", e)) @@ -101,8 +96,7 @@ where /// implementor of [`crate::platform::Platform`] for `std` #[derive(Debug)] pub struct Platform -where - Sec: Security, + where Sec: Security { steps: Steps, config: crate::config::Config, @@ -111,60 +105,47 @@ where } impl Platform -where - Sec: Security, - Steps: Step< - PlatformTypes, - PollReq = Addrd>>, - PollResp = Addrd>>, - >, + where Sec: Security, + Steps: Step, + PollReq = Addrd>>, + PollResp = Addrd>>> { /// Create a new std runtime - pub fn try_new( - addr: A, - cfg: crate::config::Config, - ) -> io::Result - where - Steps: Default, + pub fn try_new(addr: A, + cfg: crate::config::Config) + -> io::Result + where Steps: Default { fn first_addr(a: A_) -> io::Result { let yielded_no_addrs = || { - io::Error::new( - io::ErrorKind::InvalidInput, - "socket addr yielded 0 addresses", - ) + io::Error::new(io::ErrorKind::InvalidInput, + "socket addr yielded 0 addresses") }; a.to_socket_addrs() - .and_then(|mut a| a.next().ok_or_else(yielded_no_addrs)) + .and_then(|mut a| a.next().ok_or_else(yielded_no_addrs)) } let socket_error = ::Error>>::socket; - first_addr(addr) - .map(|a| { - use net::convert::{no_std, std}; - no_std::SockAddr::from(std::SockAddr(a)).0 - }) - .and_then(|a| Sec::Socket::bind(a).map_err(socket_error)) - .map(|socket| Self { - steps: Steps::default(), - config: cfg, - socket, - clock: Clock::new(), - }) + first_addr(addr).map(|a| { + use net::convert::{no_std, std}; + no_std::SockAddr::from(std::SockAddr(a)).0 + }) + .and_then(|a| Sec::Socket::bind(a).map_err(socket_error)) + .map(|socket| Self { steps: Steps::default(), + config: cfg, + socket, + clock: Clock::new() }) } } impl crate::platform::Platform for Platform -where - Sec: Security, - Steps: Step< - PlatformTypes, - PollReq = Addrd>>, - PollResp = Addrd>>, - >, + where Sec: Security, + Steps: Step, + PollReq = Addrd>>, + PollResp = Addrd>>> { type Types = PlatformTypes; type Error = io::Error; diff --git a/toad/src/std/net/convert.rs b/toad/src/std/net/convert.rs index 6aefd123..78504c6b 100644 --- a/toad/src/std/net/convert.rs +++ b/toad/src/std/net/convert.rs @@ -49,21 +49,17 @@ pub(crate) mod std { impl From for no_std::SockAddrv4 { fn from(other: SockAddrv4) -> no_std::SockAddrv4 { - no_std::SockAddrv4(no_std_net::SocketAddrV4::new( - no_std::Ipv4::from(Ipv4(*other.0.ip())).0, - other.0.port(), - )) + no_std::SockAddrv4(no_std_net::SocketAddrV4::new(no_std::Ipv4::from(Ipv4(*other.0.ip())).0, + other.0.port())) } } impl From for no_std::SockAddrv6 { fn from(other: SockAddrv6) -> no_std::SockAddrv6 { - no_std::SockAddrv6(no_std_net::SocketAddrV6::new( - no_std::Ipv6::from(Ipv6(*other.0.ip())).0, - other.0.port(), - other.0.flowinfo(), - other.0.scope_id(), - )) + no_std::SockAddrv6(no_std_net::SocketAddrV6::new(no_std::Ipv6::from(Ipv6(*other.0.ip())).0, + other.0.port(), + other.0.flowinfo(), + other.0.scope_id())) } } @@ -134,21 +130,17 @@ pub(crate) mod no_std { impl From for yes_std::SockAddrv4 { fn from(other: SockAddrv4) -> yes_std::SockAddrv4 { - yes_std::SockAddrv4(std::net::SocketAddrV4::new( - yes_std::Ipv4::from(Ipv4(*other.0.ip())).0, - other.0.port(), - )) + yes_std::SockAddrv4(std::net::SocketAddrV4::new(yes_std::Ipv4::from(Ipv4(*other.0.ip())).0, + other.0.port())) } } impl From for yes_std::SockAddrv6 { fn from(other: SockAddrv6) -> yes_std::SockAddrv6 { - yes_std::SockAddrv6(std::net::SocketAddrV6::new( - yes_std::Ipv6::from(Ipv6(*other.0.ip())).0, - other.0.port(), - other.0.flowinfo(), - other.0.scope_id(), - )) + yes_std::SockAddrv6(std::net::SocketAddrV6::new(yes_std::Ipv6::from(Ipv6(*other.0.ip())).0, + other.0.port(), + other.0.flowinfo(), + other.0.scope_id())) } } impl From for yes_std::Ip { diff --git a/toad/src/std/net/mod.rs b/toad/src/std/net/mod.rs index fcc9ae5d..bc7560c5 100644 --- a/toad/src/std/net/mod.rs +++ b/toad/src/std/net/mod.rs @@ -21,33 +21,28 @@ impl Socket for UdpSocket { } fn send(&self, msg: Addrd<&[u8]>) -> nb::Result<(), Self::Error> { - self - .set_nonblocking(true) - .bind(|_| { - UdpSocket::send_to::( - self, - msg.data(), - convert::no_std::SockAddr(msg.addr()).into(), - ) - }) - .map(|_| ()) - .map_err(convert::io_to_nb) + self.set_nonblocking(true) + .bind(|_| { + UdpSocket::send_to::(self, + msg.data(), + convert::no_std::SockAddr(msg.addr()).into()) + }) + .map(|_| ()) + .map_err(convert::io_to_nb) } fn recv(&self, buffer: &mut [u8]) -> nb::Result, Self::Error> { self.set_nonblocking(true).unwrap(); - self - .recv_from(buffer) - .map(|(n, addr)| Addrd(n, convert::std::SockAddr(addr).into())) - .map_err(convert::io_to_nb) + self.recv_from(buffer) + .map(|(n, addr)| Addrd(n, convert::std::SockAddr(addr).into())) + .map_err(convert::io_to_nb) } fn bind_raw(addr: A) -> Result { - let addrs = addr - .to_socket_addrs() - .unwrap() - .map(|no_std| convert::no_std::SockAddr(no_std).into()) - .collect::>(); + let addrs = addr.to_socket_addrs() + .unwrap() + .map(|no_std| convert::no_std::SockAddr(no_std).into()) + .collect::>(); UdpSocket::bind(addrs.as_slice()).discard(|s: &UdpSocket| Ok(s.set_nonblocking(true).unwrap())) } @@ -62,14 +57,13 @@ impl Socket for UdpSocket { } fn peek(&self, buffer: &mut [u8]) -> nb::Result, Self::Error> { - std::net::UdpSocket::peek_from(self, buffer) - .map(|(n, addr)| { - Addrd( + std::net::UdpSocket::peek_from(self, buffer).map(|(n, addr)| { + Addrd( n, convert::no_std::SockAddr::from(convert::std::SockAddr(addr)).0, ) - }) - .map_err(convert::io_to_nb) + }) + .map_err(convert::io_to_nb) } fn empty_dgram() -> Self::Dgram { diff --git a/toad/src/std/net/secure.rs b/toad/src/std/net/secure.rs index ec0080c6..afd18c61 100644 --- a/toad/src/std/net/secure.rs +++ b/toad/src/std/net/secure.rs @@ -7,10 +7,15 @@ use std::ops::{Deref, DerefMut}; use std::sync::{Arc, Mutex}; use naan::prelude::{Monad, MonadOnce, ResultExt}; -use openssl::ssl::{ - ConnectConfiguration, MidHandshakeSslStream, Ssl, SslAcceptor, SslAcceptorBuilder, SslConnector, - SslContext, SslMethod, SslMode, -}; +use openssl::ssl::{ConnectConfiguration, + MidHandshakeSslStream, + Ssl, + SslAcceptor, + SslAcceptorBuilder, + SslConnector, + SslContext, + SslMethod, + SslMode}; use tinyvec::ArrayVec; use toad_array::Array; @@ -66,10 +71,9 @@ mod error { match self { | Self::Io(io) if io.kind() == std::io::ErrorKind::WouldBlock => nb::Error::WouldBlock, | Self::Ssl(e) - if e - .io_error() - .map(|io| io.kind() == std::io::ErrorKind::WouldBlock) - .unwrap_or_default() => + if e.io_error() + .map(|io| io.kind() == std::io::ErrorKind::WouldBlock) + .unwrap_or_default() => { nb::Error::WouldBlock }, @@ -145,12 +149,10 @@ pub mod conn { impl UdpConn { pub(in crate::std) fn new(sock: Arc, addr: no_std_net::SocketAddr) -> Self { - Self { - sock, - addr, - handshake_state: HandshakeState::NotStarted, - tx_buf: vec![], - } + Self { sock, + addr, + handshake_state: HandshakeState::NotStarted, + tx_buf: vec![] } } pub(in crate::std) fn handshake_done(&mut self) { @@ -175,10 +177,8 @@ pub mod conn { match self.handshake_state { // See above comment for why we block here - | HandshakeState::NotStarted => todo::nb::block!( - sock_ref.peek_addr(), - io_timeout_after = Duration::from_secs(5) - ), + | HandshakeState::NotStarted => todo::nb::block!(sock_ref.peek_addr(), + io_timeout_after = Duration::from_secs(5)), // If we're not negotiating DTLS anymore, proceed as a normal // non-blocking connection | HandshakeState::Done => sock_ref.peek_addr().map_err(nb_to_io), @@ -194,28 +194,26 @@ pub mod conn { fn flush(&mut self) -> io::Result<()> { let tx = Addrd(self.tx_buf.as_slice(), self.addr); - Socket::send(self.sock.as_ref(), tx) - .perform_nb_err(|_| self.tx_buf.clear()) - .discard(|_: &()| Ok(self.tx_buf.clear())) - .map_err(nb_to_io) + Socket::send(self.sock.as_ref(), tx).perform_nb_err(|_| self.tx_buf.clear()) + .discard(|_: &()| Ok(self.tx_buf.clear())) + .map_err(nb_to_io) } } impl io::Read for UdpConn { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self - .peek() - .bind1(|rx_addr: SocketAddr| { - if rx_addr == self.addr { - let recv = Socket::recv(self.sock.as_ref(), buf); - recv.expect_nonblocking("toad::std::net::UdpConn::peek lied!") - } else { - // The message in the socket is for someone else, - // so we should yield - Err(io::Error::from(io::ErrorKind::WouldBlock)) - } - }) - .map(|Addrd(n, _)| n) + self.peek() + .bind1(|rx_addr: SocketAddr| { + if rx_addr == self.addr { + let recv = Socket::recv(self.sock.as_ref(), buf); + recv.expect_nonblocking("toad::std::net::UdpConn::peek lied!") + } else { + // The message in the socket is for someone else, + // so we should yield + Err(io::Error::from(io::ErrorKind::WouldBlock)) + } + }) + .map(|Addrd(n, _)| n) } } @@ -248,34 +246,31 @@ impl core::fmt::Debug for SecureUdpSocket { } impl SecureUdpSocket { - fn new_acceptor( - private_key: openssl::pkey::PKey, - cert: openssl::x509::X509, - ) -> Result { + fn new_acceptor(private_key: openssl::pkey::PKey, + cert: openssl::x509::X509) + -> Result { let builder = SslAcceptor::mozilla_intermediate_v5(SslMethod::dtls()); - builder - .discard(|_: &SslAcceptorBuilder| Ok(log::trace!("set private key"))) - .try_perform_mut(|builder| builder.set_private_key(&private_key)) - .discard(|_: &SslAcceptorBuilder| Ok(log::trace!("set cert"))) - .try_perform_mut(|builder| builder.set_certificate(&cert)) - .map(|builder| builder.build()) - .map_err(Into::into) - .discard(|_: &SslAcceptor| Ok(log::trace!("new acceptor created"))) + builder.discard(|_: &SslAcceptorBuilder| Ok(log::trace!("set private key"))) + .try_perform_mut(|builder| builder.set_private_key(&private_key)) + .discard(|_: &SslAcceptorBuilder| Ok(log::trace!("set cert"))) + .try_perform_mut(|builder| builder.set_certificate(&cert)) + .map(|builder| builder.build()) + .map_err(Into::into) + .discard(|_: &SslAcceptor| Ok(log::trace!("new acceptor created"))) } fn new_connector() -> Result { let builder = SslConnector::builder(SslMethod::dtls()); - builder - .map(|mut builder| { - let prev_mode = builder.set_mode(SslMode::all()); - let mode = prev_mode & !SslMode::ENABLE_PARTIAL_WRITE; - builder.set_mode(mode); + builder.map(|mut builder| { + let prev_mode = builder.set_mode(SslMode::all()); + let mode = prev_mode & !SslMode::ENABLE_PARTIAL_WRITE; + builder.set_mode(mode); - builder.build() - }) - .map_err(Into::into) - .discard(|_: &SslConnector| Ok(log::trace!("new connector created"))) + builder.build() + }) + .map_err(Into::into) + .discard(|_: &SslConnector| Ok(log::trace!("new connector created"))) } /// Create a new secure socket for a server @@ -287,11 +282,9 @@ impl SecureUdpSocket { /// instead, as it comes with sensible secure defaults. pub fn new_server(ssl: SslAcceptor, sock: UdpSocket) -> Self { sock.set_nonblocking(true).unwrap(); - Self { - sock: Arc::new(sock), - ssl: SslRole::Server(ssl.into_context()), - conns: Default::default(), - } + Self { sock: Arc::new(sock), + ssl: SslRole::Server(ssl.into_context()), + conns: Default::default() } } /// Create a new secure socket for a client @@ -303,11 +296,9 @@ impl SecureUdpSocket { /// instead, as it comes with sensible secure defaults. pub fn new_client(ssl: SslConnector, sock: UdpSocket) -> Self { sock.set_nonblocking(true).unwrap(); - Self { - sock: Arc::new(sock), - ssl: SslRole::Client(ssl), - conns: Default::default(), - } + Self { sock: Arc::new(sock), + ssl: SslRole::Client(ssl), + conns: Default::default() } } /// Create a new secure socket for a server @@ -317,11 +308,10 @@ impl SecureUdpSocket { /// /// This will configure openssl to use many sensible defaults, /// such as [Mozilla's recommended server-side TLS configuration](`openssl::ssl::SslAcceptor::mozilla_intermediate_v5`) - pub fn try_new_server( - sock: UdpSocket, - private_key: openssl::pkey::PKey, - cert: openssl::x509::X509, - ) -> Result { + pub fn try_new_server(sock: UdpSocket, + private_key: openssl::pkey::PKey, + cert: openssl::x509::X509) + -> Result { let ssl = Self::new_acceptor(private_key, cert); ssl.map(|ssl| Self::new_server(ssl, sock)) } @@ -337,149 +327,123 @@ impl SecureUdpSocket { ssl.map(|ssl| Self::new_client(ssl, sock)) } - fn connect( - ssl: &SslRole, - sock: Arc, - conns: &mut Connections, - addr: no_std_net::SocketAddr, - ) -> nb::Result, Error> { + fn connect(ssl: &SslRole, + sock: Arc, + conns: &mut Connections, + addr: no_std_net::SocketAddr) + -> nb::Result, Error> { let conn = conn::UdpConn::new(sock, addr); match ssl { | SslRole::Client(connector) => { - connector - .configure() - .map_err(Error::from) - .map_err(Error::into_nb) - .perform_nb_err(|e| log::error!("configure connector failed: {:?}", e)) - .bind1(|conf: ConnectConfiguration| { - // TODO: can these be enabled? - conf - .verify_hostname(false) - .use_server_name_indication(false) - .into_ssl("") - .map_err(Error::from) - .bind1(|ssl: Ssl| ssl.connect(conn).map_err(Error::from)) - .discard_mut(|stream: &mut SslStream| Ok(stream.get_mut().handshake_done())) - .map_err(Error::into_nb) - }) - .perform_nb_err(|e| log::error!("connect failed: {:?}", e)) + connector.configure() + .map_err(Error::from) + .map_err(Error::into_nb) + .perform_nb_err(|e| log::error!("configure connector failed: {:?}", e)) + .bind1(|conf: ConnectConfiguration| { + // TODO: can these be enabled? + conf.verify_hostname(false) + .use_server_name_indication(false) + .into_ssl("") + .map_err(Error::from) + .bind1(|ssl: Ssl| ssl.connect(conn).map_err(Error::from)) + .discard_mut(|stream: &mut SslStream| Ok(stream.get_mut().handshake_done())) + .map_err(Error::into_nb) + }) + .perform_nb_err(|e| log::error!("connect failed: {:?}", e)) }, | SslRole::Server(_) => { - log::error!( - "{}", - [ - "SecureUdpSocket::connect", - "called in server mode.", - "This is a bug in `toad`", - "and should be filed as an issue." - ] - .join(" ") - ); + log::error!("{}", + ["SecureUdpSocket::connect", + "called in server mode.", + "This is a bug in `toad`", + "and should be filed as an issue."].join(" ")); let not_found = Error::ConnectionNotFound; Err(not_found.into()) }, - } - .map(conn::SecureUdpConn::Established) - .recover(|e| match e { - | nb::Error::Other(Error::WouldBlockMidHandshake(e)) => { - Ok(e).map(conn::SecureUdpConn::Establishing) - }, - | e => Err(e), - }) - .map(Mutex::new) - .map(Arc::new) - .discard(|conn: &Arc>| { - conns.insert(addr, conn.clone()); - Ok(()) - }) - } - - fn accept( - ssl: &SslRole, - sock: Arc, - conns: &mut Connections, - addr: no_std_net::SocketAddr, - ) -> nb::Result, Error> { + }.map(conn::SecureUdpConn::Established) + .recover(|e| match e { + | nb::Error::Other(Error::WouldBlockMidHandshake(e)) => { + Ok(e).map(conn::SecureUdpConn::Establishing) + }, + | e => Err(e), + }) + .map(Mutex::new) + .map(Arc::new) + .discard(|conn: &Arc>| { + conns.insert(addr, conn.clone()); + Ok(()) + }) + } + + fn accept(ssl: &SslRole, + sock: Arc, + conns: &mut Connections, + addr: no_std_net::SocketAddr) + -> nb::Result, Error> { let conn = conn::UdpConn::new(sock, addr); let client_uh_oh = || { let not_found = Error::ConnectionNotFound; - log::error!( - "{}", - [ - "SecureUdpSocket::accept", - "called in client mode.", - "This is a bug in `toad`", - "and should be filed as an issue." - ] - .join(" ") - ); + log::error!("{}", + ["SecureUdpSocket::accept", + "called in client mode.", + "This is a bug in `toad`", + "and should be filed as an issue."].join(" ")); Err(not_found.into()) }; let try_accept = |ctx| { - Ssl::new(ctx) - .map_err(Error::from) - .bind1(|ssl: Ssl| ssl.accept(conn).map_err(Error::from)) - .map_err(Error::into_nb) - .perform_nb_err(|e| log::error!("accept failed: {:?}", e)) + Ssl::new(ctx).map_err(Error::from) + .bind1(|ssl: Ssl| ssl.accept(conn).map_err(Error::from)) + .map_err(Error::into_nb) + .perform_nb_err(|e| log::error!("accept failed: {:?}", e)) }; match ssl { | SslRole::Server(ctx) => try_accept(ctx), | SslRole::Client(_) => client_uh_oh(), - } - .map(conn::SecureUdpConn::Established) - .recover(|e| match e { - | nb::Error::Other(Error::WouldBlockMidHandshake(e)) => { - Ok(e).map(conn::SecureUdpConn::Establishing) - }, - | e => Err(e), - }) - .map(Mutex::new) - .map(Arc::new) - .discard(|conn: &Arc>| { - conns.insert(addr, conn.clone()); - Ok(()) - }) - } - - pub(crate) fn get_conn_or_connect( - &self, - addr: no_std_net::SocketAddr, - ) -> Result> { + }.map(conn::SecureUdpConn::Established) + .recover(|e| match e { + | nb::Error::Other(Error::WouldBlockMidHandshake(e)) => { + Ok(e).map(conn::SecureUdpConn::Establishing) + }, + | e => Err(e), + }) + .map(Mutex::new) + .map(Arc::new) + .discard(|conn: &Arc>| { + conns.insert(addr, conn.clone()); + Ok(()) + }) + } + + pub(crate) fn get_conn_or_connect(&self, + addr: no_std_net::SocketAddr) + -> Result> { match self.get_conn(addr) { | Some(conn) => Ok(conn), - | None => Self::connect( - &self.ssl, - self.sock.clone(), - &mut self.conns.lock().unwrap(), - addr, - ) - .map_err(Error::from), + | None => Self::connect(&self.ssl, + self.sock.clone(), + &mut self.conns.lock().unwrap(), + addr).map_err(Error::from), } } - pub(crate) fn get_conn_or_accept( - &self, - addr: no_std_net::SocketAddr, - ) -> Result> { + pub(crate) fn get_conn_or_accept(&self, + addr: no_std_net::SocketAddr) + -> Result> { match self.get_conn(addr) { | Some(conn) => Ok(conn), - | None => Self::accept( - &self.ssl, - self.sock.clone(), - &mut self.conns.lock().unwrap(), - addr, - ) - .map_err(Error::from), + | None => Self::accept(&self.ssl, + self.sock.clone(), + &mut self.conns.lock().unwrap(), + addr).map_err(Error::from), } } - pub(crate) fn get_conn( - &self, - addr: no_std_net::SocketAddr, - ) -> Option> { + pub(crate) fn get_conn(&self, + addr: no_std_net::SocketAddr) + -> Option> { let conns = self.conns.lock().unwrap(); conns.get(&addr).cloned() } @@ -495,32 +459,31 @@ impl SecureUdpSocket { let mid = self.conns.lock().unwrap().remove(&addr).unwrap(); - Arc::try_unwrap(mid) - .map_err(|_| { - // We do not have exclusive access, - // meaning that another thread - // is currently continuing the handshake. - Error::WouldBlock - }) - .map(|mutex| mutex.into_inner().unwrap()) - .map(|mid| match mid { - | conn::SecureUdpConn::Established(_) => unreachable!(), - | conn::SecureUdpConn::Establishing(e) => e, - }) - .map(|mid| match mid.handshake().map_err(Error::from) { - | Ok(_) => todo!(), - | Err(e) => match e { - | Error::WouldBlockMidHandshake(e) => { - self.conns.lock().unwrap().insert( + Arc::try_unwrap(mid).map_err(|_| { + // We do not have exclusive access, + // meaning that another thread + // is currently continuing the handshake. + Error::WouldBlock + }) + .map(|mutex| mutex.into_inner().unwrap()) + .map(|mid| match mid { + | conn::SecureUdpConn::Established(_) => unreachable!(), + | conn::SecureUdpConn::Establishing(e) => e, + }) + .map(|mid| match mid.handshake().map_err(Error::from) { + | Ok(_) => todo!(), + | Err(e) => match e { + | Error::WouldBlockMidHandshake(e) => { + self.conns.lock().unwrap().insert( addr, Arc::new(Mutex::new(conn::SecureUdpConn::Establishing(e))), ); - Error::WouldBlock - }, - | e => e, - }, - }) - .unwrap_err_or(|_| Error::WouldBlock) + Error::WouldBlock + }, + | e => e, + }, + }) + .unwrap_err_or(|_| Error::WouldBlock) } } @@ -541,76 +504,72 @@ impl Socket for SecureUdpSocket { } fn send(&self, msg: Addrd<&[u8]>) -> nb::Result<(), Self::Error> { - self - .get_conn_or_connect(msg.addr()) - .bind(|stream: Arc>| { - let mut lock = stream.lock().unwrap(); - match DerefMut::deref_mut(&mut lock) { - | conn::SecureUdpConn::Established(stream) => stream - .ssl_write(msg.data()) - .map_err(Error::from) - .bind1(|_: usize| stream.flush().map_err(Error::from)), - | conn::SecureUdpConn::Establishing(_) => Err(self.restart_handshake(msg.addr())), - } - }) - .map_err(Error::into_nb) - .perform_nb_err(|e| log::error!("{:?}", e)) + self.get_conn_or_connect(msg.addr()) + .bind(|stream: Arc>| { + let mut lock = stream.lock().unwrap(); + match DerefMut::deref_mut(&mut lock) { + | conn::SecureUdpConn::Established(stream) => { + stream.ssl_write(msg.data()) + .map_err(Error::from) + .bind1(|_: usize| stream.flush().map_err(Error::from)) + }, + | conn::SecureUdpConn::Establishing(_) => Err(self.restart_handshake(msg.addr())), + } + }) + .map_err(Error::into_nb) + .perform_nb_err(|e| log::error!("{:?}", e)) } fn insecure_send(&self, msg: Addrd<&[u8]>) -> nb::Result<(), Self::Error> { - Socket::send(self.sock.as_ref(), msg) - .map_err(|e| e.map(Error::from)) - .perform_nb_err(|e| log::error!("{:?}", e)) + Socket::send(self.sock.as_ref(), msg).map_err(|e| e.map(Error::from)) + .perform_nb_err(|e| log::error!("{:?}", e)) } fn recv(&self, buffer: &mut [u8]) -> nb::Result, Self::Error> { - self - .sock - .peek_addr() - .map_err(convert::nb_to_io) - .map_err(Error::from) - .bind1(|addr| self.get_conn_or_accept(addr).map(|conn| Addrd(conn, addr))) - .bind1(|Addrd(conn, addr): Addrd>>| { - let mut lock = conn.lock().unwrap(); - match DerefMut::deref_mut(&mut lock) { - | conn::SecureUdpConn::Established(conn) => conn - .ssl_read(buffer) - .map(|n| Addrd(n, addr)) - .map_err(Error::from), - | conn::SecureUdpConn::Establishing(_) => Err(self.restart_handshake(addr)), - } - }) - .map_err(Error::into_nb) - .perform_nb_err(|e| log::error!("{:?}", e)) + self.sock + .peek_addr() + .map_err(convert::nb_to_io) + .map_err(Error::from) + .bind1(|addr| self.get_conn_or_accept(addr).map(|conn| Addrd(conn, addr))) + .bind1(|Addrd(conn, addr): Addrd>>| { + let mut lock = conn.lock().unwrap(); + match DerefMut::deref_mut(&mut lock) { + | conn::SecureUdpConn::Established(conn) => conn.ssl_read(buffer) + .map(|n| Addrd(n, addr)) + .map_err(Error::from), + | conn::SecureUdpConn::Establishing(_) => Err(self.restart_handshake(addr)), + } + }) + .map_err(Error::into_nb) + .perform_nb_err(|e| log::error!("{:?}", e)) } fn peek(&self, buffer: &mut [u8]) -> nb::Result, Self::Error> { - self - .conns - .lock() - .unwrap() - .iter_mut() - .find_map(|(addr, conn)| { - match conn - .lock() - .unwrap() - .stream() - .map(|stream| stream.ssl_peek(buffer)) - { - | None | Some(Ok(0)) => None, - | Some(Ok(n)) => Some(Ok(Addrd(n, *addr))), - | Some(Err(err)) => { - let err = Error::from(err).into_nb(); - Some(Err(err).perform_nb_err(|e| log::error!("{:?}", e))) - }, - } - }) - .unwrap_or(Err(nb::Error::WouldBlock)) + self.conns + .lock() + .unwrap() + .iter_mut() + .find_map(|(addr, conn)| { + match conn.lock() + .unwrap() + .stream() + .map(|stream| stream.ssl_peek(buffer)) + { + | None | Some(Ok(0)) => None, + | Some(Ok(n)) => Some(Ok(Addrd(n, *addr))), + | Some(Err(err)) => { + let err = Error::from(err).into_nb(); + Some(Err(err).perform_nb_err(|e| log::error!("{:?}", e))) + }, + } + }) + .unwrap_or(Err(nb::Error::WouldBlock)) } /// Multicast and SSL are incompatible, so this always returns `Err(io::ErrorKind::Unsupported)`. fn join_multicast(&self, _: no_std_net::IpAddr) -> Result<()> { - Err(io::Error::from(io::ErrorKind::Unsupported).into()) - .discard_err(|e: &Error| log::error!("{:?}", e)) + Err(io::Error::from(io::ErrorKind::Unsupported).into()).discard_err(|e: &Error| { + log::error!("{:?}", e) + }) } } diff --git a/toad/src/step/ack.rs b/toad/src/step/ack.rs index dc80415f..50591462 100644 --- a/toad/src/step/ack.rs +++ b/toad/src/step/ack.rs @@ -41,20 +41,16 @@ impl, PollResp = InnerPollResp

>, P: &self.0 } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput { + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> StepOutput { match exec_inner_step!(self.0.poll_req(snap, effects), core::convert::identity) { | Some(req) if req.data().as_ref().ty == Type::Con - && req.data().as_ref().code.kind() == CodeKind::Request => + && req.data().as_ref().code.kind() == CodeKind::Request => { - effects.push(Effect::Send(Addrd( - Resp::ack(req.as_ref().data()).into(), - req.addr(), - ))); + effects.push(Effect::Send(Addrd(Resp::ack(req.as_ref().data()).into(), req.addr()))); Some(Ok(req)) }, | Some(req) => Some(Ok(req)), @@ -62,18 +58,14 @@ impl, PollResp = InnerPollResp

>, P: } } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput { - exec_inner_step!( - self.0.poll_resp(snap, effects, token, addr), - core::convert::identity - ) - .map(Ok) + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput { + exec_inner_step!(self.0.poll_resp(snap, effects, token, addr), + core::convert::identity).map(Ok) } } @@ -91,32 +83,23 @@ mod test { type InnerPollReq = super::InnerPollReq; type InnerPollResp = super::InnerPollResp; - fn test_msg( - ty: Type, - code: Code, - ) -> ( - Addrd>, - Addrd>, - ) { + fn test_msg(ty: Type, + code: Code) + -> (Addrd>, Addrd>) { use toad_msg::*; type Msg = platform::Message; - let msg = Msg { - id: Id(1), - ty, - ver: Default::default(), - token: Token(Default::default()), - code, - opts: Default::default(), - payload: Payload(Default::default()), - }; + let msg = Msg { id: Id(1), + ty, + ver: Default::default(), + token: Token(Default::default()), + code, + opts: Default::default(), + payload: Payload(Default::default()) }; let addr = crate::test::dummy_addr(); - ( - Addrd(Req::<_>::from(msg.clone()), addr), - Addrd(Resp::<_>::from(msg), addr), - ) + (Addrd(Req::<_>::from(msg.clone()), addr), Addrd(Resp::<_>::from(msg), addr)) } test::test_step!( diff --git a/toad/src/step/buffer_responses.rs b/toad/src/step/buffer_responses.rs index c2540a99..563d6a8a 100644 --- a/toad/src/step/buffer_responses.rs +++ b/toad/src/step/buffer_responses.rs @@ -27,33 +27,23 @@ pub struct BufferResponses { impl Default for BufferResponses { fn default() -> Self { - Self { - buffer: Default::default(), - inner: S::default(), - } + Self { buffer: Default::default(), + inner: S::default() } } } impl BufferResponses { fn store

(&self, resp: Addrd>) - where - P: PlatformTypes, - B: Map<(SocketAddr, Token, Type), Addrd>>, + where P: PlatformTypes, + B: Map<(SocketAddr, Token, Type), Addrd>> { let mut resp_removable = Some(resp); self.buffer.map_mut(|buf| { - let resp = Option::take(&mut resp_removable).unwrap(); - buf - .insert( - ( - resp.addr(), - resp.data().as_ref().token, - resp.data().as_ref().ty, - ), - resp, - ) - .ok() - }); + let resp = Option::take(&mut resp_removable).unwrap(); + buf.insert((resp.addr(), resp.data().as_ref().token, resp.data().as_ref().ty), + resp) + .ok() + }); } } @@ -90,12 +80,11 @@ impl core::fmt::Debug for Error { impl super::Error for Error {} -impl< - P: PlatformTypes, - B: Map<(SocketAddr, Token, Type), Addrd>>, - E: super::Error, - S: Step>, PollResp = Addrd>, Error = E>, - > Step

for BufferResponses +impl>>, + E: super::Error, + S: Step>, PollResp = Addrd>, Error = E>> Step

+ for BufferResponses { type PollReq = Addrd>; type PollResp = Addrd>; @@ -106,28 +95,23 @@ impl< &self.inner } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput { - self - .inner - .poll_req(snap, effects) - .map(|o| o.map_err(|e| e.map(Error::Inner))) + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> StepOutput { + self.inner + .poll_req(snap, effects) + .map(|o| o.map_err(|e| e.map(Error::Inner))) } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput { - let resp = exec_inner_step!( - self.inner.poll_resp(snap, effects, token, addr), - Error::Inner - ); + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput { + let resp = exec_inner_step!(self.inner.poll_resp(snap, effects, token, addr), + Error::Inner); if self.buffer.map_ref(Len::is_full) { return Some(Err(nb::Error::Other(Error::BufferResponsesFull))); @@ -143,20 +127,16 @@ impl< | Some(resp) if is_what_we_polled_for(&resp) => Some(Ok(resp)), | Some(resp) => { let mut msg = String::<1000>::default(); - write!( - &mut msg, - "polled for response to {:?}, got response with token {:?}", - token, - resp.data().token() - ) - .ok(); + write!(&mut msg, + "polled for response to {:?}, got response with token {:?}", + token, + resp.data().token()).ok(); effects.push(Effect::Log(log::Level::Info, msg)); self.store(resp); - match try_remove_from_buffer(Type::Ack) - .or_else(|| try_remove_from_buffer(Type::Con)) - .or_else(|| try_remove_from_buffer(Type::Non)) - .or_else(|| try_remove_from_buffer(Type::Reset)) + match try_remove_from_buffer(Type::Ack).or_else(|| try_remove_from_buffer(Type::Con)) + .or_else(|| try_remove_from_buffer(Type::Non)) + .or_else(|| try_remove_from_buffer(Type::Reset)) { | Some(resp) => Some(Ok(resp)), | None => Some(Err(nb::Error::WouldBlock)), diff --git a/toad/src/step/handle_acks.rs b/toad/src/step/handle_acks.rs index 6857ad72..d6a423c6 100644 --- a/toad/src/step/handle_acks.rs +++ b/toad/src/step/handle_acks.rs @@ -27,10 +27,8 @@ pub struct HandleAcks { impl Default for HandleAcks { fn default() -> Self { - Self { - buffer: Default::default(), - inner: S::default(), - } + Self { buffer: Default::default(), + inner: S::default() } } } @@ -112,12 +110,11 @@ macro_rules! common { }}; } -impl< - P: PlatformTypes, - B: Map, ()> + core::fmt::Debug, - E: super::Error, - S: Step>, PollResp = Addrd>, Error = E>, - > Step

for HandleAcks +impl, ()> + core::fmt::Debug, + E: super::Error, + S: Step>, PollResp = Addrd>, Error = E>> Step

+ for HandleAcks { type PollReq = Addrd>; type PollResp = Addrd>; @@ -128,11 +125,10 @@ impl< &self.inner } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput { + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> StepOutput { let req = exec_inner_step!(self.inner.poll_req(snap, effects), Error::Inner); match req { @@ -144,17 +140,14 @@ impl< } } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput { - let resp = exec_inner_step!( - self.inner.poll_resp(snap, effects, token, addr), - Error::Inner - ); + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput { + let resp = exec_inner_step!(self.inner.poll_resp(snap, effects, token, addr), + Error::Inner); match resp { | Some(resp) => { @@ -165,29 +158,26 @@ impl< } } - fn on_message_sent( - &self, - snap: &platform::Snapshot

, - effects: &mut P::Effects, - msg: &Addrd>, - ) -> Result<(), Self::Error> { - self - .inner - .on_message_sent(snap, effects, msg) - .map_err(Error::Inner)?; + fn on_message_sent(&self, + snap: &platform::Snapshot

, + effects: &mut P::Effects, + msg: &Addrd>) + -> Result<(), Self::Error> { + self.inner + .on_message_sent(snap, effects, msg) + .map_err(Error::Inner)?; match msg.data().ty { - | Type::Con => self - .buffer - .map_mut(|buf| buf.insert(msg.as_ref().map(|m| m.token), ())) - .recover(|e| { - if matches!(e, InsertError::Exists(_)) { - Ok(()) - } else { - Err(e) - } - }) - .map_err(|_| Error::ConBufferCapacityExhausted), + | Type::Con => self.buffer + .map_mut(|buf| buf.insert(msg.as_ref().map(|m| m.token), ())) + .recover(|e| { + if matches!(e, InsertError::Exists(_)) { + Ok(()) + } else { + Err(e) + } + }) + .map_err(|_| Error::ConBufferCapacityExhausted), | _ => Ok(()), } } @@ -212,18 +202,14 @@ mod test { fn test_message(ty: Type) -> Addrd { use toad_msg::*; - Addrd( - test::Message { - ver: Default::default(), - ty, - id: Id(1), - code: Code::new(0, 1), - token: Token(array_vec!(_ => 1)), - payload: Payload(Default::default()), - opts: Default::default(), - }, - test::dummy_addr(), - ) + Addrd(test::Message { ver: Default::default(), + ty, + id: Id(1), + code: Code::new(0, 1), + token: Token(array_vec!(_ => 1)), + payload: Payload(Default::default()), + opts: Default::default() }, + test::dummy_addr()) } test_step!( @@ -291,32 +277,27 @@ mod test { let sut = HandleAcks::::default(); - sut - .inner() - .init(TestState { - token_last_sent: None, - }) - .set_on_message_sent(|mock, _, _, msg| { - mock - .state - .map_mut(|s| s.as_mut().unwrap().token_last_sent = Some(msg.data().token)); - Ok(()) - }) - .set_poll_resp(|mock, _, _, poll_for_token, _| { - let mut msg = test::msg!(ACK {2 . 05} x.x.x.x:2222); - - let token = mock - .state - .map_ref(|s| s.as_ref().unwrap().token_last_sent.unwrap()); - Addrd::data_mut(&mut msg).token = token; - - assert_eq!(token, poll_for_token); - - let p = Payload(format!("oink oink!").bytes().collect::>()); - Addrd::data_mut(&mut msg).payload = p; - - Some(Ok(msg.map(Resp::from))) - }); + sut.inner() + .init(TestState { token_last_sent: None }) + .set_on_message_sent(|mock, _, _, msg| { + mock.state + .map_mut(|s| s.as_mut().unwrap().token_last_sent = Some(msg.data().token)); + Ok(()) + }) + .set_poll_resp(|mock, _, _, poll_for_token, _| { + let mut msg = test::msg!(ACK {2 . 05} x.x.x.x:2222); + + let token = mock.state + .map_ref(|s| s.as_ref().unwrap().token_last_sent.unwrap()); + Addrd::data_mut(&mut msg).token = token; + + assert_eq!(token, poll_for_token); + + let p = Payload(format!("oink oink!").bytes().collect::>()); + Addrd::data_mut(&mut msg).payload = p; + + Some(Ok(msg.map(Resp::from))) + }); let token = Token(array_vec![1, 2, 3, 4]); @@ -337,10 +318,8 @@ mod test { | e => panic!("{e:?}"), } - assert_eq!( - res.unwrap().unwrap().data().payload_string().unwrap(), - format!("oink oink!") - ); + assert_eq!(res.unwrap().unwrap().data().payload_string().unwrap(), + format!("oink oink!")); } #[test] @@ -354,29 +333,24 @@ mod test { let sut = HandleAcks::::default(); - sut - .inner() - .init(TestState { - token_last_sent: None, - }) - .set_on_message_sent(|mock, _, _, msg| { - mock - .state - .map_mut(|s| s.as_mut().unwrap().token_last_sent = Some(msg.data().token)); - Ok(()) - }) - .set_poll_resp(|mock, _, _, poll_for_token, _| { - let mut msg = test::msg!(ACK {0 . 00} x.x.x.x:2222); - - let token = mock - .state - .map_ref(|s| s.as_ref().unwrap().token_last_sent.unwrap()); - Addrd::data_mut(&mut msg).token = token; - - assert_eq!(token, poll_for_token); - - Some(Ok(msg.map(Resp::from))) - }); + sut.inner() + .init(TestState { token_last_sent: None }) + .set_on_message_sent(|mock, _, _, msg| { + mock.state + .map_mut(|s| s.as_mut().unwrap().token_last_sent = Some(msg.data().token)); + Ok(()) + }) + .set_poll_resp(|mock, _, _, poll_for_token, _| { + let mut msg = test::msg!(ACK {0 . 00} x.x.x.x:2222); + + let token = mock.state + .map_ref(|s| s.as_ref().unwrap().token_last_sent.unwrap()); + Addrd::data_mut(&mut msg).token = token; + + assert_eq!(token, poll_for_token); + + Some(Ok(msg.map(Resp::from))) + }); let token = Token(array_vec![1, 2, 3, 4]); diff --git a/toad/src/step/mod.rs b/toad/src/step/mod.rs index 082f4b13..fa767437 100644 --- a/toad/src/step/mod.rs +++ b/toad/src/step/mod.rs @@ -34,23 +34,21 @@ pub mod runtime { #[allow(missing_docs)] pub type Retry = retry::Retry>, Addrd>)>>; #[allow(missing_docs)] - pub type BufferResponses = buffer_responses::BufferResponses< - S, - Map>>, - >; + pub type BufferResponses = + buffer_responses::BufferResponses>>>; #[allow(missing_docs)] - pub type ProvisionIds = provision_ids::ProvisionIds< - P, - S, - Map, IdWithDefault>>>, - >; + pub type ProvisionIds = + provision_ids::ProvisionIds, IdWithDefault>>>>; #[allow(missing_docs)] - pub type Observe = observe::Observe< - S, - Array>, - Array>>, - observe::SubHash_TypePathQueryAccept

, - >; + pub type Observe = observe::Observe>, + Array>>, + observe::SubHash_TypePathQueryAccept

>; /// Parse -> ProvisionIds -> ProvisionTokens -> Ack -> Retry -> HandleAcks -> BufferResponses -> Observe #[rustfmt::skip] @@ -311,7 +309,9 @@ macro_rules! _try { }}; } -pub use {_try, exec_inner_step, log}; +pub use _try; +pub use exec_inner_step; +pub use log; /// An error that can be returned by a [`Step`]. pub trait Error: core::fmt::Debug {} @@ -342,21 +342,19 @@ pub trait Step: Default { /// # Poll for an inbound request /// This corresponds to the **server** flow. - fn poll_req( - &self, - snap: &platform::Snapshot

, - effects: &mut P::Effects, - ) -> StepOutput; + fn poll_req(&self, + snap: &platform::Snapshot

, + effects: &mut P::Effects) + -> StepOutput; /// # Poll for an inbound response /// This corresponds to the **client** flow. - fn poll_resp( - &self, - snap: &platform::Snapshot

, - effects: &mut P::Effects, - token: Token, - addr: SocketAddr, - ) -> StepOutput; + fn poll_resp(&self, + snap: &platform::Snapshot

, + effects: &mut P::Effects, + token: Token, + addr: SocketAddr) + -> StepOutput; /// # Update Observers /// @@ -365,13 +363,11 @@ pub trait Step: Default { /// /// See [`observe`] for more info. fn notify(&self, path: Path, effects: &mut P::Effects) -> Result<(), Self::Error> - where - Path: AsRef + Clone, + where Path: AsRef + Clone { - self - .inner() - .notify(path, effects) - .map_err(Self::Error::from) + self.inner() + .notify(path, effects) + .map_err(Self::Error::from) } /// Invoked before messages are sent, allowing for internal state change & modification. @@ -381,16 +377,14 @@ pub trait Step: Default { /// /// # Default Implementation /// The default implementation will invoke `self.inner().before_message_sent` - fn before_message_sent( - &self, - snap: &platform::Snapshot

, - effects: &mut

::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { - self - .inner() - .before_message_sent(snap, effects, msg) - .map_err(Self::Error::from) + fn before_message_sent(&self, + snap: &platform::Snapshot

, + effects: &mut

::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { + self.inner() + .before_message_sent(snap, effects, msg) + .map_err(Self::Error::from) } /// Invoked after messages are sent, allowing for internal state change. @@ -400,16 +394,14 @@ pub trait Step: Default { /// /// # Default Implementation /// The default implementation will just invoke `self.inner().on_message_sent` - fn on_message_sent( - &self, - snap: &platform::Snapshot

, - effects: &mut P::Effects, - msg: &Addrd>, - ) -> Result<(), Self::Error> { - self - .inner() - .on_message_sent(snap, effects, msg) - .map_err(Self::Error::from) + fn on_message_sent(&self, + snap: &platform::Snapshot

, + effects: &mut P::Effects, + msg: &Addrd>) + -> Result<(), Self::Error> { + self.inner() + .on_message_sent(snap, effects, msg) + .map_err(Self::Error::from) } } @@ -423,51 +415,47 @@ impl Step

for () { panic!("Step.inner invoked for unit (). This is incorrect and would likely cause recursion without return") } - fn poll_req( - &self, - _: &platform::Snapshot

, - _: &mut

::Effects, - ) -> StepOutput<(), ()> { + fn poll_req(&self, + _: &platform::Snapshot

, + _: &mut

::Effects) + -> StepOutput<(), ()> { None } - fn poll_resp( - &self, - _: &platform::Snapshot

, - _: &mut P::Effects, - _: Token, - _: SocketAddr, - ) -> StepOutput<(), ()> { + fn poll_resp(&self, + _: &platform::Snapshot

, + _: &mut P::Effects, + _: Token, + _: SocketAddr) + -> StepOutput<(), ()> { None } fn notify(&self, _: Path, _: &mut P::Effects) -> Result<(), Self::Error> - where - Path: AsRef, + where Path: AsRef { Ok(()) } - fn before_message_sent( - &self, - _: &platform::Snapshot

, - _: &mut P::Effects, - _: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + _: &platform::Snapshot

, + _: &mut P::Effects, + _: &mut Addrd>) + -> Result<(), Self::Error> { Ok(()) } - fn on_message_sent( - &self, - _: &platform::Snapshot

, - _: &mut P::Effects, - _: &Addrd>, - ) -> Result<(), Self::Error> { + fn on_message_sent(&self, + _: &platform::Snapshot

, + _: &mut P::Effects, + _: &Addrd>) + -> Result<(), Self::Error> { Ok(()) } } #[cfg(test)] +#[allow(missing_docs)] pub mod test { use embedded_time::Clock; @@ -476,14 +464,10 @@ pub mod test { use crate::test::ClockMock; pub fn default_snapshot() -> platform::Snapshot { - platform::Snapshot { - time: ClockMock::new().try_now().unwrap(), - recvd_dgram: Some(crate::net::Addrd( - Default::default(), - crate::test::dummy_addr(), - )), - config: crate::config::Config::default(), - } + platform::Snapshot { time: ClockMock::new().try_now().unwrap(), + recvd_dgram: Some(crate::net::Addrd(Default::default(), + crate::test::dummy_addr())), + config: crate::config::Config::default() } } #[macro_export] @@ -761,9 +745,8 @@ pub mod test { let mut msg = $msg; let assert_fn: Box)> = Box::new($assert_fn); - $step - .before_message_sent(&$snap, &mut $effects, &mut msg) - .unwrap(); + $step.before_message_sent(&$snap, &mut $effects, &mut msg) + .unwrap(); assert_fn(msg) }}; ( @@ -802,9 +785,8 @@ pub mod test { ) => {{ use $crate::step::{Step, StepOutput}; - let assert_fn: Box< - dyn Fn(StepOutput<<$step_ty as Step<_>>::PollReq, <$step_ty as Step<_>>::Error>), - > = Box::new($assert_fn); + let assert_fn: Box>::PollReq, + <$step_ty as Step<_>>::Error>)> = Box::new($assert_fn); assert_fn($step.poll_req($snap, $effects)) }}; ( @@ -817,9 +799,8 @@ pub mod test { ) => {{ use $crate::step::{Step, StepOutput}; - let assert_fn: Box< - dyn Fn(StepOutput<<$step_ty as Step<_>>::PollReq, <$step_ty as Step<_>>::Error>), - > = Box::new($assert_fn); + let assert_fn: Box>::PollReq, + <$step_ty as Step<_>>::Error>)> = Box::new($assert_fn); assert_fn($step.poll_req(&$snap, $effects)) }}; ( @@ -832,9 +813,8 @@ pub mod test { ) => {{ use $crate::step::{Step, StepOutput}; - let assert_fn: Box< - dyn Fn(StepOutput<<$step_ty as Step<_>>::PollResp, <$step_ty as Step<_>>::Error>), - > = Box::new($assert_fn); + let assert_fn: Box>::PollResp, + <$step_ty as Step<_>>::Error>)> = Box::new($assert_fn); assert_fn($step.poll_resp($snap, $effects, $token, $addr)) }}; ( @@ -847,9 +827,8 @@ pub mod test { ) => {{ use $crate::step::{Step, StepOutput}; - let assert_fn: Box< - dyn Fn(StepOutput<<$step_ty as Step<_>>::PollResp, <$step_ty as Step<_>>::Error>), - > = Box::new($assert_fn); + let assert_fn: Box>::PollResp, + <$step_ty as Step<_>>::Error>)> = Box::new($assert_fn); assert_fn($step.poll_resp(&$snap, $effects, $token, $addr)) }}; ( @@ -862,9 +841,8 @@ pub mod test { ) => {{ use $crate::step::{Step, StepOutput}; - let assert_fn: Box< - dyn Fn(StepOutput<<$step_ty as Step<_>>::PollResp, <$step_ty as Step<_>>::Error>), - > = Box::new($assert_fn); + let assert_fn: Box>::PollResp, + <$step_ty as Step<_>>::Error>)> = Box::new($assert_fn); assert_fn($step.poll_resp($snap, $effects, $token, $addr)) }}; ( @@ -897,9 +875,8 @@ pub mod test { expect (before_message_sent(_, _, $msg:expr) should be ok with {$f:expr}) ) => {{ let mut msg = $msg; - $step - .before_message_sent(&$snap, &mut $effects, &mut msg) - .unwrap(); + $step.before_message_sent(&$snap, &mut $effects, &mut msg) + .unwrap(); let f: Box)> = Box::new($f); f(msg) }}; @@ -963,5 +940,7 @@ pub mod test { }; } - pub use {dummy_step, test_step, test_step_when}; + pub use dummy_step; + pub use test_step; + pub use test_step_when; } diff --git a/toad/src/step/observe.rs b/toad/src/step/observe.rs index 8b25408f..7672d9de 100644 --- a/toad/src/step/observe.rs +++ b/toad/src/step/observe.rs @@ -54,9 +54,7 @@ impl

SubHash_TypePathQueryAccept

{ } } -impl

SubscriptionHash

for SubHash_TypePathQueryAccept

-where - P: PlatformTypes, +impl

SubscriptionHash

for SubHash_TypePathQueryAccept

where P: PlatformTypes { type Hasher = Blake2Hasher; @@ -69,12 +67,12 @@ where msg.ty.hash(&mut self.0); msg.get(QUERY).into_iter().for_each(|v| { - v.hash(&mut self.0); - }); + v.hash(&mut self.0); + }); msg.accept().hash(&mut self.0); msg.get(PATH).into_iter().for_each(|v| { - v.hash(&mut self.0); - }); + v.hash(&mut self.0); + }); } } @@ -95,9 +93,8 @@ where /// /// For a more concrete example, see the [module documentation](self). pub trait SubscriptionHash

-where - Self: Sized + Debug, - P: PlatformTypes, + where Self: Sized + Debug, + P: PlatformTypes { /// Type used to generate hashes type Hasher: Hasher; @@ -139,9 +136,8 @@ where } impl SubscriptionHash

for &mut T -where - P: PlatformTypes, - T: SubscriptionHash

, + where P: PlatformTypes, + T: SubscriptionHash

{ type Hasher = T::Hasher; @@ -156,24 +152,19 @@ where /// An Observe subscription pub struct Sub

-where - P: PlatformTypes, + where P: PlatformTypes { req: Addrd>, } -impl

core::fmt::Debug for Sub

-where - P: PlatformTypes, +impl

core::fmt::Debug for Sub

where P: PlatformTypes { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("Sub").field("req", &self.req).finish() } } -impl

Sub

-where - P: PlatformTypes, +impl

Sub

where P: PlatformTypes { #[allow(missing_docs)] pub fn new(req: Addrd>) -> Self { @@ -222,34 +213,29 @@ pub struct Observe { } impl Default for Observe -where - I: Default, - S: Default, - RQ: Default, + where I: Default, + S: Default, + RQ: Default { fn default() -> Self { - Observe { - inner: I::default(), - subs: Stem::new(S::default()), - request_queue: Stem::new(RQ::default()), - __hasher: PhantomData, - } + Observe { inner: I::default(), + subs: Stem::new(S::default()), + request_queue: Stem::new(RQ::default()), + __hasher: PhantomData } } } impl Observe { fn hash<'a, P>(sub: &'a Sub

) -> (&'a Sub

, u64) - where - P: PlatformTypes, - Hasher: SubscriptionHash

+ Default, + where P: PlatformTypes, + Hasher: SubscriptionHash

+ Default { (sub, Self::hash_req(sub.req())) } fn hash_req<'a, P>(sub: &'a Addrd>) -> u64 - where - P: PlatformTypes, - Hasher: SubscriptionHash

+ Default, + where P: PlatformTypes, + Hasher: SubscriptionHash

+ Default { let mut h = Hasher::default(); h.subscription_hash(sub); @@ -257,118 +243,100 @@ impl Observe { } fn get<'a, P>(subs: &'a Subs, addr: SocketAddr, t: Token) -> Option<&'a Sub

> - where - Subs: Array>, - P: PlatformTypes, + where Subs: Array>, + P: PlatformTypes { subs.iter().find(|s| s.token() == t && s.addr() == addr) } fn get_index<'a, P>(subs: &'a Subs, t: Token) -> Option - where - Subs: Array>, - P: PlatformTypes, + where Subs: Array>, + P: PlatformTypes { - subs - .iter() - .enumerate() - .find(|(_, s)| s.token() == t) - .map(|(ix, _)| ix) + subs.iter() + .enumerate() + .find(|(_, s)| s.token() == t) + .map(|(ix, _)| ix) } fn fmt_subs<'a, P>(&self) -> String<1000> - where - Subs: Array>, - P: PlatformTypes, + where Subs: Array>, + P: PlatformTypes { self.subs.map_ref(|subs| { - let mut msg = String::<1000>::from("["); - subs.iter().enumerate().for_each(|(n, s)| { - write!( - &mut msg, - "\"{:?} {:?}\"", - s.req.addr(), - s.req.data().msg().token - ) - .ok(); - if n < subs.len() - 1 { - write!(&mut msg, ",").ok(); - } - }); - write!(&mut msg, "]").ok(); - msg - }) - } - - fn similar_to<'a, P>( - subs: &'a Subs, - addr: SocketAddr, - t: Token, - ) -> impl 'a + Iterator> - where - Subs: Array>, - P: PlatformTypes, - Hasher: SubscriptionHash

+ Default, + let mut msg = String::<1000>::from("["); + subs.iter().enumerate().for_each(|(n, s)| { + write!(&mut msg, + "\"{:?} {:?}\"", + s.req.addr(), + s.req.data().msg().token).ok(); + if n < subs.len() - 1 { + write!(&mut msg, ",").ok(); + } + }); + write!(&mut msg, "]").ok(); + msg + }) + } + + fn similar_to<'a, P>(subs: &'a Subs, + addr: SocketAddr, + t: Token) + -> impl 'a + Iterator> + where Subs: Array>, + P: PlatformTypes, + Hasher: SubscriptionHash

+ Default { - subs - .iter() - .filter(move |s| match Self::get(subs, addr, t).map(Self::hash) { - | Some((sub, h)) => { - s.addr() != sub.addr() && s.token() != sub.token() && Self::hash(sub).1 == h - }, - | None => false, - }) - } - - fn subs_matching_path<'a, 'b, P>( - subs: &'a Subs, - p: &'b str, - ) -> impl 'a + Iterator> - where - Subs: Array>, - P: PlatformTypes, - 'b: 'a, + subs.iter() + .filter(move |s| match Self::get(subs, addr, t).map(Self::hash) { + | Some((sub, h)) => { + s.addr() != sub.addr() && s.token() != sub.token() && Self::hash(sub).1 == h + }, + | None => false, + }) + } + + fn subs_matching_path<'a, 'b, P>(subs: &'a Subs, + p: &'b str) + -> impl 'a + Iterator> + where Subs: Array>, + P: PlatformTypes, + 'b: 'a { subs.iter().filter(move |s| { - s.msg() - .get(PATH) - .map(|segs| { - segs - .iter() - .map(|val| -> &[u8] { &val.0 }) - .eq(p.split("/").map(|s| s.as_bytes())) - }) - .unwrap_or_else(|| p.is_empty()) - }) + s.msg() + .get(PATH) + .map(|segs| { + segs.iter() + .map(|val| -> &[u8] { &val.0 }) + .eq(p.split("/").map(|s| s.as_bytes())) + }) + .unwrap_or_else(|| p.is_empty()) + }) } fn remove_queued_requests_matching_path

(rq: &mut RequestQueue, path: &str) -> () - where - P: PlatformTypes, - RequestQueue: Array>>, + where P: PlatformTypes, + RequestQueue: Array>> { fn go(rq: &mut RQ, p: &str) -> () - where - P: PlatformTypes, - RQ: Array>>, + where P: PlatformTypes, + RQ: Array>> { - match rq - .iter() - .enumerate() - .find(|(_, req)| { - req - .data() - .msg() - .get(PATH) - .map(|segs| { - segs - .iter() - .map(|val| -> &[u8] { &val.0 }) - .eq(p.split("/").map(|s| s.as_bytes())) - }) - .unwrap_or_else(|| p.is_empty()) - }) - .map(|(ix, _)| ix) + match rq.iter() + .enumerate() + .find(|(_, req)| { + req.data() + .msg() + .get(PATH) + .map(|segs| { + segs.iter() + .map(|val| -> &[u8] { &val.0 }) + .eq(p.split("/").map(|s| s.as_bytes())) + }) + .unwrap_or_else(|| p.is_empty()) + }) + .map(|(ix, _)| ix) { | Some(ix) => { rq.remove(ix); @@ -382,71 +350,60 @@ impl Observe { } fn get_queued_request

(&self) -> Option>> - where - P: PlatformTypes, - RequestQueue: Array>>, + where P: PlatformTypes, + RequestQueue: Array>> { self.request_queue.map_mut(|rq| { - if rq.is_empty() { - None - } else { - rq.remove(rq.len() - 1) - } - }) - } - - fn handle_incoming_request( - &self, - req: Addrd>, - _: &platform::Snapshot

, - effs: &mut

::Effects, - ) -> super::StepOutput>, E> - where - P: PlatformTypes, - Subs: Array>, + if rq.is_empty() { + None + } else { + rq.remove(rq.len() - 1) + } + }) + } + + fn handle_incoming_request(&self, + req: Addrd>, + _: &platform::Snapshot

, + effs: &mut

::Effects) + -> super::StepOutput>, E> + where P: PlatformTypes, + Subs: Array> { match req.data().msg().observe() { | Some(Register) => { - log!( - Observe::handle_incoming_request, - effs, - log::Level::Trace, - "register: {:?} {:?}", - req.addr(), - req.data().msg().token - ); + log!(Observe::handle_incoming_request, + effs, + log::Level::Trace, + "register: {:?} {:?}", + req.addr(), + req.data().msg().token); let mut sub = Some(Sub::new(req.clone())); - self - .subs - .map_mut(move |s| s.push(Option::take(&mut sub).expect("closure only invoked once"))); + self.subs + .map_mut(move |s| s.push(Option::take(&mut sub).expect("closure only invoked once"))); }, | Some(Deregister) => { - log!( - Observe::handle_incoming_request, - effs, - log::Level::Trace, - "deregister: {:?} {:?}", - req.addr(), - req.data().msg().token - ); - self - .subs - .map_mut(|s| match Self::get_index(s, req.data().msg().token) { - | Some(ix) => { - s.remove(ix); - }, - | None => (), - }) + log!(Observe::handle_incoming_request, + effs, + log::Level::Trace, + "deregister: {:?} {:?}", + req.addr(), + req.data().msg().token); + self.subs + .map_mut(|s| match Self::get_index(s, req.data().msg().token) { + | Some(ix) => { + s.remove(ix); + }, + | None => (), + }) }, | _ => { - log!( - Observe::handle_incoming_request, - effs, - log::Level::Trace, - "ignoring: {:?} {:?}", - req.addr(), - req.data().msg().token - ); + log!(Observe::handle_incoming_request, + effs, + log::Level::Trace, + "ignoring: {:?} {:?}", + req.addr(), + req.data().msg().token); }, }; @@ -454,38 +411,35 @@ impl Observe { } fn clone_and_enqueue_sub_requests

(subs: &Subs, rq: &mut RequestQueue, path: &str) - where - P: PlatformTypes, - Subs: Array>, - RequestQueue: Array>>, - Hasher: SubscriptionHash

+ Default, + where P: PlatformTypes, + Subs: Array>, + RequestQueue: Array>>, + Hasher: SubscriptionHash

+ Default { Self::subs_matching_path(subs, path).for_each(|sub| { - // TODO: handle option capacity - let mut req = sub.req().clone(); - req - .as_mut() - .msg_mut() - .set(opt::WAS_CREATED_BY_OBSERVE, Default::default()) - .ok(); - - if rq - .iter() - .all(|req2| Self::hash_req(&req) != Self::hash_req(req2)) - { - rq.push(req); - } - }); + // TODO: handle option capacity + let mut req = sub.req().clone(); + req.as_mut() + .msg_mut() + .set(opt::WAS_CREATED_BY_OBSERVE, Default::default()) + .ok(); + + if rq.iter().all(|req2| { + Self::hash_req(&req) != Self::hash_req(req2) + }) + { + rq.push(req); + } + }); } } impl Step

for Observe -where - P: PlatformTypes, - S: Step>, PollResp = Addrd>>, - B: Default + Array>, - RQ: Default + Array>>, - H: SubscriptionHash

+ Default, + where P: PlatformTypes, + S: Step>, PollResp = Addrd>>, + B: Default + Array>, + RQ: Default + Array>>, + H: SubscriptionHash

+ Default { type PollReq = Addrd>; type PollResp = Addrd>; @@ -497,11 +451,10 @@ where &self.inner } - fn poll_req( - &self, - snap: &platform::Snapshot

, - effects: &mut

::Effects, - ) -> super::StepOutput { + fn poll_req(&self, + snap: &platform::Snapshot

, + effects: &mut

::Effects) + -> super::StepOutput { // TODO(orion): if throughput so high that there is always a request on the wire, // we will never fully flush the queue. // maybe add a timestamp or TTL check so that we can prioritize old outbound subscription updates @@ -512,109 +465,91 @@ where } } - fn poll_resp( - &self, - snap: &platform::Snapshot

, - effects: &mut

::Effects, - token: ::toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> super::StepOutput { + fn poll_resp(&self, + snap: &platform::Snapshot

, + effects: &mut

::Effects, + token: ::toad_msg::Token, + addr: no_std_net::SocketAddr) + -> super::StepOutput { self.inner.poll_resp(snap, effects, token, addr) } - fn notify( - &self, - path: Path, - effects: &mut

::Effects, - ) -> Result<(), Self::Error> - where - Path: AsRef + Clone, + fn notify(&self, + path: Path, + effects: &mut

::Effects) + -> Result<(), Self::Error> + where Path: AsRef + Clone { self.inner.notify(path.clone(), effects)?; self.request_queue.map_mut(|rq| { - log!( - Observe::notify, - effects, - log::Level::Trace, - "{}", - path.as_ref() - ); - log!( - Observe::notify, - effects, - log::Level::Trace, - "discarding {} synthetic requests not yet processed", - rq.len() - ); - - Self::remove_queued_requests_matching_path(rq, path.as_ref()); - self - .subs - .map_ref(|subs| Self::clone_and_enqueue_sub_requests(subs, rq, path.as_ref())); - - log!( - Observe::notify, - effects, - log::Level::Trace, - "{} synthetic requests now enqueued", - rq.len() - ); - }); + log!(Observe::notify, + effects, + log::Level::Trace, + "{}", + path.as_ref()); + log!(Observe::notify, + effects, + log::Level::Trace, + "discarding {} synthetic requests not yet processed", + rq.len()); + + Self::remove_queued_requests_matching_path(rq, path.as_ref()); + self.subs.map_ref(|subs| { + Self::clone_and_enqueue_sub_requests(subs, rq, path.as_ref()) + }); + + log!(Observe::notify, + effects, + log::Level::Trace, + "{} synthetic requests now enqueued", + rq.len()); + }); Ok(()) } - fn before_message_sent( - &self, - snap: &platform::Snapshot

, - effs: &mut P::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + snap: &platform::Snapshot

, + effs: &mut P::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { self.inner().before_message_sent(snap, effs, msg)?; if let Some(_) = msg.data().get(opt::WAS_CREATED_BY_OBSERVE) { msg.as_mut().remove(opt::WAS_CREATED_BY_OBSERVE); } else if msg.data().code.kind() == CodeKind::Response - && self - .subs - .map_ref(|subs| Self::get(subs, msg.addr(), msg.data().token).is_some()) + && self.subs + .map_ref(|subs| Self::get(subs, msg.addr(), msg.data().token).is_some()) { self.subs.map_ref(|subs| { - Self::similar_to(subs, msg.addr(), msg.data().token).for_each(|sub| { - let mut msg = msg.clone(); - msg - .as_mut() - .set(opt::WAS_CREATED_BY_OBSERVE, Default::default()) - .ok(); - - log!( - Observe::before_message_sent, - effs, - log::Level::Trace, - "=> {:?} {:?}", - sub.addr(), - msg.data().token - ); - effs.push(Effect::Send(msg.with_addr(sub.addr()))); - }) - }); + Self::similar_to(subs, msg.addr(), msg.data().token).for_each(|sub| { + let mut msg = msg.clone(); + msg.as_mut() + .set(opt::WAS_CREATED_BY_OBSERVE, Default::default()) + .ok(); + + log!(Observe::before_message_sent, + effs, + log::Level::Trace, + "=> {:?} {:?}", + sub.addr(), + msg.data().token); + effs.push(Effect::Send(msg.with_addr(sub.addr()))); + }) + }); } else { - log!( - Observe::before_message_sent, - effs, - log::Level::Trace, - "ignoring {:?} {:?}", - msg.addr(), - msg.data().token - ); - log!( - Observe::before_message_sent, - effs, - log::Level::Trace, - "subscriptions: {}", - self.fmt_subs().as_str() - ); + log!(Observe::before_message_sent, + effs, + log::Level::Trace, + "ignoring {:?} {:?}", + msg.addr(), + msg.data().token); + log!(Observe::before_message_sent, + effs, + log::Level::Trace, + "subscriptions: {}", + self.fmt_subs().as_str()); } Ok(()) @@ -628,7 +563,6 @@ mod tests { use ::toad_msg::{Code, ContentFormat, Id, Token, Type}; use embedded_time::Clock; - use lazycell::AtomicLazyCell; use platform::toad_msg; use tinyvec::array_vec; @@ -641,12 +575,10 @@ mod tests { type Snapshot = crate::platform::Snapshot; type Message = toad_msg::Message; type Sub = super::Sub; - type Observe = super::Observe< - S, - Vec, - Vec>>, - SubHash_TypePathQueryAccept, - >; + type Observe = super::Observe, + Vec>>, + SubHash_TypePathQueryAccept>; type PollReq = Addrd>; type PollResp = Addrd>; @@ -674,25 +606,24 @@ mod tests { ); fn poll_req_emitting_single_register_request( - num: usize, - ) -> impl Fn( - &Snapshot, - &mut Vec>, - ) -> Option>, ()>> { - static INVOCATIONS: Mutex>> = - Mutex::new(AtomicLazyCell::NONE); - - let lock = INVOCATIONS.lock().unwrap(); - if !lock.filled() { - lock.fill(Default::default()).unwrap(); + num: usize) + -> impl Fn(&Snapshot, + &mut Vec>) + -> Option>, ()>> { + static INVOCATIONS: Mutex>> = Mutex::new(None); + + { + let mut lock = INVOCATIONS.lock().unwrap(); + if lock.is_none() { + *lock = Some(HashMap::default()); + } } - drop(lock); move |_, _| { let mut inv_lock = INVOCATIONS.lock().unwrap(); - let mut map = inv_lock.replace(Default::default()).unwrap(); + let mut map = inv_lock.take().unwrap(); let call = *map.entry(num).and_modify(|n| *n += 1).or_insert(1); - inv_lock.replace(map).unwrap(); + *inv_lock = Some(map); if call == 1 { let mut msg = test::msg!(CON GET x.x.x.x:80).unwrap(); @@ -805,8 +736,7 @@ mod tests { #[test] pub fn sub_hash() { fn req(stuff: F) -> u64 - where - F: FnOnce(&mut Message), + where F: FnOnce(&mut Message) { let mut req = Message::new(Type::Con, Code::GET, Id(1), Token(Default::default())); stuff(&mut req); @@ -817,63 +747,51 @@ mod tests { h.hasher().finish() } - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - }), - req(|_| {}) - ); - assert_eq!( - req(|r| { - r.set_path("a/b/c").ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - }) - ); - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - }) - ); - assert_eq!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_content_format(ContentFormat::Json).ok(); - }) - ); - assert_ne!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Text).ok(); - }) - ); - assert_eq!( - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }), - req(|r| { - r.set_path("a/b/c").ok(); - r.add_query("filter[temp](less_than)=123").ok(); - r.set_accept(ContentFormat::Json).ok(); - }) - ); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + }), + req(|_| {})); + assert_eq!(req(|r| { + r.set_path("a/b/c").ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + })); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + })); + assert_eq!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_content_format(ContentFormat::Json).ok(); + })); + assert_ne!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Text).ok(); + })); + assert_eq!(req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + }), + req(|r| { + r.set_path("a/b/c").ok(); + r.add_query("filter[temp](less_than)=123").ok(); + r.set_accept(ContentFormat::Json).ok(); + })); } } diff --git a/toad/src/step/parse.rs b/toad/src/step/parse.rs index a7322684..765111c7 100644 --- a/toad/src/step/parse.rs +++ b/toad/src/step/parse.rs @@ -62,16 +62,15 @@ impl super::Error for Error {} macro_rules! common { ($dgram:expr) => {{ - $dgram - .map(|d| { - d.as_ref() - .fold(|dgram, addr| { - platform::Message::

::try_from_bytes(dgram).map(|dgram| Addrd(dgram, addr)) + $dgram.map(|d| { + d.as_ref() + .fold(|dgram, addr| { + platform::Message::

::try_from_bytes(dgram).map(|dgram| Addrd(dgram, addr)) + }) + .map_err(Error::Parsing) + .map_err(nb::Error::Other) }) - .map_err(Error::Parsing) - .map_err(nb::Error::Other) - }) - .unwrap_or(Err(nb::Error::WouldBlock)) + .unwrap_or(Err(nb::Error::WouldBlock)) }}; } @@ -85,22 +84,20 @@ impl, P: PlatformTypes> Step

for Parse { &self.0 } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput> { + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> StepOutput> { exec_inner_step!(self.0.poll_req(snap, effects), Error::Inner); Some(common!(snap.recvd_dgram.as_ref()).map(|addrd| addrd.map(Req::from))) } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput> { + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput> { exec_inner_step!(self.0.poll_resp(snap, effects, token, addr), Error::Inner); Some(common!(snap.recvd_dgram.as_ref()).map(|addrd| addrd.map(Resp::from))) } @@ -120,32 +117,26 @@ mod test { fn test_msg( ty: Type, - code: Code, - ) -> ( - Addrd<::Dgram>, - Addrd>, - Addrd>, - ) { + code: Code) + -> (Addrd<::Dgram>, + Addrd>, + Addrd>) { use toad_msg::*; type Msg = platform::Message; - let msg = Msg { - id: Id(1), - ty, - ver: Default::default(), - token: Token(Default::default()), - code, - opts: Default::default(), - payload: Payload(Default::default()), - }; + let msg = Msg { id: Id(1), + ty, + ver: Default::default(), + token: Token(Default::default()), + code, + opts: Default::default(), + payload: Payload(Default::default()) }; let addr = crate::test::dummy_addr(); - ( - Addrd(msg.clone().try_into_bytes().unwrap(), addr), - Addrd(Req::<_>::from(msg.clone()), addr), - Addrd(Resp::<_>::from(msg), addr), - ) + (Addrd(msg.clone().try_into_bytes().unwrap(), addr), + Addrd(Req::<_>::from(msg.clone()), addr), + Addrd(Resp::<_>::from(msg), addr)) } test::test_step!( diff --git a/toad/src/step/provision_ids.rs b/toad/src/step/provision_ids.rs index 8b36ea8a..d09aec5d 100644 --- a/toad/src/step/provision_ids.rs +++ b/toad/src/step/provision_ids.rs @@ -11,7 +11,7 @@ use toad_map::{InsertError, Map}; use toad_msg::Id; use toad_stem::Stem; -use super::{Step, _try, log}; +use super::{_try, log, Step}; use crate::config::Config; use crate::net::Addrd; use crate::platform; @@ -41,11 +41,9 @@ impl>, - const N: usize, - > IdsBySocketAddr

for ArrayVec<[(SocketAddrWithDefault, A); N]> +impl>, + const N: usize> IdsBySocketAddr

for ArrayVec<[(SocketAddrWithDefault, A); N]> { type Ids = A; } @@ -64,10 +62,7 @@ pub struct SocketAddrWithDefault(pub SocketAddr); impl Default for SocketAddrWithDefault { fn default() -> Self { use no_std_net::*; - Self(SocketAddr::V4(SocketAddrV4::new( - Ipv4Addr::new(0, 0, 0, 0), - 0, - ))) + Self(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0))) } } @@ -101,46 +96,39 @@ pub struct ProvisionIds { } impl Default for ProvisionIds -where - Inner: Default, - SeenIds: Default, + where Inner: Default, + SeenIds: Default { fn default() -> Self { - Self { - inner: Default::default(), - seen: Default::default(), - __p: PhantomData, - } + Self { inner: Default::default(), + seen: Default::default(), + __p: PhantomData } } } impl ProvisionIds -where - Ids: IdsBySocketAddr

, - P: PlatformTypes, + where Ids: IdsBySocketAddr

, + P: PlatformTypes { fn prune(effs: &mut P::Effects, seen: &mut Ids, now: Instant, config: Config) { for (_, ids) in seen.iter_mut() { ids.sort_by_key(|t| t.time()); - let ix_of_first_id_to_keep = ids - .iter() - .enumerate() - .find(|(_, id)| { - now.checked_duration_since(&id.time()) + let ix_of_first_id_to_keep = ids.iter() + .enumerate() + .find(|(_, id)| { + now.checked_duration_since(&id.time()) < Some(Milliseconds(config.exchange_lifetime_millis()).into()) - }) - .map(|(ix, _)| ix); + }) + .map(|(ix, _)| ix); match ix_of_first_id_to_keep { | Some(keep_at) if keep_at == 0 => (), | Some(keep_at) => { - log!( - ProvisionIds::prune, - effs, - log::Level::Trace, - "removing {} old irrelevant ids", - keep_at - ); + log!(ProvisionIds::prune, + effs, + log::Level::Trace, + "removing {} old irrelevant ids", + keep_at); for ix in 0..keep_at { ids.remove(ix); } @@ -154,13 +142,11 @@ where } fn new_addr(effs: &mut P::Effects, seen: &mut Ids, addr: SocketAddr) { - log!( - ProvisionIds::new_addr, - effs, - log::Level::Trace, - "haven't seen {:?} before", - addr - ); + log!(ProvisionIds::new_addr, + effs, + log::Level::Trace, + "haven't seen {:?} before", + addr); match seen.insert(SocketAddrWithDefault(addr), Default::default()) { | Ok(_) => (), | Err(InsertError::CapacityExhausted) => { @@ -191,13 +177,12 @@ where /// Generate a Message ID that has not been used yet with the connection with this socket /// /// best case O(1), worst case O(n) - fn next( - effs: &mut P::Effects, - seen: &mut Ids, - config: Config, - time: Instant, - addr: SocketAddr, - ) -> Id { + fn next(effs: &mut P::Effects, + seen: &mut Ids, + config: Config, + time: Instant, + addr: SocketAddr) + -> Id { match seen.get_mut(&SocketAddrWithDefault(addr)) { | None => { Self::new_addr(effs, seen, addr); @@ -239,25 +224,21 @@ where // and adding 1 to the integer at the start of the gap. // // if the set of ids is literally **EVERY** integer in u16 then this will panic. - let (Stamped(IdWithDefault(Id(before_gap)), _), _) = ids - .iter() - .zip(ahead) - .find( - |(Stamped(IdWithDefault(Id(cur)), _), Stamped(IdWithDefault(Id(next)), _))| { - next - cur > 1 - }, - ) - .unwrap(); + let (Stamped(IdWithDefault(Id(before_gap)), _), _) = + ids.iter() + .zip(ahead) + .find(|(Stamped(IdWithDefault(Id(cur)), _), Stamped(IdWithDefault(Id(next)), _))| { + next - cur > 1 + }) + .unwrap(); Id(before_gap + 1) }; - log!( - ProvisionIds::next, - effs, - log::Level::Debug, - "Generated new {:?}", - next - ); + log!(ProvisionIds::next, + effs, + log::Level::Debug, + "Generated new {:?}", + next); Self::seen(effs, seen, config, time, addr, next); next }, @@ -265,14 +246,12 @@ where } /// Mark an Id + Addr pair as being seen at `time`. - fn seen( - effs: &mut P::Effects, - seen: &mut Ids, - config: Config, - now: Instant, - addr: SocketAddr, - id: Id, - ) { + fn seen(effs: &mut P::Effects, + seen: &mut Ids, + config: Config, + now: Instant, + addr: SocketAddr, + id: Id) { Self::prune(effs, seen, now, config); match seen.get_mut(&SocketAddrWithDefault(addr)) { @@ -307,13 +286,11 @@ where ids.sort(); } - log!( - ProvisionIds::seen, - effs, - log::Level::Trace, - "Saw new {:?}", - id - ); + log!(ProvisionIds::seen, + effs, + log::Level::Trace, + "Saw new {:?}", + id); ids.push(Stamped(IdWithDefault(id), now)); }, } @@ -324,24 +301,21 @@ macro_rules! common { ($self:expr, $effs:expr, $snap:expr, $req_or_resp:expr) => {{ let r = $req_or_resp; $self.seen.map_mut(|s| { - Self::seen( - $effs, - s, - $snap.config, - $snap.time, - r.addr(), - r.data().msg().id, - ) - }); + Self::seen($effs, + s, + $snap.config, + $snap.time, + r.addr(), + r.data().msg().id) + }); Some(Ok(r)) }}; } impl Step

for ProvisionIds -where - P: PlatformTypes, - Inner: Step>, PollResp = Addrd>, Error = E>, - Ids: IdsBySocketAddr

, + where P: PlatformTypes, + Inner: Step>, PollResp = Addrd>, Error = E>, + Ids: IdsBySocketAddr

{ type PollReq = Addrd>; type PollResp = Addrd>; @@ -352,40 +326,36 @@ where &self.inner } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> super::StepOutput { + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> super::StepOutput { let req = self.inner.poll_req(snap, effects); let req = _try!(Option; req); common!(self, effects, snap, req) } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: SocketAddr, - ) -> super::StepOutput { + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: SocketAddr) + -> super::StepOutput { let resp = self.inner.poll_resp(snap, effects, token, addr); let resp = _try!(Option; resp); common!(self, effects, snap, resp) } - fn before_message_sent( - &self, - snap: &platform::Snapshot

, - effs: &mut P::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + snap: &platform::Snapshot

, + effs: &mut P::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { self.inner.before_message_sent(snap, effs, msg)?; if msg.data().id == Id(0) { - let id = self - .seen - .map_mut(|s| Self::next(effs, s, snap.config, snap.time, msg.addr())); + let id = self.seen + .map_mut(|s| Self::next(effs, s, snap.config, snap.time, msg.addr())); msg.data_mut().id = id; } @@ -405,27 +375,22 @@ mod test { type InnerPollReq = Addrd>; type InnerPollResp = Addrd>; - type ProvisionIds = super::ProvisionIds< - P, - S, - BTreeMap>>, - >; + type ProvisionIds = super::ProvisionIds>>>; fn test_msg(id: Id) -> Addrd { use toad_msg::*; - Addrd( - test::Message { - id, - ty: Type::Con, - ver: Default::default(), - code: Code::new(0, 0), - opts: Default::default(), - payload: Payload(vec![]), - token: Token(Default::default()), - }, - test::dummy_addr(), - ) + Addrd(test::Message { id, + ty: Type::Con, + ver: Default::default(), + code: Code::new(0, 0), + opts: Default::default(), + payload: Payload(vec![]), + token: Token(Default::default()) }, + test::dummy_addr()) } test_step!( @@ -483,39 +448,31 @@ mod test { let cfg = Config::default(); step.seen.map_mut(|s| { - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(0), - test::dummy_addr(), - Id(1), - ); - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(1), - test::dummy_addr_2(), - Id(1), - ); - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(2), - test::dummy_addr(), - Id(2), - ); - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(3), - test::dummy_addr_3(), - Id(1), - ); - }); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(0), + test::dummy_addr(), + Id(1)); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(1), + test::dummy_addr_2(), + Id(1)); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(2), + test::dummy_addr(), + Id(2)); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(3), + test::dummy_addr_3(), + Id(1)); + }); let mut addrs: Vec<_> = step.seen.map_ref(|s| s.iter().map(|(k, _)| k.0).collect()); addrs.sort(); @@ -534,29 +491,22 @@ mod test { let cfg = Config::default(); step.seen.map_mut(|seen| { - Map::insert( - seen, - SocketAddrWithDefault(test::dummy_addr()), - Default::default(), - ) - .unwrap(); - Step::seen( - &mut effs, - seen, - cfg, - ClockMock::instant(1), - test::dummy_addr_2(), - Id(1), - ); - Step::seen( - &mut effs, - seen, - cfg, - ClockMock::instant(3), - test::dummy_addr_3(), - Id(1), - ); - }); + Map::insert(seen, + SocketAddrWithDefault(test::dummy_addr()), + Default::default()).unwrap(); + Step::seen(&mut effs, + seen, + cfg, + ClockMock::instant(1), + test::dummy_addr_2(), + Id(1)); + Step::seen(&mut effs, + seen, + cfg, + ClockMock::instant(3), + test::dummy_addr_3(), + Id(1)); + }); let mut addrs: Vec<_> = step.seen.map_ref(|s| s.iter().map(|(k, _)| k.0).collect()); addrs.sort(); @@ -575,39 +525,33 @@ mod test { let cfg = Config::default(); step.seen.map_mut(|seen| { - Step::seen( - &mut effs, - seen, - cfg, - ClockMock::instant(0), - test::dummy_addr(), - Id(0), - ); - Step::seen( - &mut effs, - seen, - cfg, - ClockMock::instant(1), - test::dummy_addr(), - Id(1), - ); - Step::seen( - &mut effs, - seen, - cfg, - ClockMock::instant(2), - test::dummy_addr(), - Id(2), - ); - }); + Step::seen(&mut effs, + seen, + cfg, + ClockMock::instant(0), + test::dummy_addr(), + Id(0)); + Step::seen(&mut effs, + seen, + cfg, + ClockMock::instant(1), + test::dummy_addr(), + Id(1)); + Step::seen(&mut effs, + seen, + cfg, + ClockMock::instant(2), + test::dummy_addr(), + Id(2)); + }); let ids: Vec<_> = step.seen.map_ref(|s| { - s.get(&SocketAddrWithDefault(test::dummy_addr())) - .unwrap() - .into_iter() - .map(|Stamped(IdWithDefault(id), _)| *id) - .collect() - }); + s.get(&SocketAddrWithDefault(test::dummy_addr())) + .unwrap() + .into_iter() + .map(|Stamped(IdWithDefault(id), _)| *id) + .collect() + }); assert_eq!(ids, vec![Id(1), Id(2)]); } @@ -621,45 +565,37 @@ mod test { let exchange_lifetime_micros = cfg.exchange_lifetime_millis() * 1_000; // This test assumes that the clock considers 1 "tick" to be 1 microsecond. - assert_eq!( - Microseconds::try_from(ClockMock::instant(1).duration_since_epoch()), - Ok(Microseconds(1u64)) - ); + assert_eq!(Microseconds::try_from(ClockMock::instant(1).duration_since_epoch()), + Ok(Microseconds(1u64))); step.seen.map_mut(|s| { - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(0), - test::dummy_addr(), - Id(1), - ); - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(1), - test::dummy_addr(), - Id(2), - ); - Step::seen( - &mut effs, - s, - cfg, - ClockMock::instant(exchange_lifetime_micros + 1_000), - test::dummy_addr(), - Id(3), - ); - }); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(0), + test::dummy_addr(), + Id(1)); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(1), + test::dummy_addr(), + Id(2)); + Step::seen(&mut effs, + s, + cfg, + ClockMock::instant(exchange_lifetime_micros + 1_000), + test::dummy_addr(), + Id(3)); + }); let ids: Vec<_> = step.seen.map_ref(|s| { - s.get(&SocketAddrWithDefault(test::dummy_addr())) - .unwrap() - .iter() - .map(|Stamped(IdWithDefault(id), _)| *id) - .collect() - }); + s.get(&SocketAddrWithDefault(test::dummy_addr())) + .unwrap() + .iter() + .map(|Stamped(IdWithDefault(id), _)| *id) + .collect() + }); assert_eq!(ids, vec![Id(3)]); } @@ -672,40 +608,32 @@ mod test { let time = ClockMock::instant(0); step.seen.map_mut(|seen| { - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(22), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(1), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(2), - ); - - let generated = Step::next( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - ); - assert_eq!(generated, Id(23)) - }); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(22)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(1)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(2)); + + let generated = Step::next(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr()); + assert_eq!(generated, Id(23)) + }); } #[test] @@ -717,32 +645,26 @@ mod test { let time = ClockMock::instant(0); step.seen.map_mut(|seen| { - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(2), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(u16::MAX), - ); - - let generated = Step::next( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - ); - assert_eq!(generated, Id(1)) - }); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(2)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(u16::MAX)); + + let generated = Step::next(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr()); + assert_eq!(generated, Id(1)) + }); } #[test] @@ -754,56 +676,44 @@ mod test { let time = ClockMock::instant(0); step.seen.map_mut(|seen| { - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(1), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(2), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(3), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(5), - ); - Step::seen( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - Id(u16::MAX), - ); - - let generated = Step::next( - &mut effs, - seen, - Default::default(), - time, - test::dummy_addr(), - ); - assert_eq!(generated, Id(4)) - }); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(1)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(2)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(3)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(5)); + Step::seen(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr(), + Id(u16::MAX)); + + let generated = Step::next(&mut effs, + seen, + Default::default(), + time, + test::dummy_addr()); + assert_eq!(generated, Id(4)) + }); } #[test] @@ -811,14 +721,12 @@ mod test { type Step = ProvisionIds<()>; let step = Step::default(); let id = step.seen.map_mut(|s| { - Step::next( - &mut vec![], - s, - Default::default(), - ClockMock::instant(0), - test::dummy_addr(), - ) - }); + Step::next(&mut vec![], + s, + Default::default(), + ClockMock::instant(0), + test::dummy_addr()) + }); assert_eq!(id, Id(1)) } } diff --git a/toad/src/step/provision_tokens.rs b/toad/src/step/provision_tokens.rs index 42aec93f..93efef28 100644 --- a/toad/src/step/provision_tokens.rs +++ b/toad/src/step/provision_tokens.rs @@ -59,57 +59,48 @@ pub struct ProvisionTokens { inner: Inner, } -impl Default for ProvisionTokens -where - Inner: Default, +impl Default for ProvisionTokens where Inner: Default { fn default() -> Self { - Self { - inner: Default::default(), - } + Self { inner: Default::default() } } } impl ProvisionTokens { - fn next

( - &self, - effs: &mut P::Effects, - now: Instant, - cfg: Config, - ) -> Result> - where - P: PlatformTypes, - Inner: Step

, + fn next

(&self, + effs: &mut P::Effects, + now: Instant, + cfg: Config) + -> Result> + where P: PlatformTypes, + Inner: Step

{ // TODO(orion): we may want to handle this - let now_since_epoch = Millis::try_from(now.duration_since_epoch()) - .map_err(|_| Error::MillisSinceEpochWouldOverflow)?; + let now_since_epoch = + Millis::try_from(now.duration_since_epoch()).map_err(|_| { + Error::MillisSinceEpochWouldOverflow + })?; #[allow(clippy::many_single_char_names)] let bytes = { - let ([a, b], [c, d, e, f, g, h, i, j]) = ( - cfg.msg.token_seed.to_be_bytes(), - now_since_epoch.0.to_be_bytes(), - ); + let ([a, b], [c, d, e, f, g, h, i, j]) = + (cfg.msg.token_seed.to_be_bytes(), now_since_epoch.0.to_be_bytes()); [a, b, c, d, e, f, g, h, i, j] }; let next = Token::opaque(&bytes); - log!( - ProvisionTokens::next, - effs, - log::Level::Debug, - "Generated new {:?}", - next - ); + log!(ProvisionTokens::next, + effs, + log::Level::Debug, + "Generated new {:?}", + next); Ok(next) } } impl Step

for ProvisionTokens -where - P: PlatformTypes, - Inner: Step>, PollResp = Addrd>, Error = E>, + where P: PlatformTypes, + Inner: Step>, PollResp = Addrd>, Error = E> { type PollReq = Addrd>; type PollResp = Addrd>; @@ -120,12 +111,11 @@ where &self.inner } - fn before_message_sent( - &self, - snap: &platform::Snapshot

, - effs: &mut P::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + snap: &platform::Snapshot

, + effs: &mut P::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { self.inner.before_message_sent(snap, effs, msg)?; let token = match (msg.data().code.kind(), msg.data().token) { @@ -140,28 +130,24 @@ where Ok(()) } - fn poll_req( - &self, - snap: &platform::Snapshot

, - effects: &mut

::Effects, - ) -> super::StepOutput { - self - .inner - .poll_req(snap, effects) - .map(|r| r.map_err(|e| e.map(Error::Inner))) + fn poll_req(&self, + snap: &platform::Snapshot

, + effects: &mut

::Effects) + -> super::StepOutput { + self.inner + .poll_req(snap, effects) + .map(|r| r.map_err(|e| e.map(Error::Inner))) } - fn poll_resp( - &self, - snap: &platform::Snapshot

, - effects: &mut

::Effects, - token: Token, - addr: SocketAddr, - ) -> super::StepOutput { - self - .inner - .poll_resp(snap, effects, token, addr) - .map(|r| r.map_err(|e| e.map(Error::Inner))) + fn poll_resp(&self, + snap: &platform::Snapshot

, + effects: &mut

::Effects, + token: Token, + addr: SocketAddr) + -> super::StepOutput { + self.inner + .poll_resp(snap, effects, token, addr) + .map(|r| r.map_err(|e| e.map(Error::Inner))) } } diff --git a/toad/src/step/retry.rs b/toad/src/step/retry.rs index 606a96a0..87debe5a 100644 --- a/toad/src/step/retry.rs +++ b/toad/src/step/retry.rs @@ -5,7 +5,7 @@ use toad_msg::{CodeKind, Token, Type}; use toad_stem::Stem; use toad_string::{format, String}; -use super::{log, Step, StepOutput, _try}; +use super::{_try, log, Step, StepOutput}; use crate::config::Config; use crate::net::Addrd; use crate::platform::{self, Effect, PlatformTypes, Snapshot}; @@ -27,105 +27,89 @@ pub struct Debug { /// Buffer used to store messages queued for retry pub trait Buf

-where - P: PlatformTypes, - Self: Array, Addrd>)>, + where P: PlatformTypes, + Self: Array, Addrd>)> { /// Data points used by log messaging - fn debug( - now: Instant, - state: &State, - msg: &Addrd>, - ) -> Debug { - let msg_short = format!( - 100, - "{:?} {:?} {:?}", - msg.data().ty, - msg.data().code, - msg.data().token - ); + fn debug(now: Instant, + state: &State, + msg: &Addrd>) + -> Debug { + let msg_short = format!(100, + "{:?} {:?} {:?}", + msg.data().ty, + msg.data().code, + msg.data().token); let since_first_attempt = Millis::try_from(now - state.retry_timer().first_attempted_at()) .expect("duration since first attempt should be less than u64::MAX milliseconds"); let since_last_attempt = Millis::try_from(now - state.retry_timer().last_attempted_at()) .expect("duration since last attempt should be less than u64::MAX milliseconds"); - let until_next_attempt = state - .retry_timer() - .next_attempt_at() - .checked_duration_since(&now) - .map(|until| { - Millis::try_from(until) + let until_next_attempt = state.retry_timer() + .next_attempt_at() + .checked_duration_since(&now) + .map(|until| { + Millis::try_from(until) .expect("duration until next attempt should be less than u64::MAX milliseconds") - }); + }); let msg_should_be = if msg.data().ty == Type::Con { - "acknowledged" - } else { - "responded to" - } - .into(); - Debug { - since_first_attempt, - since_last_attempt, - until_next_attempt, - msg_should_be, - msg_short, - } + "acknowledged" + } else { + "responded to" + }.into(); + Debug { since_first_attempt, + since_last_attempt, + until_next_attempt, + msg_should_be, + msg_short } } /// Send all messages that need to be sent - fn attempt_all( - &mut self, - now: Instant, - effects: &mut P::Effects, - ) -> Result<(), Error> { + fn attempt_all(&mut self, + now: Instant, + effects: &mut P::Effects) + -> Result<(), Error> { self.iter_mut().for_each(|(state, msg)| { - let dbg = Self::debug(now, state, msg); - match state.timer().what_should_i_do(now) { - | Ok(YouShould::Retry) => { - log!( - retry::Buf::attempt_all, - effects, - log::Level::Info, - "{} not {} in {}ms. retrying...", - dbg.msg_short, - dbg.msg_should_be, - dbg.since_last_attempt - ); - effects.push(Effect::Send(msg.clone())); - }, - | _ => log!( - retry::Buf::attempt_all, - effects, - log::Level::Trace, - "{} not {} in {}ms, will retry in {:?}", - dbg.msg_short, - dbg.msg_should_be, - dbg.since_last_attempt, - dbg.until_next_attempt - ), - } - }); + let dbg = Self::debug(now, state, msg); + match state.timer().what_should_i_do(now) { + | Ok(YouShould::Retry) => { + log!(retry::Buf::attempt_all, + effects, + log::Level::Info, + "{} not {} in {}ms. retrying...", + dbg.msg_short, + dbg.msg_should_be, + dbg.since_last_attempt); + effects.push(Effect::Send(msg.clone())); + }, + | _ => log!(retry::Buf::attempt_all, + effects, + log::Level::Trace, + "{} not {} in {}ms, will retry in {:?}", + dbg.msg_short, + dbg.msg_should_be, + dbg.since_last_attempt, + dbg.until_next_attempt), + } + }); Ok(()) } /// We saw a response and should remove all tracking of a token (if we have any) fn forget(&mut self, now: Instant, effects: &mut P::Effects, token: Token) { - match self - .iter() - .enumerate() - .find(|(_, (_, msg))| msg.data().token == token) + match self.iter() + .enumerate() + .find(|(_, (_, msg))| msg.data().token == token) { | Some((ix, (state, msg))) => { let dbg = Self::debug(now, state, msg); - log!( - retry::Buf::forget, - effects, - log::Level::Debug, - "{} {} after waiting {}ms since last attempt (first attempt {}ms ago)", - dbg.msg_short, - dbg.msg_should_be, - dbg.since_last_attempt, - dbg.since_first_attempt - ); + log!(retry::Buf::forget, + effects, + log::Level::Debug, + "{} {} after waiting {}ms since last attempt (first attempt {}ms ago)", + dbg.msg_short, + dbg.msg_should_be, + dbg.since_last_attempt, + dbg.since_first_attempt); self.remove(ix); }, | _ => (), @@ -143,35 +127,31 @@ where }, | Some((state, msg)) if matches!(state, State::ConPreAck { .. }) => { let dbg = Self::debug(now, state, msg); - log!( - retry::Buf::mark_acked, - effects, - log::Level::Debug, - "{} request acked after waiting {}ms since last attempt (first attempt {}ms ago)", - dbg.msg_short, - dbg.since_last_attempt, - dbg.since_first_attempt - ); + log!(retry::Buf::mark_acked, + effects, + log::Level::Debug, + "{} request acked after waiting {}ms since last attempt (first attempt {}ms ago)", + dbg.msg_short, + dbg.since_last_attempt, + dbg.since_first_attempt); let timer = match state { - | State::ConPreAck { - post_ack_strategy, - post_ack_max_attempts, - .. - } => RetryTimer::new(now, *post_ack_strategy, *post_ack_max_attempts), + | State::ConPreAck { post_ack_strategy, + post_ack_max_attempts, + .. } => { + RetryTimer::new(now, *post_ack_strategy, *post_ack_max_attempts) + }, | _ => unreachable!(), }; *state = State::Just(timer); }, | _ => { - log!( - retry::Buf::mark_acked, - effects, - log::Level::Info, - "ACK {:?} does not apply to any known messages", - token - ); + log!(retry::Buf::mark_acked, + effects, + log::Level::Info, + "ACK {:?} does not apply to any known messages", + token); }, }; } @@ -183,23 +163,19 @@ where match found { | Some((state, msg)) => { let dbg = Self::debug(now, state, msg); - log!( - retry::Buf::mark_reset, - effects, - log::Level::Debug, - "{} got RESET, dropping all retry state.", - dbg.msg_short - ); + log!(retry::Buf::mark_reset, + effects, + log::Level::Debug, + "{} got RESET, dropping all retry state.", + dbg.msg_short); self.forget(now, effects, token) }, | _ => { - log!( - retry::Buf::mark_reset, - effects, - log::Level::Info, - "RESET {:?} does not correspond to any known messages", - token - ); + log!(retry::Buf::mark_reset, + effects, + log::Level::Info, + "RESET {:?} does not correspond to any known messages", + token); }, }; } @@ -208,12 +184,11 @@ where /// received /// /// May invoke `mark_acked` & `forget` - fn maybe_seen_response( - &mut self, - now: Instant, - effects: &mut P::Effects, - msg: Addrd<&platform::Message

>, - ) -> Result<(), Error> { + fn maybe_seen_response(&mut self, + now: Instant, + effects: &mut P::Effects, + msg: Addrd<&platform::Message

>) + -> Result<(), Error> { match (msg.data().ty, msg.data().code.kind()) { | (Type::Reset, _) => { self.mark_reset(now, effects, msg.data().token); @@ -230,14 +205,12 @@ where Ok(()) }, | _ => { - log!( - retry::Buf::maybe_seen_response, - effects, - log::Level::Trace, - "ignoring a {:?} {:?} message; could not possibly affect any pending retries", - msg.data().ty, - msg.data().code - ); + log!(retry::Buf::maybe_seen_response, + effects, + log::Level::Trace, + "ignoring a {:?} {:?} message; could not possibly affect any pending retries", + msg.data().ty, + msg.data().code); Ok(()) }, } @@ -245,66 +218,51 @@ where /// Called when a message of any kind is sent, /// and may store it to be retried in the future - fn store_retryables( - &mut self, - now: Instant, - effects: &mut P::Effects, - msg: &Addrd>, - config: Config, - ) -> Result<(), Error> { + fn store_retryables(&mut self, + now: Instant, + effects: &mut P::Effects, + msg: &Addrd>, + config: Config) + -> Result<(), Error> { match msg.data().ty { | Type::Con | Type::Non if self.is_full() => Err(Error::RetryBufferFull), | Type::Con => { - let timer = RetryTimer::new( - now, - config.msg.con.unacked_retry_strategy, - config.msg.con.max_attempts, - ); - self.push(( - State::ConPreAck { - timer, - post_ack_strategy: config.msg.con.acked_retry_strategy, - post_ack_max_attempts: config.msg.con.max_attempts, - }, - msg.clone(), - )); - - log!( - retry::Buf::store_retryables, - effects, - log::Level::Trace, - "sent CON {:?}; will retry if no ACK", - msg.data().code - ); + let timer = RetryTimer::new(now, + config.msg.con.unacked_retry_strategy, + config.msg.con.max_attempts); + self.push((State::ConPreAck { timer, + post_ack_strategy: config.msg.con.acked_retry_strategy, + post_ack_max_attempts: config.msg.con.max_attempts }, + msg.clone())); + + log!(retry::Buf::store_retryables, + effects, + log::Level::Trace, + "sent CON {:?}; will retry if no ACK", + msg.data().code); Ok(()) }, | Type::Non if msg.data().code.kind() == CodeKind::Request => { - log!( - retry::Buf::store_retryables, - effects, - log::Level::Trace, - "sent NON request {:?}; will retry if no response", - msg.data().code - ); - let timer = RetryTimer::new( - now, - config.msg.non.retry_strategy, - config.msg.non.max_attempts, - ); + log!(retry::Buf::store_retryables, + effects, + log::Level::Trace, + "sent NON request {:?}; will retry if no response", + msg.data().code); + let timer = RetryTimer::new(now, + config.msg.non.retry_strategy, + config.msg.non.max_attempts); self.push((State::Just(timer), msg.clone())); Ok(()) }, | _ => { - log!( - retry::Buf::store_retryables, - effects, - log::Level::Trace, - "{:?} {:?} will not be retried", - msg.data().ty, - msg.data().code - ); + log!(retry::Buf::store_retryables, + effects, + log::Level::Trace, + "{:?} {:?} will not be retried", + msg.data().ty, + msg.data().code); Ok(()) }, } @@ -312,17 +270,15 @@ where } impl Buf

for T -where - T: Array, Addrd>)>, - P: PlatformTypes, + where T: Array, Addrd>)>, + P: PlatformTypes { } /// The state of a message stored in the retry [buffer](Buf) #[derive(PartialEq, Eq, Debug)] pub enum State -where - C: Clock, + where C: Clock { /// A message that is not an un-acked CON /// @@ -344,9 +300,7 @@ where }, } -impl State -where - C: Clock, +impl State where C: Clock { /// Gets the current in-use retry timer pub fn retry_timer(&self) -> &RetryTimer { @@ -358,45 +312,33 @@ where } impl Copy for State where C: Clock {} -impl Clone for State -where - C: Clock, +impl Clone for State where C: Clock { fn clone(&self) -> Self { match self { | Self::Just(t) => Self::Just(*t), - | Self::ConPreAck { - timer, - post_ack_strategy, - post_ack_max_attempts, - } => Self::ConPreAck { - timer: *timer, - post_ack_strategy: *post_ack_strategy, - post_ack_max_attempts: *post_ack_max_attempts, + | Self::ConPreAck { timer, + post_ack_strategy, + post_ack_max_attempts, } => { + Self::ConPreAck { timer: *timer, + post_ack_strategy: *post_ack_strategy, + post_ack_max_attempts: *post_ack_max_attempts } }, } } } -impl Default for State -where - C: Clock, +impl Default for State where C: Clock { fn default() -> Self { - Self::new( - Instant::new(0), - Strategy::Delay { - min: Milliseconds(0), - max: Milliseconds(0), - }, - Attempts::default(), - ) + Self::new(Instant::new(0), + Strategy::Delay { min: Milliseconds(0), + max: Milliseconds(0) }, + Attempts::default()) } } -impl State -where - C: Clock, +impl State where C: Clock { fn new(time: Instant, strat: Strategy, max_attempts: Attempts) -> Self { Self::Just(RetryTimer::new(time, strat, max_attempts)) @@ -420,15 +362,12 @@ pub struct Retry { } impl Default for Retry -where - Inner: Default, - Buffer: Default, + where Inner: Default, + Buffer: Default { fn default() -> Self { - Self { - inner: Inner::default(), - buf: Stem::::default(), - } + Self { inner: Inner::default(), + buf: Stem::::default() } } } @@ -466,11 +405,10 @@ impl From for Error { } impl Step

for Retry -where - Buffer: Buf

, - P: PlatformTypes, - E: super::Error, - Inner: Step>, PollResp = Addrd>, Error = E>, + where Buffer: Buf

, + P: PlatformTypes, + E: super::Error, + Inner: Step>, PollResp = Addrd>, Error = E> { type PollReq = Addrd>; type PollResp = Addrd>; @@ -481,11 +419,10 @@ where &self.inner } - fn poll_req( - &self, - snap: &Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput { + fn poll_req(&self, + snap: &Snapshot

, + effects: &mut

::Effects) + -> StepOutput { // SERVER FLOW: // * CON responses WILL be retried // * NON responses WILL NOT be retried @@ -493,47 +430,43 @@ where // * RESET WILL NOT be retried _try!(Result; self.buf.map_mut(|b| b.attempt_all::(snap.time, effects))); - let req = self - .inner - .poll_req(snap, effects) - .map(|r| r.map_err(|nb| nb.map(Error::Inner))); + let req = self.inner + .poll_req(snap, effects) + .map(|r| r.map_err(|nb| nb.map(Error::Inner))); let req = _try!(Option; req); _try!(Result; self.buf.map_mut(|b| b.maybe_seen_response::(snap.time, effects, req.as_ref().map(|r| r.as_ref())))); Some(Ok(req)) } - fn poll_resp( - &self, - snap: &Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput { + fn poll_resp(&self, + snap: &Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput { // CLIENT FLOW: // * CON requests WILL be retried // * NON requests WILL be retried // * RESET WILL NOT be retried _try!(Result; self.buf.map_mut(|b| b.attempt_all::(snap.time, effects))); - let resp = self - .inner - .poll_resp(snap, effects, token, addr) - .map(|r| r.map_err(|nb| nb.map(Error::Inner))); + let resp = + self.inner + .poll_resp(snap, effects, token, addr) + .map(|r| r.map_err(|nb| nb.map(Error::Inner))); let resp = _try!(Option; resp); _try!(Result; self.buf.map_mut(|b| b.maybe_seen_response::(snap.time, effects, resp.as_ref().map(|r| r.as_ref())))); Some(Ok(resp)) } - fn on_message_sent( - &self, - snap: &platform::Snapshot

, - effects: &mut P::Effects, - msg: &Addrd>, - ) -> Result<(), Self::Error> { + fn on_message_sent(&self, + snap: &platform::Snapshot

, + effects: &mut P::Effects, + msg: &Addrd>) + -> Result<(), Self::Error> { self.inner.on_message_sent(snap, effects, msg)?; - self - .buf - .map_mut(|b| b.store_retryables(snap.time, effects, msg, snap.config)) + self.buf + .map_mut(|b| b.store_retryables(snap.time, effects, msg, snap.config)) } } @@ -553,38 +486,27 @@ mod tests { type Retry = super::Retry, Addrd>)>>; fn snap_time(config: Config, time: u64) -> test::Snapshot { - test::Snapshot { - config, - recvd_dgram: Some(Addrd(tinyvec::array_vec!(1), test::dummy_addr())), - time: ClockMock::instant(time * 1000), - } + test::Snapshot { config, + recvd_dgram: Some(Addrd(tinyvec::array_vec!(1), test::dummy_addr())), + time: ClockMock::instant(time * 1000) } } fn config(con_delay: u64, sec_delay: u64) -> Config { let con_delay = Milliseconds(con_delay); let sec_delay = Milliseconds(sec_delay); - let strategy_acked_con_or_non = Strategy::Delay { - min: sec_delay, - max: sec_delay, - }; - Config { - msg: config::Msg { - con: config::Con { - unacked_retry_strategy: Strategy::Delay { - min: con_delay, - max: con_delay, - }, - acked_retry_strategy: strategy_acked_con_or_non, - ..Default::default() - }, - non: config::Non { - retry_strategy: strategy_acked_con_or_non, - ..Default::default() - }, - ..Default::default() - }, - ..Default::default() - } + let strategy_acked_con_or_non = Strategy::Delay { min: sec_delay, + max: sec_delay }; + Config { msg: config::Msg { con: config::Con { unacked_retry_strategy: + Strategy::Delay { min: con_delay, + max: con_delay }, + acked_retry_strategy: + strategy_acked_con_or_non, + ..Default::default() }, + non: config::Non { retry_strategy: + strategy_acked_con_or_non, + ..Default::default() }, + ..Default::default() }, + ..Default::default() } } type InnerPollReq = Addrd; @@ -631,24 +553,23 @@ mod tests { let token = Token(array_vec![1, 2, 3]); let token: &'static Token = unsafe { core::mem::transmute::<_, _>(&token) }; s.inner() - .set_poll_resp(|_, Snapshot { time, .. }, _, _, _| { - let time: u64 = Milliseconds::try_from(time.duration_since_epoch()) - .unwrap() - .0; - - let mut rep = test::msg!(ACK EMPTY x.x.x.x:0000); - rep.as_mut().token = *token; - - match time { - | 350 => Some(Ok(rep.map(Resp::from))), - | 850 => { - rep.as_mut().ty = Type::Non; - rep.as_mut().code = Code::new(2, 4); - Some(Ok(rep.map(Resp::from))) - }, - | _ => None, - } - }); + .set_poll_resp(|_, Snapshot { time, .. }, _, _, _| { + let time: u64 = Milliseconds::try_from(time.duration_since_epoch()).unwrap() + .0; + + let mut rep = test::msg!(ACK EMPTY x.x.x.x:0000); + rep.as_mut().token = *token; + + match time { + | 350 => Some(Ok(rep.map(Resp::from))), + | 850 => { + rep.as_mut().ty = Type::Non; + rep.as_mut().code = Code::new(2, 4); + Some(Ok(rep.map(Resp::from))) + }, + | _ => None, + } + }); let cfg = config(200, 400); let mut effs = Vec::::new(); macro_rules! sent { @@ -671,80 +592,64 @@ mod tests { req.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &req) - .unwrap(); - - s.poll_resp( - &snap_time(cfg, 150), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + .unwrap(); + + s.poll_resp(&snap_time(cfg, 150), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); - s.poll_resp( - &snap_time(cfg, 250), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 250), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); - let ack = s - .poll_resp( - &snap_time(cfg, 350), - &mut effs, - req.data().token, - req.addr(), - ) - .unwrap() - .unwrap(); + let ack = s.poll_resp(&snap_time(cfg, 350), + &mut effs, + req.data().token, + req.addr()) + .unwrap() + .unwrap(); assert_eq!(ack.data().msg().ty, Type::Ack); assert_eq!(sent!().len(), 1); - s.poll_resp( - &snap_time(cfg, 550), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 550), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); - s.poll_resp( - &snap_time(cfg, 750), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 750), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 2); - let rep = s - .poll_resp( - &snap_time(cfg, 850), - &mut effs, - req.data().token, - req.addr(), - ) - .unwrap() - .unwrap(); + let rep = s.poll_resp(&snap_time(cfg, 850), + &mut effs, + req.data().token, + req.addr()) + .unwrap() + .unwrap(); assert_eq!(rep.data().msg().ty, Type::Non); assert_eq!(sent!().len(), 2); - s.poll_resp( - &snap_time(cfg, 10_000), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 10_000), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 2); } @@ -770,32 +675,30 @@ mod tests { let token_c: &'static Token = unsafe { core::mem::transmute::<_, _>(&token_c) }; s.inner() - .set_poll_resp(|_, Snapshot { time, .. }, _, token, _| { - let time: u64 = Milliseconds::try_from(time.duration_since_epoch()) - .unwrap() - .0; - - let mut rst = test::msg!(RESET x.x.x.x:0000); - rst.as_mut().token = token; - - match time { - | 150 => Some(Ok(rst.map(Resp::from))), - | _ => None, - } - }) - .set_poll_req(|_, Snapshot { time, .. }, _| { - let time: u64 = Milliseconds::try_from(time.duration_since_epoch()) - .unwrap() - .0; - - let mut rst = test::msg!(RESET x.x.x.x:0000); - rst.as_mut().token = *token_c; - - match time { - | 150 => Some(Ok(rst.map(Req::from))), - | _ => None, - } - }); + .set_poll_resp(|_, Snapshot { time, .. }, _, token, _| { + let time: u64 = Milliseconds::try_from(time.duration_since_epoch()).unwrap() + .0; + + let mut rst = test::msg!(RESET x.x.x.x:0000); + rst.as_mut().token = token; + + match time { + | 150 => Some(Ok(rst.map(Resp::from))), + | _ => None, + } + }) + .set_poll_req(|_, Snapshot { time, .. }, _| { + let time: u64 = Milliseconds::try_from(time.duration_since_epoch()).unwrap() + .0; + + let mut rst = test::msg!(RESET x.x.x.x:0000); + rst.as_mut().token = *token_c; + + match time { + | 150 => Some(Ok(rst.map(Req::from))), + | _ => None, + } + }); let cfg = config(200, 400); let mut effs = Vec::::new(); macro_rules! sent { @@ -824,42 +727,39 @@ mod tests { con_rep.as_mut().token = *token_c; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &con_rep) - .unwrap(); + .unwrap(); s.on_message_sent(&snap_time(cfg, 50), &mut effs, &con_req) - .unwrap(); + .unwrap(); s.on_message_sent(&snap_time(cfg, 50), &mut effs, &non_req) - .unwrap(); + .unwrap(); - let rep = s - .poll_resp(&snap_time(cfg, 150), &mut effs, *token_a, con_req.addr()) - .unwrap() - .unwrap(); + let rep = s.poll_resp(&snap_time(cfg, 150), &mut effs, *token_a, con_req.addr()) + .unwrap() + .unwrap(); assert_eq!(sent!().len(), 0); assert_eq!(rep.data().msg().ty, Type::Reset); - let rep = s - .poll_resp(&snap_time(cfg, 150), &mut effs, *token_b, con_req.addr()) - .unwrap() - .unwrap(); + let rep = s.poll_resp(&snap_time(cfg, 150), &mut effs, *token_b, con_req.addr()) + .unwrap() + .unwrap(); assert_eq!(sent!().len(), 0); assert_eq!(rep.data().msg().ty, Type::Reset); - let req = s - .poll_req(&snap_time(cfg, 150), &mut effs) - .unwrap() - .unwrap(); + let req = s.poll_req(&snap_time(cfg, 150), &mut effs) + .unwrap() + .unwrap(); assert_eq!(sent!().len(), 0); assert_eq!(req.data().msg().ty, Type::Reset); s.poll_resp(&snap_time(cfg, 10_000), &mut effs, *token_a, con_req.addr()) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); s.poll_resp(&snap_time(cfg, 10_000), &mut effs, *token_b, con_req.addr()) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); s.poll_req(&snap_time(cfg, 10_000), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); } @@ -880,18 +780,17 @@ mod tests { let token = Token(array_vec![1, 2, 3]); let token: &'static Token = unsafe { core::mem::transmute::<_, _>(&token) }; s.inner().set_poll_req(|_, Snapshot { time, .. }, _| { - let time: u64 = Milliseconds::try_from(time.duration_since_epoch()) - .unwrap() - .0; - - let mut ack = test::msg!(ACK EMPTY x.x.x.x:0000); - ack.as_mut().token = *token; - - match time { - | 350 => Some(Ok(ack.map(Req::from))), - | _ => None, - } - }); + let time: u64 = Milliseconds::try_from(time.duration_since_epoch()).unwrap() + .0; + + let mut ack = test::msg!(ACK EMPTY x.x.x.x:0000); + ack.as_mut().token = *token; + + match time { + | 350 => Some(Ok(ack.map(Req::from))), + | _ => None, + } + }); let cfg = config(200, 400); let mut effs = Vec::::new(); macro_rules! sent { @@ -914,28 +813,27 @@ mod tests { rep.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &rep) - .unwrap(); + .unwrap(); s.poll_req(&snap_time(cfg, 150), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); s.poll_req(&snap_time(cfg, 250), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); - let ack = s - .poll_req(&snap_time(cfg, 350), &mut effs) - .unwrap() - .unwrap(); + let ack = s.poll_req(&snap_time(cfg, 350), &mut effs) + .unwrap() + .unwrap(); assert_eq!(ack.data().msg().ty, Type::Ack); assert_eq!(sent!().len(), 1); s.poll_req(&snap_time(cfg, 10_000), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); } @@ -954,19 +852,18 @@ mod tests { let token = Token(array_vec![1, 2, 3]); let token: &'static Token = unsafe { core::mem::transmute::<_, _>(&token) }; s.inner() - .set_poll_resp(|_, Snapshot { time, .. }, _, _, _| { - let time: u64 = Milliseconds::try_from(time.duration_since_epoch()) - .unwrap() - .0; - - let mut rep = test::msg!(NON {2 . 04} x.x.x.x:0000); - rep.as_mut().token = *token; - - match time { - | 350 => Some(Ok(rep.map(Resp::from))), - | _ => None, - } - }); + .set_poll_resp(|_, Snapshot { time, .. }, _, _, _| { + let time: u64 = Milliseconds::try_from(time.duration_since_epoch()).unwrap() + .0; + + let mut rep = test::msg!(NON {2 . 04} x.x.x.x:0000); + rep.as_mut().token = *token; + + match time { + | 350 => Some(Ok(rep.map(Resp::from))), + | _ => None, + } + }); let cfg = config(200, 200); let mut effs = Vec::::new(); macro_rules! sent { @@ -989,48 +886,39 @@ mod tests { req.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &req) - .unwrap(); - - s.poll_resp( - &snap_time(cfg, 150), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + .unwrap(); + + s.poll_resp(&snap_time(cfg, 150), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); - s.poll_resp( - &snap_time(cfg, 250), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 250), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); - let rep = s - .poll_resp( - &snap_time(cfg, 350), - &mut effs, - req.data().token, - req.addr(), - ) - .unwrap() - .unwrap(); + let rep = s.poll_resp(&snap_time(cfg, 350), + &mut effs, + req.data().token, + req.addr()) + .unwrap() + .unwrap(); assert_eq!(rep.data().msg().ty, Type::Non); assert_eq!(sent!().len(), 1); - s.poll_resp( - &snap_time(cfg, 10_000), - &mut effs, - req.data().token, - req.addr(), - ) - .ok_or(()) - .unwrap_err(); + s.poll_resp(&snap_time(cfg, 10_000), + &mut effs, + req.data().token, + req.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 1); } @@ -1069,21 +957,19 @@ mod tests { ack.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &ack) - .unwrap(); - - s.poll_resp( - &snap_time(cfg, 10_000), - &mut effs, - ack.data().token, - ack.addr(), - ) - .ok_or(()) - .unwrap_err(); + .unwrap(); + + s.poll_resp(&snap_time(cfg, 10_000), + &mut effs, + ack.data().token, + ack.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); s.poll_req(&snap_time(cfg, 10_000), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); } @@ -1122,21 +1008,19 @@ mod tests { rep.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &rep) - .unwrap(); - - s.poll_resp( - &snap_time(cfg, 10_000), - &mut effs, - rep.data().token, - rep.addr(), - ) - .ok_or(()) - .unwrap_err(); + .unwrap(); + + s.poll_resp(&snap_time(cfg, 10_000), + &mut effs, + rep.data().token, + rep.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); s.poll_req(&snap_time(cfg, 10_000), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); } @@ -1175,21 +1059,19 @@ mod tests { rst.as_mut().token = *token; s.on_message_sent(&snap_time(cfg, 50), &mut effs, &rst) - .unwrap(); - - s.poll_resp( - &snap_time(cfg, 10_000), - &mut effs, - rst.data().token, - rst.addr(), - ) - .ok_or(()) - .unwrap_err(); + .unwrap(); + + s.poll_resp(&snap_time(cfg, 10_000), + &mut effs, + rst.data().token, + rst.addr()) + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); s.poll_req(&snap_time(cfg, 10_000), &mut effs) - .ok_or(()) - .unwrap_err(); + .ok_or(()) + .unwrap_err(); assert_eq!(sent!().len(), 0); } } diff --git a/toad/src/step/set_standard_options.rs b/toad/src/step/set_standard_options.rs index 2bdefc78..2bdc04a0 100644 --- a/toad/src/step/set_standard_options.rs +++ b/toad/src/step/set_standard_options.rs @@ -18,9 +18,7 @@ use crate::resp::Resp; #[derive(Debug)] pub struct SetStandardOptions(S); -impl Default for SetStandardOptions -where - S: Default, +impl Default for SetStandardOptions where S: Default { fn default() -> Self { Self(S::default()) @@ -28,10 +26,9 @@ where } impl Step

for SetStandardOptions -where - P: PlatformTypes, - E: super::Error, - S: Step>, PollResp = Addrd>, Error = E>, + where P: PlatformTypes, + E: super::Error, + S: Step>, PollResp = Addrd>, Error = E> { type PollReq = Addrd>; type PollResp = Addrd>; @@ -42,30 +39,27 @@ where &self.0 } - fn poll_req( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - ) -> StepOutput { + fn poll_req(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects) + -> StepOutput { self.0.poll_req(snap, effects) } - fn poll_resp( - &self, - snap: &crate::platform::Snapshot

, - effects: &mut

::Effects, - token: toad_msg::Token, - addr: no_std_net::SocketAddr, - ) -> StepOutput { + fn poll_resp(&self, + snap: &crate::platform::Snapshot

, + effects: &mut

::Effects, + token: toad_msg::Token, + addr: no_std_net::SocketAddr) + -> StepOutput { self.0.poll_resp(snap, effects, token, addr) } - fn before_message_sent( - &self, - snap: &platform::Snapshot

, - effs: &mut P::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + snap: &platform::Snapshot

, + effs: &mut P::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { self.0.before_message_sent(snap, effs, msg)?; let (host, port) = (msg.addr().ip(), msg.addr().port()); @@ -93,18 +87,14 @@ mod test { fn test_message(ty: Type) -> Addrd { use toad_msg::*; - Addrd( - crate::test::Message { - ver: Default::default(), - ty, - id: Id(1), - code: Code::new(1, 1), - token: Token(array_vec!(_ => 1)), - payload: Payload(Default::default()), - opts: Default::default(), - }, - crate::test::dummy_addr(), - ) + Addrd(crate::test::Message { ver: Default::default(), + ty, + id: Id(1), + code: Code::new(1, 1), + token: Token(array_vec!(_ => 1)), + payload: Payload(Default::default()), + opts: Default::default() }, + crate::test::dummy_addr()) } test_step!( diff --git a/toad/src/test.rs b/toad/src/test.rs index 20d1e3b6..e6e9e243 100644 --- a/toad/src/test.rs +++ b/toad/src/test.rs @@ -1,4 +1,5 @@ #![allow(dead_code)] +#![allow(missing_docs)] use ::core::cell::Cell; use ::core::ops::Deref; @@ -99,11 +100,9 @@ pub type Req = crate::req::Req; pub type Resp = crate::resp::Resp; pub fn snapshot() -> Snapshot { - Snapshot { - config: Default::default(), - time: ClockMock::instant(0), - recvd_dgram: None, - } + Snapshot { config: Default::default(), + time: ClockMock::instant(0), + recvd_dgram: None } } pub fn dummy_addr() -> SocketAddr { @@ -123,91 +122,80 @@ pub mod stepfn { use super::*; pub trait poll_req - where - Self: 'static - + for<'a> FnMut(&'a Self_, &'a Snapshot, &'a mut Vec) -> Option>, + where Self: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec) + -> Option> { } - impl poll_req for T where - T: 'static - + for<'a> FnMut(&'a Self_, &'a Snapshot, &'a mut Vec) -> Option> + impl poll_req for T + where T: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec) + -> Option> { } pub trait poll_resp - where - Self: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - Token, - SocketAddr, - ) -> Option>, + where Self: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + Token, + SocketAddr) -> Option> { } - impl poll_resp for T where - T: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - Token, - SocketAddr, - ) -> Option> + impl poll_resp for T + where T: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + Token, + SocketAddr) -> Option> { } pub trait notify - where - Self: 'static + for<'a> FnMut(&'a Self_, &'a str, &'a mut Vec) -> Result<(), E>, + where Self: 'static + for<'a> FnMut(&'a Self_, &'a str, &'a mut Vec) -> Result<(), E> { } - impl notify for T where - T: 'static + for<'a> FnMut(&'a Self_, &'a str, &'a mut Vec) -> Result<(), E> + impl notify for T + where T: 'static + for<'a> FnMut(&'a Self_, &'a str, &'a mut Vec) -> Result<(), E> { } pub trait before_message_sent - where - Self: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - &'a mut Addrd, - ) -> Result<(), E>, + where Self: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + &'a mut Addrd) -> Result<(), E> { } - impl before_message_sent for T where - T: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - &'a mut Addrd, - ) -> Result<(), E> + impl before_message_sent for T + where T: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + &'a mut Addrd) -> Result<(), E> { } pub trait on_message_sent - where - Self: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - &'a Addrd, - ) -> Result<(), E>, + where Self: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + &'a Addrd) -> Result<(), E> { } - impl on_message_sent for T where - T: 'static - + for<'a> FnMut( - &'a Self_, - &'a Snapshot, - &'a mut Vec, - &'a Addrd, - ) -> Result<(), E> + impl on_message_sent for T + where T: 'static + + for<'a> FnMut(&'a Self_, + &'a Snapshot, + &'a mut Vec, + &'a Addrd) -> Result<(), E> { } } @@ -229,8 +217,7 @@ impl MockStep { } pub fn init_default(&self) -> &Self - where - State: Default, + where State: Default { self.init(Default::default()) } @@ -268,20 +255,17 @@ impl MockStep { impl Default for MockStep { fn default() -> Self { - Self { - poll_req: RwLock::new(Box::new(|_, _, _| None)), - poll_resp: RwLock::new(Box::new(|_, _, _, _, _| None)), - notify: RwLock::new(Box::new(|_, _, _| Ok(()))), - before_message_sent: RwLock::new(Box::new(|_, _, _, _| Ok(()))), - on_message_sent: RwLock::new(Box::new(|_, _, _, _| Ok(()))), - state: Stem::new(None), - } + Self { poll_req: RwLock::new(Box::new(|_, _, _| None)), + poll_resp: RwLock::new(Box::new(|_, _, _, _, _| None)), + notify: RwLock::new(Box::new(|_, _, _| Ok(()))), + before_message_sent: RwLock::new(Box::new(|_, _, _, _| Ok(()))), + on_message_sent: RwLock::new(Box::new(|_, _, _, _| Ok(()))), + state: Stem::new(None) } } } impl crate::step::Step for MockStep -where - E: From<()> + crate::step::Error, + where E: From<()> + crate::step::Error { type PollReq = Rq; type PollResp = Rp; @@ -292,50 +276,45 @@ where &() } - fn poll_req( - &self, - snap: &platform::Snapshot, - effects: &mut ::Effects, - ) -> step::StepOutput { + fn poll_req(&self, + snap: &platform::Snapshot, + effects: &mut ::Effects) + -> step::StepOutput { let mut g = self.poll_req.try_write().unwrap(); g.as_mut()(self, snap, effects) } - fn poll_resp( - &self, - snap: &platform::Snapshot, - effects: &mut ::Effects, - token: Token, - addr: SocketAddr, - ) -> step::StepOutput { + fn poll_resp(&self, + snap: &platform::Snapshot, + effects: &mut ::Effects, + token: Token, + addr: SocketAddr) + -> step::StepOutput { let mut g = self.poll_resp.try_write().unwrap(); g.as_mut()(self, snap, effects, token, addr) } fn notify(&self, path: Path, effects: &mut Vec) -> Result<(), Self::Error> - where - Path: AsRef + Clone, + where Path: AsRef + Clone { let mut g = self.notify.try_write().unwrap(); g.as_mut()(self, path.as_ref(), effects) } - fn before_message_sent( - &self, - snap: &platform::Snapshot, - effects: &mut ::Effects, - msg: &mut Addrd>, - ) -> Result<(), Self::Error> { + fn before_message_sent(&self, + snap: &platform::Snapshot, + effects: &mut ::Effects, + msg: &mut Addrd>) + -> Result<(), Self::Error> { let mut g = self.before_message_sent.try_write().unwrap(); g.as_mut()(self, snap, effects, msg) } - fn on_message_sent( - &self, - snap: &platform::Snapshot, - effects: &mut Vec, - msg: &Addrd>, - ) -> Result<(), Self::Error> { + fn on_message_sent(&self, + snap: &platform::Snapshot, + effects: &mut Vec, + msg: &Addrd>) + -> Result<(), Self::Error> { let mut g = self.on_message_sent.try_write().unwrap(); g.as_mut()(self, snap, effects, msg) } @@ -354,10 +333,8 @@ pub struct Timeout { impl Timeout { pub fn new(dur: Duration) -> Self { - Self { - state: Arc::new(Mutex::new(TimeoutState::WillPanic)), - dur, - } + Self { state: Arc::new(Mutex::new(TimeoutState::WillPanic)), + dur } } pub fn cancel(state: Arc>) { @@ -419,25 +396,20 @@ pub struct SockMock { impl SockMock { pub fn new() -> Self { - Self { - rx: Default::default(), - tx: Default::default(), - } + Self { rx: Default::default(), + tx: Default::default() } } - pub fn send_msg( - rx: &Arc>>>>, - msg: Addrd>, - ) { + pub fn send_msg(rx: &Arc>>>>, + msg: Addrd>) { rx.lock() .unwrap() .push(msg.map(|msg| msg.try_into_bytes().unwrap())); } - pub fn await_msg( - addr: SocketAddr, - tx: &Arc>>>>, - ) -> platform::Message

{ + pub fn await_msg(addr: SocketAddr, + tx: &Arc>>>>) + -> platform::Message

{ let attempt = || { tx.lock() .unwrap() @@ -473,11 +445,10 @@ impl Socket for SockMock { let dgram = rx.drain(0..1).next().unwrap(); - dgram - .data() - .iter() - .enumerate() - .for_each(|(ix, byte)| buf[ix] = *byte); + dgram.data() + .iter() + .enumerate() + .for_each(|(ix, byte)| buf[ix] = *byte); Ok(dgram.map(|bytes| bytes.len())) } diff --git a/toad/src/time.rs b/toad/src/time.rs index 17fd22bc..b6750bd6 100644 --- a/toad/src/time.rs +++ b/toad/src/time.rs @@ -28,16 +28,14 @@ impl core::fmt::Debug for Stamped { use core::fmt::Write; let mut instant = String::<100>::default(); - write!( - instant, - "<{}ms since epoch>", - Millis::try_from(self.1.duration_since_epoch()).unwrap() - )?; + write!(instant, + "<{}ms since epoch>", + Millis::try_from(self.1.duration_since_epoch()).unwrap())?; f.debug_tuple("Stamped") - .field(&self.0) - .field(&instant) - .finish() + .field(&self.0) + .field(&instant) + .finish() } } @@ -123,10 +121,7 @@ impl Stamped { /// TODO pub fn find_latest(winner: Option>, cur: Stamped) -> Option> { - Some( - winner - .filter(|winner| winner.time() > cur.time()) - .unwrap_or(cur), - ) + Some(winner.filter(|winner| winner.time() > cur.time()) + .unwrap_or(cur)) } } diff --git a/toad/src/todo.rs b/toad/src/todo.rs index 4866a840..90fd3475 100644 --- a/toad/src/todo.rs +++ b/toad/src/todo.rs @@ -54,9 +54,7 @@ impl String { pub fn resize(&mut self) -> String { let mut bytes = self.0.unwrap(); bytes.truncate(M); - String(Writable::from( - self.as_writable().drain(..).collect::>(), - )) + String(Writable::from(self.as_writable().drain(..).collect::>())) } /// Alias for [`AsRef`] @@ -147,9 +145,9 @@ pub(crate) trait NbResultExt { impl NbResultExt for ::nb::Result { fn perform_nb_err(self, f: impl FnOnce(&E) -> ()) -> ::nb::Result { self.discard_err(|e: &::nb::Error| match e { - | &::nb::Error::Other(ref e) => f(e), - | &::nb::Error::WouldBlock => (), - }) + | &::nb::Error::Other(ref e) => f(e), + | &::nb::Error::WouldBlock => (), + }) } #[cfg(feature = "std")] @@ -179,23 +177,20 @@ pub(crate) mod nb { }; ($stuff:expr, timeout_after = $duration:expr, timeout_err = $timeout_err:expr) => {{ let start = ::std::time::Instant::now(); - $crate::todo::nb::block!( - $stuff, - with = || { - if ::std::time::Instant::now() - start > $duration { - Some(Err($timeout_err())) - } else { - None - } - } - ) + $crate::todo::nb::block!($stuff, + with = || { + if ::std::time::Instant::now() - start > $duration { + Some(Err($timeout_err())) + } else { + None + } + }) }}; ($stuff:expr, io_timeout_after = $duration:expr) => { - $crate::todo::nb::block!( - $stuff, - timeout_after = $duration, - timeout_err = || ::std::io::Error::from(::std::io::ErrorKind::TimedOut) - ) + $crate::todo::nb::block!($stuff, + timeout_after = $duration, + timeout_err = + || ::std::io::Error::from(::std::io::ErrorKind::TimedOut)) }; }