commit 31fc9ebb9296c7b39ae15f076003eef5b33e50c3 Author: PIVODEVAT Date: Sat Dec 13 21:43:14 2025 +0300 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0ab2920 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2083 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom 0.2.16", + "once_cell", + "version_check", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "array-init-cursor" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed51fe0f224d1d4ea768be38c51f9f831dee9d05c163c11fba0b8c44387b1fc3" + +[[package]] +name = "ascii-canvas" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8824ecca2e851cec16968d54a01dd372ef8f95b244fb84b84e70128be347c3c6" +dependencies = [ + "term", +] + +[[package]] +name = "askama" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb98f10f371286b177db5eeb9a6e5396609555686a35e1d4f7b9a9c6d8af0139" +dependencies = [ + "askama_derive", + "askama_escape", + "askama_shared", +] + +[[package]] +name = "askama_derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87bf87e6e8b47264efa9bde63d6225c6276a52e05e91bf37eaa8afd0032d6b71" +dependencies = [ + "askama_shared", + "proc-macro2", + "syn 1.0.109", +] + +[[package]] +name = "askama_escape" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341" + +[[package]] +name = "askama_shared" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf722b94118a07fcbc6640190f247334027685d4e218b794dbfe17c32bf38ed0" +dependencies = [ + "askama_escape", + "humansize", + "mime", + "mime_guess", + "nom", + "num-traits", + "percent-encoding", + "proc-macro2", + "quote", + "serde", + "syn 1.0.109", + "toml", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + +[[package]] +name = "async-executor" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand 2.3.0", + "futures-lite 2.6.1", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-lock" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" +dependencies = [ + "event-listener", +] + +[[package]] +name = "async-oneshot" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae47de2a02d543205f3f5457a90b6ecbc9494db70557bd29590ec8f1ddff5463" +dependencies = [ + "futures-micro", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "atomic-take" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ab6b55fe97976e46f91ddbed8d147d966475dc29b2032757ba47e02376fbc3" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "axum" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59446ce19cd142f8833f856eb31f3eb097812d1479ab224f54d72428ca21ea22" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "beef" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" + +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" + +[[package]] +name = "bitpattern" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fc436c543b5fd522e5428d65c88e7bfb538ba267dad95cfb9d8fb8a465b0935" +dependencies = [ + "paste", + "proc-macro2", + "quote", +] + +[[package]] +name = "blackwriter-server" +version = "0.1.0" +dependencies = [ + "axum", + "mediasoup", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "bytes" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "codespan" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3362992a0d9f1dd7c3d0e89e0ab2bb540b7a95fea8cd798090e758fda2899b5e" +dependencies = [ + "codespan-reporting", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.111", +] + +[[package]] +name = "dirs-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "ena" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d248bdd43ce613d87415282f69b9bb99d947d290b10962dd6c56233312c2ad5" +dependencies = [ + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener-primitives" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5384093b4255393cc8c42f0fc3dd4f19977ad3b1025f968257854895a993028c" +dependencies = [ + "nohash-hasher", + "parking_lot 0.11.2", + "smallvec", +] + +[[package]] +name = "eyre" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec" +dependencies = [ + "indenter", + "once_cell", +] + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand 2.3.0", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-micro" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b460264b3593d68b16a7bc35f7bc226ddfebdf9a1c8db1ed95d5cc6b7168c826" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "pin-utils", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "h264-profile-level-id" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45d0dbf6a9847b64c9b06938660891f983434dcc009b5ae6a58f5e34af74a649" +dependencies = [ + "bitpattern", + "log", + "thiserror 1.0.69", +] + +[[package]] +name = "hash_hasher" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b4b9ebce26001bad2e6366295f64e381c1e9c479109202149b9e15e154973e9" + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +dependencies = [ + "ahash 0.7.8", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" +dependencies = [ + "ahash 0.8.12", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humansize" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02296996cb8796d7c6e3bc2d9211b7802812d36999a51bb754123ead7d37d026" + +[[package]] +name = "hyper" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "indenter" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", +] + +[[package]] +name = "indexmap" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "js-sys" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lalrpop" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55cb077ad656299f160924eb2912aa147d7339ea7d69e1b5517326fdcec3c1ca" +dependencies = [ + "ascii-canvas", + "bit-set", + "ena", + "itertools", + "lalrpop-util", + "petgraph", + "pico-args", + "regex", + "regex-syntax 0.8.8", + "string_cache", + "term", + "tiny-keccak", + "unicode-xid", + "walkdir", +] + +[[package]] +name = "lalrpop-util" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "libc" +version = "0.2.178" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" + +[[package]] +name = "libredox" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +dependencies = [ + "bitflags 2.9.0", + "libc", +] + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", + "serde", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "logos" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf8b031682c67a8e3d5446840f9573eb7fe26efe7ec8d195c9ac4c0647c502f1" +dependencies = [ + "logos-derive", +] + +[[package]] +name = "logos-derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d849148dbaf9661a6151d1ca82b13bb4c4c128146a88d05253b38d4e2f496c" +dependencies = [ + "beef", + "fnv", + "proc-macro2", + "quote", + "regex-syntax 0.6.29", + "syn 1.0.109", +] + +[[package]] +name = "lru" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "mediasoup" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e98865ad6bd08f48bf380cf11fd06d9d78638c11cae1f78f8dfa7dfbfead39e" +dependencies = [ + "async-channel", + "async-executor", + "async-lock", + "async-oneshot", + "async-trait", + "atomic-take", + "event-listener-primitives", + "fastrand 1.9.0", + "futures-lite 1.13.0", + "h264-profile-level-id", + "hash_hasher", + "log", + "lru", + "mediasoup-sys", + "mediasoup-types", + "nohash-hasher", + "once_cell", + "parking_lot 0.12.3", + "planus", + "regex", + "serde", + "serde_json", + "serde_repr", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "mediasoup-sys" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca610ebc75215b7530027e3f1a171bb35337eff96b9e9df5ad19f189136df61f" +dependencies = [ + "planus", + "planus-codegen", + "planus-translation", + "serde", +] + +[[package]] +name = "mediasoup-types" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53ec9d899d198e0a9e992daef34a49f0031f1a2b44079e6a0ef6e91781b5b5bd" +dependencies = [ + "once_cell", + "regex", + "serde", + "serde_json", + "thiserror 2.0.17", +] + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core 0.8.6", +] + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core 0.9.10", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "winapi", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.10", + "smallvec", + "windows-targets 0.52.6", +] + +[[package]] +name = "paste" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880" +dependencies = [ + "paste-impl", + "proc-macro-hack", +] + +[[package]] +name = "paste-impl" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6" +dependencies = [ + "proc-macro-hack", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap 2.12.1", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "planus" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cbec589fda965e8d0cf7dddaa87d37ae5ccaed0c43986e8faf5998f24ef82f5" +dependencies = [ + "array-init-cursor", + "hashbrown 0.13.2", +] + +[[package]] +name = "planus-codegen" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d1bb11066c61d46d6d8f21d342d300f06d08bcce15f88399fdd40e1341c421" +dependencies = [ + "askama", + "eyre", + "heck", + "planus-types", + "random_color", + "thiserror 1.0.69", + "vec_map", +] + +[[package]] +name = "planus-lexer" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ecb00082b1324541f02f323585333e88ed3bf90cdbad3741e52eabf166fbcd6" +dependencies = [ + "codespan", + "derive_more", + "logos", +] + +[[package]] +name = "planus-translation" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7bd8ffea859844a23ea28d58354e9e466f3454981b368ba7d8226edac50398b" +dependencies = [ + "atty", + "bitflags 2.9.0", + "codespan", + "codespan-reporting", + "indexmap 1.9.3", + "lalrpop", + "lalrpop-util", + "num-traits", + "planus-lexer", + "planus-types", + "string-interner", +] + +[[package]] +name = "planus-types" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10306bda3579cc7a43537cb3f81212d93ce4fea32a219d9c0a7788d8c5d8e114" +dependencies = [ + "codespan", + "indexmap 1.9.3", + "lalrpop-util", + "planus-lexer", + "string-interner", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha", + "rand_core", + "rand_hc", + "rand_pcg", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_pcg" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429" +dependencies = [ + "rand_core", +] + +[[package]] +name = "random_color" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f34bd6526786b2ce5141fd37a4084b5da1ebae74595b5b0d05482a7cef7181" +dependencies = [ + "rand", +] + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1" +dependencies = [ + "bitflags 2.9.0", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax 0.8.8", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.8", +] + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[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.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "string-interner" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e2531d8525b29b514d25e275a43581320d587b86db302b9a7e464bac579648" +dependencies = [ + "cfg-if", + "hashbrown 0.11.2", + "serde", +] + +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot 0.12.3", + "phf_shared", + "precomputed-hash", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "term" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" +dependencies = [ + "dirs-next", + "rustversion", + "winapi", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl 2.0.17", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + +[[package]] +name = "tokio" +version = "1.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot 0.12.3", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + +[[package]] +name = "tower" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "uuid" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" +dependencies = [ + "getrandom 0.3.4", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.111", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +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.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "zerocopy" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f353b3e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "blackwriter-server" +version = "0.1.0" +edition = "2024" + +[dependencies] +axum = "0.8.7" +mediasoup = "0.20.0" +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0" +tokio = { version = "1.48.0", features = ["full"] } diff --git a/doc/axum.md b/doc/axum.md new file mode 100644 index 0000000..582c4b2 --- /dev/null +++ b/doc/axum.md @@ -0,0 +1,15350 @@ +# Crate Documentation + +**Version:** 0.8.7 + +**Format Version:** 56 + +# Module `axum` + +axum is a web application framework that focuses on ergonomics and modularity. + +# High-level features + +- Route requests to handlers with a macro-free API. +- Declaratively parse requests using extractors. +- Simple and predictable error handling model. +- Generate responses with minimal boilerplate. +- Take full advantage of the [`tower`] and [`tower-http`] ecosystem of + middleware, services, and utilities. + +In particular, the last point is what sets `axum` apart from other frameworks. +`axum` doesn't have its own middleware system but instead uses +[`tower::Service`]. This means `axum` gets timeouts, tracing, compression, +authorization, and more, for free. It also enables you to share middleware with +applications written using [`hyper`] or [`tonic`]. + +# Compatibility + +axum is designed to work with [tokio] and [hyper]. Runtime and +transport layer independence is not a goal, at least for the time being. + +# Example + +The "Hello, World!" of axum is: + +```rust,no_run +use axum::{ + routing::get, + Router, +}; + +#[tokio::main] +async fn main() { + // build our application with a single route + let app = Router::new().route("/", get(|| async { "Hello, World!" })); + + // run our app with hyper, listening globally on port 3000 + let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + axum::serve(listener, app).await.unwrap(); +} +``` + +Note using `#[tokio::main]` requires you enable tokio's `macros` and `rt-multi-thread` features +or just `full` to enable all features (`cargo add tokio --features macros,rt-multi-thread`). + +# Routing + +[`Router`] is used to set up which paths go to which services: + +```rust +use axum::{Router, routing::get}; + +// our router +let app = Router::new() + .route("/", get(root)) + .route("/foo", get(get_foo).post(post_foo)) + .route("/foo/bar", get(foo_bar)); + +// which calls one of these handlers +async fn root() {} +async fn get_foo() {} +async fn post_foo() {} +async fn foo_bar() {} +# let _: Router = app; +``` + +See [`Router`] for more details on routing. + +# Handlers + +In axum a "handler" is an async function that accepts zero or more +["extractors"](crate::extract) as arguments and returns something that +can be converted [into a response](crate::response). + +Handlers are where your application logic lives and axum applications are built +by routing between handlers. + +[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html + +See [`handler`](crate::handler) for more details on handlers. + +# Extractors + +An extractor is a type that implements [`FromRequest`] or [`FromRequestParts`]. Extractors are +how you pick apart the incoming request to get the parts your handler needs. + +```rust +use axum::extract::{Path, Query, Json}; +use std::collections::HashMap; + +// `Path` gives you the path parameters and deserializes them. +async fn path(Path(user_id): Path) {} + +// `Query` gives you the query parameters and deserializes them. +async fn query(Query(params): Query>) {} + +// Buffer the request body and deserialize it as JSON into a +// `serde_json::Value`. `Json` supports any type that implements +// `serde::Deserialize`. +async fn json(Json(payload): Json) {} +``` + +See [`extract`](crate::extract) for more details on extractors. + +# Responses + +Anything that implements [`IntoResponse`] can be returned from handlers. + +```rust,no_run +use axum::{ + body::Body, + routing::get, + response::Json, + Router, +}; +use serde_json::{Value, json}; + +// `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8` +async fn plain_text() -> &'static str { + "foo" +} + +// `Json` gives a content-type of `application/json` and works with any type +// that implements `serde::Serialize` +async fn json() -> Json { + Json(json!({ "data": 42 })) +} + +let app = Router::new() + .route("/plain_text", get(plain_text)) + .route("/json", get(json)); +# let _: Router = app; +``` + +See [`response`](crate::response) for more details on building responses. + +# Error handling + +axum aims to have a simple and predictable error handling model. That means +it is simple to convert errors into responses and you are guaranteed that +all errors are handled. + +See [`error_handling`] for more details on axum's +error handling model and how to handle errors gracefully. + +# Middleware + +There are several different ways to write middleware for axum. See +[`middleware`] for more details. + +# Sharing state with handlers + +It is common to share some state between handlers. For example, a +pool of database connections or clients to other services may need to +be shared. + +The four most common ways of doing that are: + +- Using the [`State`] extractor +- Using request extensions +- Using closure captures +- Using task-local variables + +## Using the [`State`] extractor + +```rust,no_run +use axum::{ + extract::State, + routing::get, + Router, +}; +use std::sync::Arc; + +struct AppState { + // ... +} + +let shared_state = Arc::new(AppState { /* ... */ }); + +let app = Router::new() + .route("/", get(handler)) + .with_state(shared_state); + +async fn handler( + State(state): State>, +) { + // ... +} +# let _: Router = app; +``` + +You should prefer using [`State`] if possible since it's more type safe. The downside is that +it's less dynamic than task-local variables and request extensions. + +See [`State`] for more details about accessing state. + +## Using request extensions + +Another way to share state with handlers is using [`Extension`] as +layer and extractor: + +```rust,no_run +use axum::{ + extract::Extension, + routing::get, + Router, +}; +use std::sync::Arc; + +struct AppState { + // ... +} + +let shared_state = Arc::new(AppState { /* ... */ }); + +let app = Router::new() + .route("/", get(handler)) + .layer(Extension(shared_state)); + +async fn handler( + Extension(state): Extension>, +) { + // ... +} +# let _: Router = app; +``` + +The downside to this approach is that you'll get runtime errors +(specifically a `500 Internal Server Error` response) if you try and extract +an extension that doesn't exist, perhaps because you forgot to add the +middleware or because you're extracting the wrong type. + +## Using closure captures + +State can also be passed directly to handlers using closure captures: + +```rust,no_run +use axum::{ + Json, + extract::{Extension, Path}, + routing::{get, post}, + Router, +}; +use std::sync::Arc; +use serde::Deserialize; + +struct AppState { + // ... +} + +let shared_state = Arc::new(AppState { /* ... */ }); + +let app = Router::new() + .route( + "/users", + post({ + let shared_state = Arc::clone(&shared_state); + move |body| create_user(body, shared_state) + }), + ) + .route( + "/users/{id}", + get({ + let shared_state = Arc::clone(&shared_state); + move |path| get_user(path, shared_state) + }), + ); + +async fn get_user(Path(user_id): Path, state: Arc) { + // ... +} + +async fn create_user(Json(payload): Json, state: Arc) { + // ... +} + +#[derive(Deserialize)] +struct CreateUserPayload { + // ... +} +# let _: Router = app; +``` + +The downside to this approach is that it's the most verbose approach. + +## Using task-local variables + +This also allows to share state with `IntoResponse` implementations: + +```rust,no_run +use axum::{ + extract::Request, + http::{header, StatusCode}, + middleware::{self, Next}, + response::{IntoResponse, Response}, + routing::get, + Router, +}; +use tokio::task_local; + +#[derive(Clone)] +struct CurrentUser { + name: String, +} +task_local! { + pub static USER: CurrentUser; +} + +async fn auth(req: Request, next: Next) -> Result { + let auth_header = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|header| header.to_str().ok()) + .ok_or(StatusCode::UNAUTHORIZED)?; + if let Some(current_user) = authorize_current_user(auth_header).await { + // State is setup here in the middleware + Ok(USER.scope(current_user, next.run(req)).await) + } else { + Err(StatusCode::UNAUTHORIZED) + } +} +async fn authorize_current_user(auth_token: &str) -> Option { + Some(CurrentUser { + name: auth_token.to_string(), + }) +} + +struct UserResponse; + +impl IntoResponse for UserResponse { + fn into_response(self) -> Response { + // State is accessed here in the IntoResponse implementation + let current_user = USER.with(|u| u.clone()); + (StatusCode::OK, current_user.name).into_response() + } +} + +async fn handler() -> UserResponse { + UserResponse +} + +let app: Router = Router::new() + .route("/", get(handler)) + .route_layer(middleware::from_fn(auth)); +``` + +The main downside to this approach is that it only works when the async executor being used +has the concept of task-local variables. The example above uses +[tokio's `task_local` macro](https://docs.rs/tokio/1/tokio/macro.task_local.html). +smol does not yet offer equivalent functionality at the time of writing (see +[this GitHub issue](https://github.com/smol-rs/async-executor/issues/139)). + +# Building integrations for axum + +Libraries authors that want to provide [`FromRequest`], [`FromRequestParts`], or +[`IntoResponse`] implementations should depend on the [`axum-core`] crate, instead of `axum` if +possible. [`axum-core`] contains core types and traits and is less likely to receive breaking +changes. + +# Required dependencies + +To use axum there are a few dependencies you have to pull in as well: + +```toml +[dependencies] +axum = "" +tokio = { version = "", features = ["full"] } +tower = "" +``` + +The `"full"` feature for tokio isn't necessary but it's the easiest way to get started. + +Tower isn't strictly necessary either but helpful for testing. See the +testing example in the repo to learn more about testing axum apps. + +# Examples + +The axum repo contains [a number of examples][examples] that show how to put all the +pieces together. + +# Feature flags + +axum uses a set of [feature flags] to reduce the amount of compiled and +optional dependencies. + +The following optional features are available: + +Name | Description | Default? +---|---|--- +`http1` | Enables hyper's `http1` feature | +`http2` | Enables hyper's `http2` feature | +`json` | Enables the [`Json`] type and some similar convenience functionality | +`macros` | Enables optional utility macros | +`matched-path` | Enables capturing of every request's router path and the [`MatchedPath`] extractor | +`multipart` | Enables parsing `multipart/form-data` requests with [`Multipart`] | +`original-uri` | Enables capturing of every request's original URI and the [`OriginalUri`] extractor | +`tokio` | Enables `tokio` as a dependency and `axum::serve`, `SSE` and `extract::connect_info` types. | +`tower-log` | Enables `tower`'s `log` feature | +`tracing` | Log rejections from built-in extractors | +`ws` | Enables WebSockets support via [`extract::ws`] | +`form` | Enables the `Form` extractor | +`query` | Enables the `Query` extractor | + +[`MatchedPath`]: crate::extract::MatchedPath +[`Multipart`]: crate::extract::Multipart +[`OriginalUri`]: crate::extract::OriginalUri +[`tower`]: https://crates.io/crates/tower +[`tower-http`]: https://crates.io/crates/tower-http +[`tokio`]: http://crates.io/crates/tokio +[`hyper`]: http://crates.io/crates/hyper +[`tonic`]: http://crates.io/crates/tonic +[feature flags]: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section +[`IntoResponse`]: crate::response::IntoResponse +[`Timeout`]: tower::timeout::Timeout +[examples]: https://github.com/tokio-rs/axum/tree/main/examples +[`Router::merge`]: crate::routing::Router::merge +[`Service`]: tower::Service +[`Service::poll_ready`]: tower::Service::poll_ready +[`Service`'s]: tower::Service +[`tower::Service`]: tower::Service +[tower-guides]: https://github.com/tower-rs/tower/tree/master/guides +[`Uuid`]: https://docs.rs/uuid/latest/uuid/ +[`FromRequest`]: crate::extract::FromRequest +[`FromRequestParts`]: crate::extract::FromRequestParts +[`HeaderMap`]: http::header::HeaderMap +[`Request`]: http::Request +[customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs +[axum-macros]: https://docs.rs/axum-macros +[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html +[`Handler`]: crate::handler::Handler +[`Infallible`]: std::convert::Infallible +[load shed]: tower::load_shed +[`axum-core`]: http://crates.io/crates/axum-core +[`State`]: crate::extract::State + +## Modules + +## Module `body` + +HTTP body utilities. + +```rust +pub mod body { /* ... */ } +``` + +### Functions + +#### Function `to_bytes` + +Converts [`Body`] into [`Bytes`] and limits the maximum size of the body. + +# Example + +```rust +use axum::body::{to_bytes, Body}; + +# async fn foo() -> Result<(), axum_core::Error> { +let body = Body::from(vec![1, 2, 3]); +// Use `usize::MAX` if you don't care about the maximum size. +let bytes = to_bytes(body, usize::MAX).await?; +assert_eq!(&bytes[..], &[1, 2, 3]); +# Ok(()) +# } +``` + +You can detect if the limit was hit by checking the source of the error: + +```rust +use axum::body::{to_bytes, Body}; +use http_body_util::LengthLimitError; + +# #[tokio::main] +# async fn main() { +let body = Body::from(vec![1, 2, 3]); +match to_bytes(body, 1).await { + Ok(_bytes) => panic!("should have hit the limit"), + Err(err) => { + let source = std::error::Error::source(&err).unwrap(); + assert!(source.is::()); + } +} +# } +``` + +```rust +pub async fn to_bytes(body: Body, limit: usize) -> Result { /* ... */ } +``` + +### Re-exports + +#### Re-export `Body` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use http_body::Body as HttpBody; +``` + +#### Re-export `Bytes` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use bytes::Bytes; +``` + +#### Re-export `Body` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::body::Body; +``` + +#### Re-export `BodyDataStream` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::body::BodyDataStream; +``` + +## Module `error_handling` + +Error handling model and utilities + +# axum's error handling model + +axum is based on [`tower::Service`] which bundles errors through its associated +`Error` type. If you have a [`Service`] that produces an error and that error +makes it all the way up to hyper, the connection will be terminated _without_ +sending a response. This is generally not desirable so axum makes sure you +always produce a response by relying on the type system. + +axum does this by requiring all services have [`Infallible`] as their error +type. `Infallible` is the error type for errors that can never happen. + +This means if you define a handler like: + +```rust +use axum::http::StatusCode; + +async fn handler() -> Result { + # todo!() + // ... +} +``` + +While it looks like it might fail with a `StatusCode` this actually isn't an +"error". If this handler returns `Err(some_status_code)` that will still be +converted into a [`Response`] and sent back to the client. This is done +through `StatusCode`'s [`IntoResponse`] implementation. + +It doesn't matter whether you return `Err(StatusCode::NOT_FOUND)` or +`Err(StatusCode::INTERNAL_SERVER_ERROR)`. These are not considered errors in +axum. + +Instead of a direct `StatusCode`, it makes sense to use intermediate error type +that can ultimately be converted to `Response`. This allows using `?` operator +in handlers. See those examples: + +* [`anyhow-error-response`][anyhow] for generic boxed errors +* [`error-handling`][error-handling] for application-specific detailed errors + +[anyhow]: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs +[error-handling]: https://github.com/tokio-rs/axum/blob/main/examples/error-handling/src/main.rs + +This also applies to extractors. If an extractor doesn't match the request the +request will be rejected and a response will be returned without calling your +handler. See [`extract`](crate::extract) to learn more about handling extractor +failures. + +# Routing to fallible services + +You generally don't have to think about errors if you're only using async +functions as handlers. However if you're embedding general `Service`s or +applying middleware, which might produce errors you have to tell axum how to +convert those errors into responses. + +```rust +use axum::{ + Router, + body::Body, + http::{Request, Response, StatusCode}, + error_handling::HandleError, +}; + +async fn thing_that_might_fail() -> Result<(), anyhow::Error> { + # Ok(()) + // ... +} + +// this service might fail with `anyhow::Error` +let some_fallible_service = tower::service_fn(|_req| async { + thing_that_might_fail().await?; + Ok::<_, anyhow::Error>(Response::new(Body::empty())) +}); + +let app = Router::new().route_service( + "/", + // we cannot route to `some_fallible_service` directly since it might fail. + // we have to use `handle_error` which converts its errors into responses + // and changes its error type from `anyhow::Error` to `Infallible`. + HandleError::new(some_fallible_service, handle_anyhow_error), +); + +// handle errors by converting them into something that implements +// `IntoResponse` +async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Something went wrong: {err}"), + ) +} +# let _: Router = app; +``` + +# Applying fallible middleware + +Similarly axum requires you to handle errors from middleware. That is done with +[`HandleErrorLayer`]: + +```rust +use axum::{ + Router, + BoxError, + routing::get, + http::StatusCode, + error_handling::HandleErrorLayer, +}; +use std::time::Duration; +use tower::ServiceBuilder; + +let app = Router::new() + .route("/", get(|| async {})) + .layer( + ServiceBuilder::new() + // `timeout` will produce an error if the handler takes + // too long so we must handle those + .layer(HandleErrorLayer::new(handle_timeout_error)) + .timeout(Duration::from_secs(30)) + ); + +async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) { + if err.is::() { + ( + StatusCode::REQUEST_TIMEOUT, + "Request took too long".to_string(), + ) + } else { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Unhandled internal error: {err}"), + ) + } +} +# let _: Router = app; +``` + +# Running extractors for error handling + +`HandleErrorLayer` also supports running extractors: + +```rust +use axum::{ + Router, + BoxError, + routing::get, + http::{StatusCode, Method, Uri}, + error_handling::HandleErrorLayer, +}; +use std::time::Duration; +use tower::ServiceBuilder; + +let app = Router::new() + .route("/", get(|| async {})) + .layer( + ServiceBuilder::new() + // `timeout` will produce an error if the handler takes + // too long so we must handle those + .layer(HandleErrorLayer::new(handle_timeout_error)) + .timeout(Duration::from_secs(30)) + ); + +async fn handle_timeout_error( + // `Method` and `Uri` are extractors so they can be used here + method: Method, + uri: Uri, + // the last argument must be the error itself + err: BoxError, +) -> (StatusCode, String) { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("`{method} {uri}` failed with {err}"), + ) +} +# let _: Router = app; +``` + +[`tower::Service`]: `tower::Service` +[`Infallible`]: std::convert::Infallible +[`Response`]: crate::response::Response +[`IntoResponse`]: crate::response::IntoResponse + +```rust +pub mod error_handling { /* ... */ } +``` + +### Modules + +## Module `future` + +Future types. + +```rust +pub mod future { /* ... */ } +``` + +### Types + +#### Struct `HandleErrorFuture` + +Response future for [`HandleError`]. + +```rust +pub struct HandleErrorFuture { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **FutureExt** +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryFuture** + - ```rust + fn try_poll(self: Pin<&mut F>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **TryFutureExt** +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Types + +#### Struct `HandleErrorLayer` + +[`Layer`] that applies [`HandleError`] which is a [`Service`] adapter +that handles errors by converting them into responses. + +See [module docs](self) for more details on axum's error handling model. + +```rust +pub struct HandleErrorLayer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(f: F) -> Self { /* ... */ } + ``` + Create a new `HandleErrorLayer`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Layer** + - ```rust + fn layer(self: &Self, inner: S) -> ::Service { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `HandleError` + +A [`Service`] adapter that handles errors by converting them into responses. + +See [module docs](self) for more details on axum's error handling model. + +```rust +pub struct HandleError { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(inner: S, f: F) -> Self { /* ... */ } + ``` + Create a new `HandleError`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **MakeService** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll>::MakeError>> { /* ... */ } + ``` + + - ```rust + fn make_service(self: &mut Self, target: Target) -> >::Future { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +## Module `extract` + +Types and traits for extracting data from requests. + +# Intro + +A handler function is an async function that takes any number of +"extractors" as arguments. An extractor is a type that implements +[`FromRequest`] or [`FromRequestParts`]. + +For example, [`Json`] is an extractor that consumes the request body and +deserializes it as JSON into some target type: + +```rust,no_run +use axum::{ + extract::Json, + routing::post, + handler::Handler, + Router, +}; +use serde::Deserialize; + +#[derive(Deserialize)] +struct CreateUser { + email: String, + password: String, +} + +async fn create_user(Json(payload): Json) { + // ... +} + +let app = Router::new().route("/users", post(create_user)); +# let _: Router = app; +``` + +# Common extractors + +Some commonly used extractors are: + +```rust,no_run +use axum::{ + extract::{Request, Json, Path, Extension, Query}, + routing::post, + http::header::HeaderMap, + body::{Bytes, Body}, + Router, +}; +use serde_json::Value; +use std::collections::HashMap; + +// `Path` gives you the path parameters and deserializes them. See its docs for +// more details +async fn path(Path(user_id): Path) {} + +// `Query` gives you the query parameters and deserializes them. +async fn query(Query(params): Query>) {} + +// `HeaderMap` gives you all the headers +async fn headers(headers: HeaderMap) {} + +// `String` consumes the request body and ensures it is valid utf-8 +async fn string(body: String) {} + +// `Bytes` gives you the raw request body +async fn bytes(body: Bytes) {} + +// We've already seen `Json` for parsing the request body as json +async fn json(Json(payload): Json) {} + +// `Request` gives you the whole request for maximum control +async fn request(request: Request) {} + +// `Extension` extracts data from "request extensions" +// This is commonly used to share state with handlers +async fn extension(Extension(state): Extension) {} + +#[derive(Clone)] +struct State { /* ... */ } + +let app = Router::new() + .route("/path/{user_id}", post(path)) + .route("/query", post(query)) + .route("/string", post(string)) + .route("/bytes", post(bytes)) + .route("/json", post(json)) + .route("/request", post(request)) + .route("/extension", post(extension)); +# let _: Router = app; +``` + +# Applying multiple extractors + +You can also apply multiple extractors: + +```rust,no_run +use axum::{ + extract::{Path, Query}, + routing::get, + Router, +}; +use uuid::Uuid; +use serde::Deserialize; + +let app = Router::new().route("/users/{id}/things", get(get_user_things)); + +#[derive(Deserialize)] +struct Pagination { + page: usize, + per_page: usize, +} + +async fn get_user_things( + Path(user_id): Path, + Query(pagination): Query, +) { + // ... +} +# let _: Router = app; +``` + +# The order of extractors + +Extractors always run in the order of the function parameters that is from +left to right. + +The request body is an asynchronous stream that can only be consumed once. +Therefore you can only have one extractor that consumes the request body. axum +enforces this by requiring such extractors to be the _last_ argument your +handler takes. + +For example + +```rust +use axum::{extract::State, http::{Method, HeaderMap}}; +# +# #[derive(Clone)] +# struct AppState { +# } + +async fn handler( + // `Method` and `HeaderMap` don't consume the request body so they can + // put anywhere in the argument list (but before `body`) + method: Method, + headers: HeaderMap, + // `State` is also an extractor so it needs to be before `body` + State(state): State, + // `String` consumes the request body and thus must be the last extractor + body: String, +) { + // ... +} +# +# let _: axum::routing::MethodRouter = axum::routing::get(handler); +``` + +We get a compile error if `String` isn't the last extractor: + +```rust,compile_fail +use axum::http::Method; + +async fn handler( + // this doesn't work since `String` must be the last argument + body: String, + method: Method, +) { + // ... +} +# +# let _: axum::routing::MethodRouter = axum::routing::get(handler); +``` + +This also means you cannot consume the request body twice: + +```rust,compile_fail +use axum::Json; +use serde::Deserialize; + +#[derive(Deserialize)] +struct Payload {} + +async fn handler( + // `String` and `Json` both consume the request body + // so they cannot both be used + string_body: String, + json_body: Json, +) { + // ... +} +# +# let _: axum::routing::MethodRouter = axum::routing::get(handler); +``` + +axum enforces this by requiring the last extractor implements [`FromRequest`] +and all others implement [`FromRequestParts`]. + +# Handling extractor rejections + +If you want to handle the case of an extractor failing within a specific +handler, you can wrap it in `Result`, with the error being the rejection type +of the extractor: + +```rust,no_run +use axum::{ + extract::{Json, rejection::JsonRejection}, + routing::post, + Router, +}; +use serde_json::Value; + +async fn create_user(payload: Result, JsonRejection>) { + match payload { + Ok(payload) => { + // We got a valid JSON payload + } + Err(JsonRejection::MissingJsonContentType(_)) => { + // Request didn't have `Content-Type: application/json` + // header + } + Err(JsonRejection::JsonDataError(_)) => { + // Couldn't deserialize the body into the target type + } + Err(JsonRejection::JsonSyntaxError(_)) => { + // Syntax error in the body + } + Err(JsonRejection::BytesRejection(_)) => { + // Failed to extract the request body + } + Err(_) => { + // `JsonRejection` is marked `#[non_exhaustive]` so match must + // include a catch-all case. + } + } +} + +let app = Router::new().route("/users", post(create_user)); +# let _: Router = app; +``` + +# Optional extractors + +Some extractors implement [`OptionalFromRequestParts`] in addition to +[`FromRequestParts`], or [`OptionalFromRequest`] in addition to [`FromRequest`]. + +These extractors can be used inside of `Option`. It depends on the particular +`OptionalFromRequestParts` or `OptionalFromRequest` implementation what this +does: For example for `TypedHeader` from axum-extra, you get `None` if the +header you're trying to extract is not part of the request, but if the header +is present and fails to parse, the request is rejected. + +```rust,no_run +use axum::{routing::post, Router}; +use axum_extra::{headers::UserAgent, TypedHeader}; +use serde_json::Value; + +async fn foo(user_agent: Option>) { + if let Some(TypedHeader(user_agent)) = user_agent { + // The client sent a user agent + } else { + // No user agent header + } +} + +let app = Router::new().route("/foo", post(foo)); +# let _: Router = app; +``` + +# Customizing extractor responses + +If an extractor fails it will return a response with the error and your +handler will not be called. To customize the error response you have two +options: + +1. Use `Result` as your extractor like shown in + ["Handling extractor rejections"](#handling-extractor-rejections). + This works well if you're only using the extractor in a single handler. +2. Create your own extractor that in its [`FromRequest`] implementation calls + one of axum's built in extractors but returns a different response for + rejections. See the [customize-extractor-error] example for more details. + +# Accessing inner errors + +axum's built-in extractors don't directly expose the inner error. This gives us +more flexibility and allows us to change internal implementations without +breaking the public API. + +For example that means while [`Json`] is implemented using [`serde_json`] it +doesn't directly expose the [`serde_json::Error`] that's contained in +[`JsonRejection::JsonDataError`]. However it is still possible to access via +methods from [`std::error::Error`]: + +```rust +use std::error::Error; +use axum::{ + extract::{Json, rejection::JsonRejection}, + response::IntoResponse, + http::StatusCode, +}; +use serde_json::{json, Value}; + +async fn handler( + result: Result, JsonRejection>, +) -> Result, (StatusCode, String)> { + match result { + // if the client sent valid JSON then we're good + Ok(Json(payload)) => Ok(Json(json!({ "payload": payload }))), + + Err(err) => match err { + JsonRejection::JsonDataError(err) => { + Err(serde_json_error_response(err)) + } + JsonRejection::JsonSyntaxError(err) => { + Err(serde_json_error_response(err)) + } + // handle other rejections from the `Json` extractor + JsonRejection::MissingJsonContentType(_) => Err(( + StatusCode::BAD_REQUEST, + "Missing `Content-Type: application/json` header".to_string(), + )), + JsonRejection::BytesRejection(_) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + "Failed to buffer request body".to_string(), + )), + // we must provide a catch-all case since `JsonRejection` is marked + // `#[non_exhaustive]` + _ => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + "Unknown error".to_string(), + )), + }, + } +} + +// attempt to extract the inner `serde_path_to_error::Error`, +// if that succeeds we can provide a more specific error. +// +// `Json` uses `serde_path_to_error` so the error will be wrapped in `serde_path_to_error::Error`. +fn serde_json_error_response(err: E) -> (StatusCode, String) +where + E: Error + 'static, +{ + if let Some(err) = find_error_source::>(&err) { + let serde_json_err = err.inner(); + ( + StatusCode::BAD_REQUEST, + format!( + "Invalid JSON at line {} column {}", + serde_json_err.line(), + serde_json_err.column() + ), + ) + } else { + (StatusCode::BAD_REQUEST, "Unknown error".to_string()) + } +} + +// attempt to downcast `err` into a `T` and if that fails recursively try and +// downcast `err`'s source +fn find_error_source<'a, T>(err: &'a (dyn Error + 'static)) -> Option<&'a T> +where + T: Error + 'static, +{ + if let Some(err) = err.downcast_ref::() { + Some(err) + } else if let Some(source) = err.source() { + find_error_source(source) + } else { + None + } +} +# +# #[tokio::main] +# async fn main() { +# use axum::extract::FromRequest; +# +# let req = axum::http::Request::builder() +# .header("content-type", "application/json") +# .body(axum::body::Body::from("{")) +# .unwrap(); +# +# let err = match Json::::from_request(req, &()).await.unwrap_err() { +# JsonRejection::JsonSyntaxError(err) => err, +# _ => panic!(), +# }; +# +# let (_, body) = serde_json_error_response(err); +# assert_eq!(body, "Invalid JSON at line 1 column 1"); +# } +``` + +Note that while this approach works it might break in the future if axum changes +its implementation to use a different error type internally. Such changes might +happen without major breaking versions. + +# Defining custom extractors + +You can also define your own extractors by implementing either +[`FromRequestParts`] or [`FromRequest`]. + +## Implementing `FromRequestParts` + +Implement `FromRequestParts` if your extractor doesn't need access to the +request body: + +```rust,no_run +use axum::{ + extract::FromRequestParts, + routing::get, + Router, + http::{ + StatusCode, + header::{HeaderValue, USER_AGENT}, + request::Parts, + }, +}; + +struct ExtractUserAgent(HeaderValue); + +impl FromRequestParts for ExtractUserAgent +where + S: Send + Sync, +{ + type Rejection = (StatusCode, &'static str); + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + if let Some(user_agent) = parts.headers.get(USER_AGENT) { + Ok(ExtractUserAgent(user_agent.clone())) + } else { + Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing")) + } + } +} + +async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) { + // ... +} + +let app = Router::new().route("/foo", get(handler)); +# let _: Router = app; +``` + +## Implementing `FromRequest` + +If your extractor needs to consume the request body you must implement [`FromRequest`] + +```rust,no_run +use axum::{ + extract::{Request, FromRequest}, + response::{Response, IntoResponse}, + body::{Bytes, Body}, + routing::get, + Router, + http::{ + StatusCode, + header::{HeaderValue, USER_AGENT}, + }, +}; + +struct ValidatedBody(Bytes); + +impl FromRequest for ValidatedBody +where + Bytes: FromRequest, + S: Send + Sync, +{ + type Rejection = Response; + + async fn from_request(req: Request, state: &S) -> Result { + let body = Bytes::from_request(req, state) + .await + .map_err(IntoResponse::into_response)?; + + // do validation... + + Ok(Self(body)) + } +} + +async fn handler(ValidatedBody(body): ValidatedBody) { + // ... +} + +let app = Router::new().route("/foo", get(handler)); +# let _: Router = app; +``` + +## Cannot implement both `FromRequest` and `FromRequestParts` + +Note that you will make your extractor unusable by implementing both +`FromRequest` and `FromRequestParts` directly for the same type, unless it is +wrapping another extractor: + +```rust,compile_fail +use axum::{ + Router, + routing::get, + extract::{FromRequest, Request, FromRequestParts}, + http::request::Parts, + body::Body, +}; +use std::convert::Infallible; + +// Some extractor that doesn't wrap another extractor +struct MyExtractor; + +// `MyExtractor` implements both `FromRequest` +impl FromRequest for MyExtractor +where + S: Send + Sync, +{ + type Rejection = Infallible; + + async fn from_request(req: Request, state: &S) -> Result { + // ... + # todo!() + } +} + +// and `FromRequestParts` +impl FromRequestParts for MyExtractor +where + S: Send + Sync, +{ + type Rejection = Infallible; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + // ... + # todo!() + } +} + +let app = Router::new().route( + "/", + // This fails when we go to actually use `MyExtractor` in a handler function. + // This is due to a limit in Rust's type system. + // + // The workaround is to implement either `FromRequest` or `FromRequestParts` + // but not both, if your extractor doesn't wrap another extractor. + // + // See "Wrapping extractors" for how to wrap other extractors. + get(|_: MyExtractor| async {}), +); +# let _: Router = app; +``` + +# Accessing other extractors in `FromRequest` or `FromRequestParts` implementations + +When defining custom extractors you often need to access another extractor +in your implementation. + +```rust +use axum::{ + extract::{Extension, FromRequestParts}, + http::{StatusCode, HeaderMap, request::Parts}, + response::{IntoResponse, Response}, + routing::get, + Router, +}; + +#[derive(Clone)] +struct State { + // ... +} + +struct AuthenticatedUser { + // ... +} + +impl FromRequestParts for AuthenticatedUser +where + S: Send + Sync, +{ + type Rejection = Response; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + // You can either call them directly... + let headers = HeaderMap::from_request_parts(parts, state) + .await + .map_err(|err| match err {})?; + + // ... or use `extract` / `extract_with_state` from `RequestExt` / `RequestPartsExt` + use axum::RequestPartsExt; + let Extension(state) = parts.extract::>() + .await + .map_err(|err| err.into_response())?; + + unimplemented!("actually perform the authorization") + } +} + +async fn handler(user: AuthenticatedUser) { + // ... +} + +let state = State { /* ... */ }; + +let app = Router::new().route("/", get(handler)).layer(Extension(state)); +# let _: Router = app; +``` + +# Request body limits + +For security reasons, [`Bytes`] will, by default, not accept bodies larger than +2MB. This also applies to extractors that uses [`Bytes`] internally such as +`String`, [`Json`], and [`Form`]. + +For more details, including how to disable this limit, see [`DefaultBodyLimit`]. + +# Wrapping extractors + +If you want to write an extractor that generically wraps another extractor +(that may or may not consume the request body) you should implement both +[`FromRequest`] and [`FromRequestParts`]: + +```rust +use axum::{ + Router, + body::Body, + routing::get, + extract::{Request, FromRequest, FromRequestParts}, + http::{HeaderMap, request::Parts}, +}; +use std::time::{Instant, Duration}; + +// an extractor that wraps another and measures how long time it takes to run +struct Timing { + extractor: E, + duration: Duration, +} + +// we must implement both `FromRequestParts` +impl FromRequestParts for Timing +where + S: Send + Sync, + T: FromRequestParts, +{ + type Rejection = T::Rejection; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let start = Instant::now(); + let extractor = T::from_request_parts(parts, state).await?; + let duration = start.elapsed(); + Ok(Timing { + extractor, + duration, + }) + } +} + +// and `FromRequest` +impl FromRequest for Timing +where + S: Send + Sync, + T: FromRequest, +{ + type Rejection = T::Rejection; + + async fn from_request(req: Request, state: &S) -> Result { + let start = Instant::now(); + let extractor = T::from_request(req, state).await?; + let duration = start.elapsed(); + Ok(Timing { + extractor, + duration, + }) + } +} + +async fn handler( + // this uses the `FromRequestParts` impl + _: Timing, + // this uses the `FromRequest` impl + _: Timing, +) {} +# let _: axum::routing::MethodRouter = axum::routing::get(handler); +``` + +# Logging rejections + +All built-in extractors will log rejections for easier debugging. To see the +logs, enable the `tracing` feature for axum (enabled by default) and the +`axum::rejection=trace` tracing target, for example with +`RUST_LOG=info,axum::rejection=trace cargo run`. + +[axum-extra]: https://docs.rs/axum-extra/latest/axum_extra/extract/index.html +[`body::Body`]: crate::body::Body +[`Bytes`]: crate::body::Bytes +[customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs +[`HeaderMap`]: https://docs.rs/http/latest/http/header/struct.HeaderMap.html +[`Request`]: https://docs.rs/http/latest/http/struct.Request.html +[`JsonRejection::JsonDataError`]: rejection::JsonRejection::JsonDataError + +```rust +pub mod extract { /* ... */ } +``` + +### Modules + +## Module `connect_info` + +**Attributes:** + +- `Other("#[(feature = \"tokio\")]")` + +Extractor for getting connection information from a client. + +See [`Router::into_make_service_with_connect_info`] for more details. + +[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info + +```rust +pub mod connect_info { /* ... */ } +``` + +### Types + +#### Struct `IntoMakeServiceWithConnectInfo` + +A [`MakeService`] created from a router. + +See [`Router::into_make_service_with_connect_info`] for more details. + +[`MakeService`]: tower::make::MakeService +[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info + +```rust +pub struct IntoMakeServiceWithConnectInfo { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **MakeService** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll>::MakeError>> { /* ... */ } + ``` + + - ```rust + fn make_service(self: &mut Self, target: Target) -> >::Future { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, target: T) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `ResponseFuture` + +Response future for [`IntoMakeServiceWithConnectInfo`]. + +```rust +pub struct ResponseFuture { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<''_>) -> std::task::Poll<::Output> { /* ... */ } + ``` + +- **FutureExt** +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryFuture** + - ```rust + fn try_poll(self: Pin<&mut F>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **TryFutureExt** +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `ConnectInfo` + +Extractor for getting connection information produced by a [`Connected`]. + +Note this extractor requires you to use +[`Router::into_make_service_with_connect_info`] to run your app +otherwise it will fail at runtime. + +See [`Router::into_make_service_with_connect_info`] for more details. + +[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info + +```rust +pub struct ConnectInfo(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> ConnectInfo { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **CryptoRng** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + +- **DerefMut** + - ```rust + fn deref_mut(self: &mut Self) -> &mut ::Target { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **FromRequest** + - ```rust + fn from_request(req: Request, state: &S) -> impl Future>::Rejection>> { /* ... */ } + ``` + +- **FromRequestParts** + - ```rust + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result::Rejection> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **Receiver** +- **RefUnwindSafe** +- **Rng** +- **RngCore** + - ```rust + fn next_u32(self: &mut Self) -> u32 { /* ... */ } + ``` + + - ```rust + fn next_u64(self: &mut Self) -> u64 { /* ... */ } + ``` + + - ```rust + fn fill_bytes(self: &mut Self, dst: &mut [u8]) { /* ... */ } + ``` + +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryCryptoRng** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **TryRngCore** + - ```rust + fn try_next_u32(self: &mut Self) -> Result::Error> { /* ... */ } + ``` + + - ```rust + fn try_next_u64(self: &mut Self) -> Result::Error> { /* ... */ } + ``` + + - ```rust + fn try_fill_bytes(self: &mut Self, dst: &mut [u8]) -> Result<(), ::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MockConnectInfo` + +Middleware used to mock [`ConnectInfo`] during tests. + +If you're accidentally using [`MockConnectInfo`] and +[`Router::into_make_service_with_connect_info`] at the same time then +[`Router::into_make_service_with_connect_info`] takes precedence. + +# Example + +``` +use axum::{ + Router, + extract::connect_info::{MockConnectInfo, ConnectInfo}, + body::Body, + routing::get, + http::{Request, StatusCode}, +}; +use std::net::SocketAddr; +use tower::ServiceExt; + +async fn handler(ConnectInfo(addr): ConnectInfo) {} + +// this router you can run with `app.into_make_service_with_connect_info::()` +fn app() -> Router { + Router::new().route("/", get(handler)) +} + +// use this router for tests +fn test_app() -> Router { + app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))) +} + +// #[tokio::test] +async fn some_test() { + let app = test_app(); + + let request = Request::new(Body::empty()); + let response = app.oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); +} +# +# #[tokio::main] +# async fn main() { +# some_test().await; +# } +``` + +[`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info + +```rust +pub struct MockConnectInfo(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> MockConnectInfo { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Layer** + - ```rust + fn layer(self: &Self, inner: S) -> ::Service { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Traits + +#### Trait `Connected` + +Trait that connected IO resources implement and use to produce information +about the connection. + +The goal for this trait is to allow users to implement custom IO types that +can still provide the same connection metadata. + +See [`Router::into_make_service_with_connect_info`] for more details. + +[`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info + +```rust +pub trait Connected: Clone + Send + Sync + ''static { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `connect_info`: Create type holding information about the connection. + +##### Implementations + +This trait is implemented for the following types: + +- `SocketAddr` +- `::Addr` with <''a, L, F> +- `std::net::SocketAddr` + +## Module `path` + +Extractor that will get captures from the URL and parse them using +[`serde`]. + +```rust +pub mod path { /* ... */ } +``` + +### Types + +#### Struct `Path` + +Extractor that will get captures from the URL and parse them using +[`serde`]. + +Any percent encoded parameters will be automatically decoded. The decoded +parameters must be valid UTF-8, otherwise `Path` will fail and return a `400 +Bad Request` response. + +# `Option>` behavior + +You can use `Option>` as an extractor to allow the same handler to +be used in a route with parameters that deserialize to `T`, and another +route with no parameters at all. + +# Example + +These examples assume the `serde` feature of the [`uuid`] crate is enabled. + +One `Path` can extract multiple captures. It is not necessary (and does +not work) to give a handler more than one `Path` argument. + +[`uuid`]: https://crates.io/crates/uuid + +```rust,no_run +use axum::{ + extract::Path, + routing::get, + Router, +}; +use uuid::Uuid; + +async fn users_teams_show( + Path((user_id, team_id)): Path<(Uuid, Uuid)>, +) { + // ... +} + +let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show)); +# let _: Router = app; +``` + +If the path contains only one parameter, then you can omit the tuple. + +```rust,no_run +use axum::{ + extract::Path, + routing::get, + Router, +}; +use uuid::Uuid; + +async fn user_info(Path(user_id): Path) { + // ... +} + +let app = Router::new().route("/users/{user_id}", get(user_info)); +# let _: Router = app; +``` + +Path segments also can be deserialized into any type that implements +[`serde::Deserialize`]. This includes tuples and structs: + +```rust,no_run +use axum::{ + extract::Path, + routing::get, + Router, +}; +use serde::Deserialize; +use uuid::Uuid; + +// Path segment labels will be matched with struct field names +#[derive(Deserialize)] +struct Params { + user_id: Uuid, + team_id: Uuid, +} + +async fn users_teams_show( + Path(Params { user_id, team_id }): Path, +) { + // ... +} + +// When using tuples the path segments will be matched by their position in the route +async fn users_teams_create( + Path((user_id, team_id)): Path<(String, String)>, +) { + // ... +} + +let app = Router::new().route( + "/users/{user_id}/team/{team_id}", + get(users_teams_show).post(users_teams_create), +); +# let _: Router = app; +``` + +If you wish to capture all path parameters you can use `HashMap` or `Vec`: + +```rust,no_run +use axum::{ + extract::Path, + routing::get, + Router, +}; +use std::collections::HashMap; + +async fn params_map( + Path(params): Path>, +) { + // ... +} + +async fn params_vec( + Path(params): Path>, +) { + // ... +} + +let app = Router::new() + .route("/users/{user_id}/team/{team_id}", get(params_map).post(params_vec)); +# let _: Router = app; +``` + +# Providing detailed rejection output + +If the URI cannot be deserialized into the target type the request will be rejected and an +error response will be returned. See [`customize-path-rejection`] for an example of how to customize that error. + +[`serde`]: https://crates.io/crates/serde +[`serde::Deserialize`]: https://docs.rs/serde/1.0.127/serde/trait.Deserialize.html +[`customize-path-rejection`]: https://github.com/tokio-rs/axum/blob/main/examples/customize-path-rejection/src/main.rs + +```rust +pub struct Path(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **CryptoRng** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + +- **DerefMut** + - ```rust + fn deref_mut(self: &mut Self) -> &mut ::Target { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRequest** + - ```rust + fn from_request(req: Request, state: &S) -> impl Future>::Rejection>> { /* ... */ } + ``` + +- **FromRequestParts** + - ```rust + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result::Rejection> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **OptionalFromRequestParts** + - ```rust + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result, ::Rejection> { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **Receiver** +- **RefUnwindSafe** +- **Rng** +- **RngCore** + - ```rust + fn next_u32(self: &mut Self) -> u32 { /* ... */ } + ``` + + - ```rust + fn next_u64(self: &mut Self) -> u64 { /* ... */ } + ``` + + - ```rust + fn fill_bytes(self: &mut Self, dst: &mut [u8]) { /* ... */ } + ``` + +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryCryptoRng** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **TryRngCore** + - ```rust + fn try_next_u32(self: &mut Self) -> Result::Error> { /* ... */ } + ``` + + - ```rust + fn try_next_u64(self: &mut Self) -> Result::Error> { /* ... */ } + ``` + + - ```rust + fn try_fill_bytes(self: &mut Self, dst: &mut [u8]) -> Result<(), ::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `ErrorKind` + +**Attributes:** + +- `MustUse { reason: None }` +- `NonExhaustive` + +The kinds of errors that can happen we deserializing into a [`Path`]. + +This type is obtained through [`FailedToDeserializePathParams::kind`] or +[`FailedToDeserializePathParams::into_kind`] and is useful for building +more precise error messages. + +```rust +pub enum ErrorKind { + WrongNumberOfParameters { + got: usize, + expected: usize, + }, + ParseErrorAtKey { + key: String, + value: String, + expected_type: &''static str, + }, + ParseErrorAtIndex { + index: usize, + value: String, + expected_type: &''static str, + }, + ParseError { + value: String, + expected_type: &''static str, + }, + InvalidUtf8InPathParam { + key: String, + }, + UnsupportedType { + name: &''static str, + }, + DeserializeError { + key: String, + value: String, + message: String, + }, + Message(String), +} +``` + +##### Variants + +###### `WrongNumberOfParameters` + +The URI contained the wrong number of parameters. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `got` | `usize` | The number of actual parameters in the URI. | +| `expected` | `usize` | The number of expected parameters. | + +###### `ParseErrorAtKey` + +Failed to parse the value at a specific key into the expected type. + +This variant is used when deserializing into types that have named fields, such as structs. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `key` | `String` | The key at which the value was located. | +| `value` | `String` | The value from the URI. | +| `expected_type` | `&''static str` | The expected type of the value. | + +###### `ParseErrorAtIndex` + +Failed to parse the value at a specific index into the expected type. + +This variant is used when deserializing into sequence types, such as tuples. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `index` | `usize` | The index at which the value was located. | +| `value` | `String` | The value from the URI. | +| `expected_type` | `&''static str` | The expected type of the value. | + +###### `ParseError` + +Failed to parse a value into the expected type. + +This variant is used when deserializing into a primitive type (such as `String` and `u32`). + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `value` | `String` | The value from the URI. | +| `expected_type` | `&''static str` | The expected type of the value. | + +###### `InvalidUtf8InPathParam` + +A parameter contained text that, once percent decoded, wasn't valid UTF-8. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `key` | `String` | The key at which the invalid value was located. | + +###### `UnsupportedType` + +Tried to serialize into an unsupported type such as nested maps. + +This error kind is caused by programmer errors and thus gets converted into a `500 Internal +Server Error` response. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `name` | `&''static str` | The name of the unsupported type. | + +###### `DeserializeError` + +Failed to deserialize the value with a custom deserialization error. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `key` | `String` | The key at which the invalid value was located. | +| `value` | `String` | The value that failed to deserialize. | +| `message` | `String` | The deserializaation failure message. | + +###### `Message` + +Catch-all variant for errors that don't fit any other variant. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `String` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &ErrorKind) -> bool { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **StructuralPartialEq** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `FailedToDeserializePathParams` + +Rejection type for [`Path`] if the captured routes params couldn't be deserialized +into the expected type. + +```rust +pub struct FailedToDeserializePathParams(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn kind(self: &Self) -> &ErrorKind { /* ... */ } + ``` + Get a reference to the underlying error kind. + +- ```rust + pub fn into_kind(self: Self) -> ErrorKind { /* ... */ } + ``` + Convert this error into the underlying error kind. + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializePathParams) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `RawPathParams` + +Extractor that will get captures from the URL without deserializing them. + +In general you should prefer to use [`Path`] as it is higher level, however `RawPathParams` is +suitable if just want the raw params without deserializing them and thus saving some +allocations. + +Any percent encoded parameters will be automatically decoded. The decoded parameters must be +valid UTF-8, otherwise `RawPathParams` will fail and return a `400 Bad Request` response. + +# Example + +```rust,no_run +use axum::{ + extract::RawPathParams, + routing::get, + Router, +}; + +async fn users_teams_show(params: RawPathParams) { + for (key, value) in ¶ms { + println!("{key:?} = {value:?}"); + } +} + +let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show)); +# let _: Router = app; +``` + +```rust +pub struct RawPathParams(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn iter(self: &Self) -> RawPathParamsIter<''_> { /* ... */ } + ``` + Get an iterator over the path parameters. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRequest** + - ```rust + fn from_request(req: Request, state: &S) -> impl Future>::Rejection>> { /* ... */ } + ``` + +- **FromRequestParts** + - ```rust + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result::Rejection> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> ::IntoIter { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `RawPathParamsIter` + +An iterator over raw path parameters. + +Created with [`RawPathParams::iter`]. + +```rust +pub struct RawPathParamsIter<''a>(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **IteratorRandom** +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidUtf8InPathParam` + +Rejection used by [`RawPathParams`] if a parameter contained text that, once percent decoded, +wasn't valid UTF-8. + +```rust +pub struct InvalidUtf8InPathParam { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidUtf8InPathParam) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +## Module `rejection` + +Rejection response types. + +```rust +pub mod rejection { /* ... */ } +``` + +### Types + +#### Struct `JsonDataError` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"json\")))]")` +- `Other("#[doc(cfg(feature = \"json\"))]")` + +Rejection type for [`Json`](super::Json). + +This rejection is used if the request body is syntactically valid JSON but couldn't be +deserialized into the target type. + +```rust +pub struct JsonDataError(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: JsonDataError) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `JsonSyntaxError` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"json\")))]")` +- `Other("#[doc(cfg(feature = \"json\"))]")` + +Rejection type for [`Json`](super::Json). + +This rejection is used if the request body didn't contain syntactically valid JSON. + +```rust +pub struct JsonSyntaxError(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: JsonSyntaxError) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MissingJsonContentType` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"json\")))]")` +- `Other("#[doc(cfg(feature = \"json\"))]")` +- `NonExhaustive` + +Rejection type for [`Json`](super::Json) used if the `Content-Type` +header is missing. + +```rust +pub struct MissingJsonContentType; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MissingJsonContentType) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MissingExtension` + +Rejection type for [`Extension`](super::Extension) if an expected +request extension was not found. + +```rust +pub struct MissingExtension(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MissingExtension) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MissingPathParams` + +**Attributes:** + +- `NonExhaustive` + +Rejection type used if axum's internal representation of path parameters +is missing. This is commonly caused by extracting `Request<_>`. `Path` +must be extracted first. + +```rust +pub struct MissingPathParams; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MissingPathParams) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: MissingPathParams) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidFormContentType` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`Form`](super::Form) or [`RawForm`](super::RawForm) +used if the `Content-Type` header is missing +or its value is not `application/x-www-form-urlencoded`. + +```rust +pub struct InvalidFormContentType; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidFormContentType) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: InvalidFormContentType) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `FailedToDeserializeForm` + +Rejection type used if the [`Form`](super::Form) extractor is unable to +deserialize the form into the target type. + +```rust +pub struct FailedToDeserializeForm(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializeForm) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `FailedToDeserializeFormBody` + +Rejection type used if the [`Form`](super::Form) extractor is unable to +deserialize the form body into the target type. + +```rust +pub struct FailedToDeserializeFormBody(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializeFormBody) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `FailedToDeserializeQueryString` + +Rejection type used if the [`Query`](super::Query) extractor is unable to +deserialize the query string into the target type. + +```rust +pub struct FailedToDeserializeQueryString(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializeQueryString) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `QueryRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`Query`](super::Query). + +Contains one variant for each way the [`Query`](super::Query) extractor +can fail. + +```rust +pub enum QueryRejection { + FailedToDeserializeQueryString(FailedToDeserializeQueryString), +} +``` + +##### Variants + +###### `FailedToDeserializeQueryString` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `FailedToDeserializeQueryString` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializeQueryString) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `FormRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`Form`](super::Form). + +Contains one variant for each way the [`Form`](super::Form) extractor +can fail. + +```rust +pub enum FormRejection { + InvalidFormContentType(InvalidFormContentType), + FailedToDeserializeForm(FailedToDeserializeForm), + FailedToDeserializeFormBody(FailedToDeserializeFormBody), + BytesRejection(BytesRejection), +} +``` + +##### Variants + +###### `InvalidFormContentType` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidFormContentType` | | + +###### `FailedToDeserializeForm` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `FailedToDeserializeForm` | | + +###### `FailedToDeserializeFormBody` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `FailedToDeserializeFormBody` | | + +###### `BytesRejection` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `BytesRejection` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidFormContentType) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: FailedToDeserializeForm) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: FailedToDeserializeFormBody) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: BytesRejection) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `RawFormRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`RawForm`](super::RawForm). + +Contains one variant for each way the [`RawForm`](super::RawForm) extractor +can fail. + +```rust +pub enum RawFormRejection { + InvalidFormContentType(InvalidFormContentType), + BytesRejection(BytesRejection), +} +``` + +##### Variants + +###### `InvalidFormContentType` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidFormContentType` | | + +###### `BytesRejection` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `BytesRejection` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidFormContentType) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: BytesRejection) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `JsonRejection` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"json\")))]")` +- `Other("#[doc(cfg(feature = \"json\"))]")` +- `NonExhaustive` + +Rejection used for [`Json`](super::Json). + +Contains one variant for each way the [`Json`](super::Json) extractor +can fail. + +```rust +pub enum JsonRejection { + JsonDataError(JsonDataError), + JsonSyntaxError(JsonSyntaxError), + MissingJsonContentType(MissingJsonContentType), + BytesRejection(BytesRejection), +} +``` + +##### Variants + +###### `JsonDataError` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `JsonDataError` | | + +###### `JsonSyntaxError` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `JsonSyntaxError` | | + +###### `MissingJsonContentType` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MissingJsonContentType` | | + +###### `BytesRejection` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `BytesRejection` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: JsonDataError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: JsonSyntaxError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: MissingJsonContentType) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: BytesRejection) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `ExtensionRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`Extension`](super::Extension). + +Contains one variant for each way the [`Extension`](super::Extension) extractor +can fail. + +```rust +pub enum ExtensionRejection { + MissingExtension(MissingExtension), +} +``` + +##### Variants + +###### `MissingExtension` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MissingExtension` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MissingExtension) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `PathRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`Path`](super::Path). + +Contains one variant for each way the [`Path`](super::Path) extractor +can fail. + +```rust +pub enum PathRejection { + FailedToDeserializePathParams(FailedToDeserializePathParams), + MissingPathParams(MissingPathParams), +} +``` + +##### Variants + +###### `FailedToDeserializePathParams` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `FailedToDeserializePathParams` | | + +###### `MissingPathParams` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MissingPathParams` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: FailedToDeserializePathParams) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: MissingPathParams) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `RawPathParamsRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`RawPathParams`](super::RawPathParams). + +Contains one variant for each way the [`RawPathParams`](super::RawPathParams) extractor +can fail. + +```rust +pub enum RawPathParamsRejection { + InvalidUtf8InPathParam(InvalidUtf8InPathParam), + MissingPathParams(MissingPathParams), +} +``` + +##### Variants + +###### `InvalidUtf8InPathParam` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidUtf8InPathParam` | | + +###### `MissingPathParams` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MissingPathParams` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidUtf8InPathParam) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: MissingPathParams) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MatchedPathMissing` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"matched-path\")))]")` +- `Other("#[doc(cfg(feature = \"matched-path\"))]")` +- `NonExhaustive` + +Rejection if no matched path could be found. + +See [`MatchedPath`](super::MatchedPath) for more details. + +```rust +pub struct MatchedPathMissing; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MatchedPathMissing) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `MatchedPathRejection` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"matched-path\")))]")` +- `Other("#[doc(cfg(feature = \"matched-path\"))]")` +- `NonExhaustive` + +Rejection used for [`MatchedPath`](super::MatchedPath). + +```rust +pub enum MatchedPathRejection { + MatchedPathMissing(MatchedPathMissing), +} +``` + +##### Variants + +###### `MatchedPathMissing` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MatchedPathMissing` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MatchedPathMissing) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `NestedPathRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`NestedPath`](super::NestedPath). + +This rejection is used if the matched route wasn't nested. + +```rust +pub struct NestedPathRejection; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Re-exports + +#### Re-export `FailedToDeserializePathParams` + +```rust +pub use crate::extract::path::FailedToDeserializePathParams; +``` + +#### Re-export `InvalidUtf8InPathParam` + +```rust +pub use crate::extract::path::InvalidUtf8InPathParam; +``` + +#### Re-export `axum_core::extract::rejection::*` + +```rust +pub use axum_core::extract::rejection::*; +``` + +## Module `ws` + +**Attributes:** + +- `Other("#[(feature = \"ws\")]")` + +Handle WebSocket connections. + +# Example + +``` +use axum::{ + extract::ws::{WebSocketUpgrade, WebSocket}, + routing::any, + response::{IntoResponse, Response}, + Router, +}; + +let app = Router::new().route("/ws", any(handler)); + +async fn handler(ws: WebSocketUpgrade) -> Response { + ws.on_upgrade(handle_socket) +} + +async fn handle_socket(mut socket: WebSocket) { + while let Some(msg) = socket.recv().await { + let msg = if let Ok(msg) = msg { + msg + } else { + // client disconnected + return; + }; + + if socket.send(msg).await.is_err() { + // client disconnected + return; + } + } +} +# let _: Router = app; +``` + +# Passing data and/or state to an `on_upgrade` callback + +``` +use axum::{ + extract::{ws::{WebSocketUpgrade, WebSocket}, State}, + response::Response, + routing::any, + Router, +}; + +#[derive(Clone)] +struct AppState { + // ... +} + +async fn handler(ws: WebSocketUpgrade, State(state): State) -> Response { + ws.on_upgrade(|socket| handle_socket(socket, state)) +} + +async fn handle_socket(socket: WebSocket, state: AppState) { + // ... +} + +let app = Router::new() + .route("/ws", any(handler)) + .with_state(AppState { /* ... */ }); +# let _: Router = app; +``` + +# Read and write concurrently + +If you need to read and write concurrently from a [`WebSocket`] you can use +[`StreamExt::split`]: + +```rust,no_run +use axum::{Error, extract::ws::{WebSocket, Message}}; +use futures_util::{sink::SinkExt, stream::{StreamExt, SplitSink, SplitStream}}; + +async fn handle_socket(mut socket: WebSocket) { + let (mut sender, mut receiver) = socket.split(); + + tokio::spawn(write(sender)); + tokio::spawn(read(receiver)); +} + +async fn read(receiver: SplitStream) { + // ... +} + +async fn write(sender: SplitSink) { + // ... +} +``` + +[`StreamExt::split`]: https://docs.rs/futures/0.3.17/futures/stream/trait.StreamExt.html#method.split + +```rust +pub mod ws { /* ... */ } +``` + +### Modules + +## Module `rejection` + +WebSocket specific rejections. + +```rust +pub mod rejection { /* ... */ } +``` + +### Types + +#### Struct `MethodNotGet` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct MethodNotGet; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MethodNotGet) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MethodNotConnect` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct MethodNotConnect; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MethodNotConnect) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidConnectionHeader` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct InvalidConnectionHeader; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidConnectionHeader) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidUpgradeHeader` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct InvalidUpgradeHeader; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidUpgradeHeader) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidProtocolPseudoheader` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct InvalidProtocolPseudoheader; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidProtocolPseudoheader) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidWebSocketVersionHeader` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct InvalidWebSocketVersionHeader; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidWebSocketVersionHeader) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `WebSocketKeyHeaderMissing` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +```rust +pub struct WebSocketKeyHeaderMissing; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: WebSocketKeyHeaderMissing) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `ConnectionNotUpgradable` + +**Attributes:** + +- `NonExhaustive` + +Rejection type for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +This rejection is returned if the connection cannot be upgraded for example if the +request is HTTP/1.0. + +See [MDN] for more details about connection upgrades. + +[MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade + +```rust +pub struct ConnectionNotUpgradable; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: ConnectionNotUpgradable) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `WebSocketUpgradeRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`WebSocketUpgrade`](super::WebSocketUpgrade). + +Contains one variant for each way the [`WebSocketUpgrade`](super::WebSocketUpgrade) +extractor can fail. + +```rust +pub enum WebSocketUpgradeRejection { + MethodNotGet(MethodNotGet), + MethodNotConnect(MethodNotConnect), + InvalidConnectionHeader(InvalidConnectionHeader), + InvalidUpgradeHeader(InvalidUpgradeHeader), + InvalidProtocolPseudoheader(InvalidProtocolPseudoheader), + InvalidWebSocketVersionHeader(InvalidWebSocketVersionHeader), + WebSocketKeyHeaderMissing(WebSocketKeyHeaderMissing), + ConnectionNotUpgradable(ConnectionNotUpgradable), +} +``` + +##### Variants + +###### `MethodNotGet` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MethodNotGet` | | + +###### `MethodNotConnect` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `MethodNotConnect` | | + +###### `InvalidConnectionHeader` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidConnectionHeader` | | + +###### `InvalidUpgradeHeader` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidUpgradeHeader` | | + +###### `InvalidProtocolPseudoheader` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidProtocolPseudoheader` | | + +###### `InvalidWebSocketVersionHeader` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidWebSocketVersionHeader` | | + +###### `WebSocketKeyHeaderMissing` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `WebSocketKeyHeaderMissing` | | + +###### `ConnectionNotUpgradable` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `ConnectionNotUpgradable` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: MethodNotGet) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: MethodNotConnect) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: InvalidConnectionHeader) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: InvalidUpgradeHeader) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: InvalidProtocolPseudoheader) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: InvalidWebSocketVersionHeader) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: WebSocketKeyHeaderMissing) -> Self { /* ... */ } + ``` + + - ```rust + fn from(inner: ConnectionNotUpgradable) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +## Module `close_code` + +Constants for [`CloseCode`]s. + +[`CloseCode`]: super::CloseCode + +```rust +pub mod close_code { /* ... */ } +``` + +### Constants and Statics + +#### Constant `NORMAL` + +Indicates a normal closure, meaning that the purpose for which the connection was +established has been fulfilled. + +```rust +pub const NORMAL: u16 = 1000; +``` + +#### Constant `AWAY` + +Indicates that an endpoint is "going away", such as a server going down or a browser having +navigated away from a page. + +```rust +pub const AWAY: u16 = 1001; +``` + +#### Constant `PROTOCOL` + +Indicates that an endpoint is terminating the connection due to a protocol error. + +```rust +pub const PROTOCOL: u16 = 1002; +``` + +#### Constant `UNSUPPORTED` + +Indicates that an endpoint is terminating the connection because it has received a type of +data that it cannot accept. + +For example, an endpoint MAY send this if it understands only text data, but receives a binary message. + +```rust +pub const UNSUPPORTED: u16 = 1003; +``` + +#### Constant `STATUS` + +Indicates that no status code was included in a closing frame. + +```rust +pub const STATUS: u16 = 1005; +``` + +#### Constant `ABNORMAL` + +Indicates an abnormal closure. + +```rust +pub const ABNORMAL: u16 = 1006; +``` + +#### Constant `INVALID` + +Indicates that an endpoint is terminating the connection because it has received data +within a message that was not consistent with the type of the message. + +For example, an endpoint received non-UTF-8 RFC3629 data within a text message. + +```rust +pub const INVALID: u16 = 1007; +``` + +#### Constant `POLICY` + +Indicates that an endpoint is terminating the connection because it has received a message +that violates its policy. + +This is a generic status code that can be returned when there is +no other more suitable status code (e.g., `UNSUPPORTED` or `SIZE`) or if there is a need to +hide specific details about the policy. + +```rust +pub const POLICY: u16 = 1008; +``` + +#### Constant `SIZE` + +Indicates that an endpoint is terminating the connection because it has received a message +that is too big for it to process. + +```rust +pub const SIZE: u16 = 1009; +``` + +#### Constant `EXTENSION` + +Indicates that an endpoint (client) is terminating the connection because the server +did not respond to extension negotiation correctly. + +Specifically, the client has expected the server to negotiate one or more extension(s), +but the server didn't return them in the response message of the WebSocket handshake. +The list of extensions that are needed should be given as the reason for closing. +Note that this status code is not used by the server, +because it can fail the WebSocket handshake instead. + +```rust +pub const EXTENSION: u16 = 1010; +``` + +#### Constant `ERROR` + +Indicates that a server is terminating the connection because it encountered an unexpected +condition that prevented it from fulfilling the request. + +```rust +pub const ERROR: u16 = 1011; +``` + +#### Constant `RESTART` + +Indicates that the server is restarting. + +```rust +pub const RESTART: u16 = 1012; +``` + +#### Constant `AGAIN` + +Indicates that the server is overloaded and the client should either connect to a different +IP (when multiple targets exist), or reconnect to the same IP when a user has performed an +action. + +```rust +pub const AGAIN: u16 = 1013; +``` + +### Types + +#### Struct `WebSocketUpgrade` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"ws\")))]")` +- `Other("#[doc(cfg(feature = \"ws\"))]")` +- `MustUse { reason: None }` + +Extractor for establishing WebSocket connections. + +For HTTP/1.1 requests, this extractor requires the request method to be `GET`; +in later versions, `CONNECT` is used instead. +To support both, it should be used with [`any`](crate::routing::any). + +See the [module docs](self) for an example. + +[`MethodFilter`]: crate::routing::MethodFilter + +```rust +pub struct WebSocketUpgrade { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn read_buffer_size(self: Self, size: usize) -> Self { /* ... */ } + ``` + Read buffer capacity. The default value is 128KiB + +- ```rust + pub fn write_buffer_size(self: Self, size: usize) -> Self { /* ... */ } + ``` + The target minimum size of the write buffer to reach before writing the data + +- ```rust + pub fn max_write_buffer_size(self: Self, max: usize) -> Self { /* ... */ } + ``` + The max size of the write buffer in bytes. Setting this can provide backpressure + +- ```rust + pub fn max_message_size(self: Self, max: usize) -> Self { /* ... */ } + ``` + Set the maximum message size (defaults to 64 megabytes) + +- ```rust + pub fn max_frame_size(self: Self, max: usize) -> Self { /* ... */ } + ``` + Set the maximum frame size (defaults to 16 megabytes) + +- ```rust + pub fn accept_unmasked_frames(self: Self, accept: bool) -> Self { /* ... */ } + ``` + Allow server to accept unmasked frames (defaults to false) + +- ```rust + pub fn protocols(self: Self, protocols: I) -> Self +where + I: IntoIterator, + ::Item: Into> { /* ... */ } + ``` + Set the known protocols. + +- ```rust + pub fn selected_protocol(self: &Self) -> Option<&HeaderValue> { /* ... */ } + ``` + Return the selected WebSocket subprotocol, if one has been chosen. + +- ```rust + pub fn on_failed_upgrade(self: Self, callback: C) -> WebSocketUpgrade +where + C: OnFailedUpgrade { /* ... */ } + ``` + Provide a callback to call if upgrading the connection fails. + +- ```rust + pub fn on_upgrade(self: Self, callback: C) -> Response +where + C: FnOnce(WebSocket) -> Fut + Send + ''static, + Fut: Future + Send + ''static, + F: OnFailedUpgrade { /* ... */ } + ``` + Finalize upgrading the connection and call the provided callback with + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRequest** + - ```rust + fn from_request(req: Request, state: &S) -> impl Future>::Rejection>> { /* ... */ } + ``` + +- **FromRequestParts** + - ```rust + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result::Rejection> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `DefaultOnFailedUpgrade` + +**Attributes:** + +- `NonExhaustive` + +The default `OnFailedUpgrade` used by `WebSocketUpgrade`. + +It simply ignores the error. + +```rust +pub struct DefaultOnFailedUpgrade; +``` + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **OnFailedUpgrade** + - ```rust + fn call(self: Self, _error: Error) { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `WebSocket` + +A stream of WebSocket messages. + +See [the module level documentation](self) for more details. + +```rust +pub struct WebSocket { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option> { /* ... */ } + ``` + Receive another message. + +- ```rust + pub async fn send(self: &mut Self, msg: Message) -> Result<(), Error> { /* ... */ } + ``` + Send a message. + +- ```rust + pub fn protocol(self: &Self) -> Option<&HeaderValue> { /* ... */ } + ``` + Return the selected WebSocket subprotocol, if one has been chosen. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedStream** + - ```rust + fn is_terminated(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the websocket has been terminated. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sink** + - ```rust + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), ::Error> { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + +- **SinkExt** +- **Stream** + - ```rust + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Item>> { /* ... */ } + ``` + +- **StreamExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **TryStream** + - ```rust + fn try_poll_next(self: Pin<&mut S>, cx: &mut Context<''_>) -> Poll::Ok, ::Error>>> { /* ... */ } + ``` + +- **TryStreamExt** +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `Utf8Bytes` + +UTF-8 wrapper for [Bytes]. + +An [Utf8Bytes] is always guaranteed to contain valid UTF-8. + +```rust +pub struct Utf8Bytes(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub const fn from_static(str: &''static str) -> Self { /* ... */ } + ``` + Creates from a static str. + +- ```rust + pub fn as_str(self: &Self) -> &str { /* ... */ } + ``` + Returns as a string slice. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Utf8Bytes { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Utf8Bytes { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(s: String) -> Self { /* ... */ } + ``` + + - ```rust + fn from(s: &str) -> Self { /* ... */ } + ``` + + - ```rust + fn from(s: &String) -> Self { /* ... */ } + ``` + + - ```rust + fn from(Utf8Bytes: Utf8Bytes) -> Self { /* ... */ } + ``` + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Utf8Bytes) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &T) -> bool { /* ... */ } + ``` + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **Receiver** +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + + - ```rust + fn try_from(bytes: Bytes) -> Result::Error> { /* ... */ } + ``` + + - ```rust + fn try_from(v: Vec) -> Result::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Type Alias `CloseCode` + +Status code used to indicate why an endpoint is closing the WebSocket connection. + +```rust +pub type CloseCode = u16; +``` + +#### Struct `CloseFrame` + +A struct representing the close command. + +```rust +pub struct CloseFrame { + pub code: CloseCode, + pub reason: Utf8Bytes, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `code` | `CloseCode` | The reason as a code. | +| `reason` | `Utf8Bytes` | The reason as text string. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> CloseFrame { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &CloseFrame) -> bool { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `Message` + +A WebSocket message. + +```rust +pub enum Message { + Text(Utf8Bytes), + Binary(crate::body::Bytes), + Ping(crate::body::Bytes), + Pong(crate::body::Bytes), + Close(Option), +} +``` + +##### Variants + +###### `Text` + +A text WebSocket message + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `Utf8Bytes` | | + +###### `Binary` + +A binary WebSocket message + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::body::Bytes` | | + +###### `Ping` + +A ping message with the specified payload + +The payload here must have a length less than 125 bytes. + +Ping messages will be automatically responded to by the server, so you do not have to worry +about dealing with them yourself. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::body::Bytes` | | + +###### `Pong` + +A pong message with the specified payload + +The payload here must have a length less than 125 bytes. + +Pong messages will be automatically sent to the client if a ping message is received, so +you do not have to worry about constructing them yourself unless you want to implement a +[unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3). + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::body::Bytes` | | + +###### `Close` + +A close message with the optional close frame. + +You may "uncleanly" close a WebSocket connection at any time +by simply dropping the [`WebSocket`]. +However, you may also use the graceful closing protocol, in which +1. peer A sends a close frame, and does not send any further messages; +2. peer B responds with a close frame, and does not send any further messages; +3. peer A processes the remaining messages sent by peer B, before finally +4. both peers close the connection. + +After sending a close frame, +you may still read messages, +but attempts to send another message will error. +After receiving a close frame, +axum will automatically respond with a close frame if necessary +(you do not have to deal with this yourself). +Since no further messages will be received, +you may either do nothing +or explicitly drop the connection. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `Option` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_data(self: Self) -> Bytes { /* ... */ } + ``` + Consume the WebSocket and return it as binary data. + +- ```rust + pub fn into_text(self: Self) -> Result { /* ... */ } + ``` + Attempt to consume the WebSocket message and convert it to a Utf8Bytes. + +- ```rust + pub fn to_text(self: &Self) -> Result<&str, Error> { /* ... */ } + ``` + Attempt to get a &str from the WebSocket message, + +- ```rust + pub fn text(string: S) -> Message +where + S: Into { /* ... */ } + ``` + Create a new text WebSocket message from a stringable. + +- ```rust + pub fn binary(bin: B) -> Message +where + B: Into { /* ... */ } + ``` + Create a new binary WebSocket message by converting to `Bytes`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Message { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(string: String) -> Self { /* ... */ } + ``` + + - ```rust + fn from(string: &''s str) -> Self { /* ... */ } + ``` + + - ```rust + fn from(data: &''b [u8]) -> Self { /* ... */ } + ``` + + - ```rust + fn from(data: Bytes) -> Self { /* ... */ } + ``` + + - ```rust + fn from(data: Vec) -> Self { /* ... */ } + ``` + + - ```rust + fn from(msg: Message) -> Self { /* ... */ } + ``` + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Message) -> bool { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sink** + - ```rust + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), ::Error> { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Traits + +#### Trait `OnFailedUpgrade` + +What to do when a connection upgrade fails. + +See [`WebSocketUpgrade::on_failed_upgrade`] for more details. + +```rust +pub trait OnFailedUpgrade: Send + ''static { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `call`: Call the callback. + +##### Implementations + +This trait is implemented for the following types: + +- `F` with +- `DefaultOnFailedUpgrade` + +## Module `multipart` + +**Attributes:** + +- `Other("#[(feature = \"multipart\")]")` + +Extractor that parses `multipart/form-data` requests commonly used with file uploads. + +See [`Multipart`] for more details. + +```rust +pub mod multipart { /* ... */ } +``` + +### Types + +#### Struct `Multipart` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"multipart\")))]")` +- `Other("#[doc(cfg(feature = \"multipart\"))]")` + +Extractor that parses `multipart/form-data` requests (commonly used with file uploads). + +⚠️ Since extracting multipart form data from the request requires consuming the body, the +`Multipart` extractor must be *last* if there are multiple extractors in a handler. +See ["the order of extractors"][order-of-extractors] + +[order-of-extractors]: crate::extract#the-order-of-extractors + +# Example + +```rust,no_run +use axum::{ + extract::Multipart, + routing::post, + Router, +}; +use futures_util::stream::StreamExt; + +async fn upload(mut multipart: Multipart) { + while let Some(mut field) = multipart.next_field().await.unwrap() { + let name = field.name().unwrap().to_string(); + let data = field.bytes().await.unwrap(); + + println!("Length of `{}` is {} bytes", name, data.len()); + } +} + +let app = Router::new().route("/upload", post(upload)); +# let _: Router = app; +``` + +# Large Files + +For security reasons, by default, `Multipart` limits the request body size to 2MB. +See [`DefaultBodyLimit`][default-body-limit] for how to configure this limit. + +[default-body-limit]: crate::extract::DefaultBodyLimit + +```rust +pub struct Multipart { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn next_field(self: &mut Self) -> Result>, MultipartError> { /* ... */ } + ``` + Yields the next [`Field`] if available. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRequest** + - ```rust + async fn from_request(req: Request, _state: &S) -> Result::Rejection> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **OptionalFromRequest** + - ```rust + async fn from_request(req: Request, _state: &S) -> Result, ::Rejection> { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `Field` + +A single field in a multipart stream. + +```rust +pub struct Field<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn name(self: &Self) -> Option<&str> { /* ... */ } + ``` + The field name found in the + +- ```rust + pub fn file_name(self: &Self) -> Option<&str> { /* ... */ } + ``` + The file name found in the + +- ```rust + pub fn content_type(self: &Self) -> Option<&str> { /* ... */ } + ``` + Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field. + +- ```rust + pub fn headers(self: &Self) -> &HeaderMap { /* ... */ } + ``` + Get a map of headers as [`HeaderMap`]. + +- ```rust + pub async fn bytes(self: Self) -> Result { /* ... */ } + ``` + Get the full data of the field as [`Bytes`]. + +- ```rust + pub async fn text(self: Self) -> Result { /* ... */ } + ``` + Get the full field data as text. + +- ```rust + pub async fn chunk(self: &mut Self) -> Result, MultipartError> { /* ... */ } + ``` + Stream a chunk of the field data. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Stream** + - ```rust + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Item>> { /* ... */ } + ``` + +- **StreamExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **TryStream** + - ```rust + fn try_poll_next(self: Pin<&mut S>, cx: &mut Context<''_>) -> Poll::Ok, ::Error>>> { /* ... */ } + ``` + +- **TryStreamExt** +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `MultipartError` + +Errors associated with parsing `multipart/form-data` requests. + +```rust +pub struct MultipartError { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Enum `MultipartRejection` + +**Attributes:** + +- `NonExhaustive` + +Rejection used for [`Multipart`]. + +Contains one variant for each way the [`Multipart`] extractor can fail. + +```rust +pub enum MultipartRejection { + InvalidBoundary(InvalidBoundary), +} +``` + +##### Variants + +###### `InvalidBoundary` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `InvalidBoundary` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn std::error::Error + ''static> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidBoundary) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `InvalidBoundary` + +**Attributes:** + +- `NonExhaustive` + +Rejection type used if the `boundary` in a `multipart/form-data` is +missing or invalid. + +```rust +pub struct InvalidBoundary; +``` + +##### Implementations + +###### Methods + +- ```rust + pub fn body_text(self: &Self) -> String { /* ... */ } + ``` + Get the response body text used for this rejection. + +- ```rust + pub fn status(self: &Self) -> http::StatusCode { /* ... */ } + ``` + Get the status code used for this rejection. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(inner: InvalidBoundary) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> $crate::response::Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **ToStringFallible** + - ```rust + fn try_to_string(self: &Self) -> Result { /* ... */ } + ``` + [`ToString::to_string`][`alloc::string::ToString::to_string`], but without panic on OOM. + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Re-exports + +#### Re-export `DefaultBodyLimit` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::DefaultBodyLimit; +``` + +#### Re-export `FromRef` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::FromRef; +``` + +#### Re-export `FromRequest` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::FromRequest; +``` + +#### Re-export `FromRequestParts` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::FromRequestParts; +``` + +#### Re-export `OptionalFromRequest` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::OptionalFromRequest; +``` + +#### Re-export `OptionalFromRequestParts` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::OptionalFromRequestParts; +``` + +#### Re-export `Request` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::extract::Request; +``` + +#### Re-export `FromRef` + +**Attributes:** + +- `Other("#[(feature = \"macros\")]")` + +```rust +pub use axum_macros::FromRef; +``` + +#### Re-export `FromRequest` + +**Attributes:** + +- `Other("#[(feature = \"macros\")]")` + +```rust +pub use axum_macros::FromRequest; +``` + +#### Re-export `FromRequestParts` + +**Attributes:** + +- `Other("#[(feature = \"macros\")]")` + +```rust +pub use axum_macros::FromRequestParts; +``` + +#### Re-export `NestedPath` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::nested_path::NestedPath; +``` + +#### Re-export `Path` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::path::Path; +``` + +#### Re-export `RawPathParams` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::path::RawPathParams; +``` + +#### Re-export `RawForm` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::raw_form::RawForm; +``` + +#### Re-export `RawQuery` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::raw_query::RawQuery; +``` + +#### Re-export `State` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::state::State; +``` + +#### Re-export `ConnectInfo` + +**Attributes:** + +- `Other("#[doc(inline)]")` +- `Other("#[(feature = \"tokio\")]")` + +```rust +pub use self::connect_info::ConnectInfo; +``` + +#### Re-export `Json` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` +- `Other("#[(feature = \"json\")]")` + +```rust +pub use crate::Json; +``` + +#### Re-export `Extension` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use crate::Extension; +``` + +#### Re-export `Form` + +**Attributes:** + +- `Other("#[(feature = \"form\")]")` +- `Other("#[doc(no_inline)]")` + +```rust +pub use crate::form::Form; +``` + +#### Re-export `MatchedPath` + +**Attributes:** + +- `Other("#[(feature = \"matched-path\")]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::matched_path::MatchedPath; +``` + +#### Re-export `Multipart` + +**Attributes:** + +- `Other("#[(feature = \"multipart\")]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::multipart::Multipart; +``` + +#### Re-export `Query` + +**Attributes:** + +- `Other("#[(feature = \"query\")]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::query::Query; +``` + +#### Re-export `OriginalUri` + +**Attributes:** + +- `Other("#[(feature = \"original-uri\")]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::original_uri::OriginalUri; +``` + +#### Re-export `WebSocketUpgrade` + +**Attributes:** + +- `Other("#[(feature = \"ws\")]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::ws::WebSocketUpgrade; +``` + +## Module `handler` + +Async functions that can be used to handle requests. + +In axum a "handler" is an async function that accepts zero or more +["extractors"](crate::extract) as arguments and returns something that +can be converted [into a response](crate::response). + +Handlers are where your application logic lives and axum applications are built +by routing between handlers. + +[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html + +Some examples of handlers: + +```rust +use axum::{body::Bytes, http::StatusCode}; + +// Handler that immediately returns an empty `200 OK` response. +async fn unit_handler() {} + +// Handler that immediately returns a `200 OK` response with a plain text +// body. +async fn string_handler() -> String { + "Hello, World!".to_string() +} + +// Handler that buffers the request body and returns it. +// +// This works because `Bytes` implements `FromRequest` +// and therefore can be used as an extractor. +// +// `String` and `StatusCode` both implement `IntoResponse` and +// therefore `Result` also implements `IntoResponse` +async fn echo(body: Bytes) -> Result { + if let Ok(string) = String::from_utf8(body.to_vec()) { + Ok(string) + } else { + Err(StatusCode::BAD_REQUEST) + } +} +``` + +Instead of a direct `StatusCode`, it makes sense to use intermediate error type +that can ultimately be converted to `Response`. This allows using `?` operator +in handlers. See those examples: + +* [`anyhow-error-response`][anyhow] for generic boxed errors +* [`error-handling`][error-handling] for application-specific detailed errors + +[anyhow]: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs +[error-handling]: https://github.com/tokio-rs/axum/blob/main/examples/error-handling/src/main.rs + +## Debugging handler type errors + +For a function to be used as a handler it must implement the [`Handler`] trait. +axum provides blanket implementations for functions that: + +- Are `async fn`s. +- Take no more than 16 arguments that all implement `Send`. + - All except the last argument implement [`FromRequestParts`]. + - The last argument implements [`FromRequest`]. +- Returns something that implements [`IntoResponse`]. +- If a closure is used it must implement `Clone + Send` and be +`'static`. +- Returns a future that is `Send`. The most common way to accidentally make a +future `!Send` is to hold a `!Send` type across an await. + +Unfortunately Rust gives poor error messages if you try to use a function +that doesn't quite match what's required by [`Handler`]. + +You might get an error like this: + +```not_rust +error[E0277]: the trait bound `fn(bool) -> impl Future {handler}: Handler<_, _>` is not satisfied + --> src/main.rs:13:44 + | +13 | let app = Router::new().route("/", get(handler)); + | ^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(bool) -> impl Future {handler}` + | + ::: axum/src/handler/mod.rs:116:8 + | +116 | H: Handler, + | ------------- required by this bound in `axum::routing::get` +``` + +This error doesn't tell you _why_ your function doesn't implement +[`Handler`]. It's possible to improve the error with the [`debug_handler`] +proc-macro from the [axum-macros] crate. + +[axum-macros]: https://docs.rs/axum-macros +[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html + +```rust +pub mod handler { /* ... */ } +``` + +### Modules + +## Module `future` + +Handler future types. + +```rust +pub mod future { /* ... */ } +``` + +### Types + +#### Struct `IntoServiceFuture` + +The response future for [`IntoService`](super::IntoService). + +```rust +pub struct IntoServiceFuture { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<''_>) -> std::task::Poll<::Output> { /* ... */ } + ``` + +- **FutureExt** +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryFuture** + - ```rust + fn try_poll(self: Pin<&mut F>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **TryFutureExt** +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `LayeredFuture` + +The response future for [`Layered`](super::Layered). + +```rust +pub struct LayeredFuture { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: Pin<&mut Self>, cx: &mut Context<''_>) -> std::task::Poll<::Output> { /* ... */ } + ``` + +- **FutureExt** +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Types + +#### Struct `Layered` + +A [`Service`] created from a [`Handler`] by applying a Tower middleware. + +Created with [`Handler::layer`]. See that method for more details. + +```rust +pub struct Layered { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Handler** + - ```rust + fn call(self: Self, req: Request, state: S) -> ::Future { /* ... */ } + ``` + +- **HandlerWithoutStateExt** + - ```rust + fn into_service(self: Self) -> HandlerService { /* ... */ } + ``` + + - ```rust + fn into_make_service(self: Self) -> IntoMakeService> { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo, C> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Traits + +#### Trait `Handler` + +**Attributes:** + +- `Other("#[diagnostic::on_unimplemented(note =\n\"Consider using `#[axum::debug_handler]` to improve the error message\")]")` + +Trait for async functions that can be used to handle requests. + +You shouldn't need to depend on this trait directly. It is automatically +implemented to closures of the right types. + +See the [module docs](crate::handler) for more details. + +# Converting `Handler`s into [`Service`]s + +To convert `Handler`s into [`Service`]s you have to call either +[`HandlerWithoutStateExt::into_service`] or [`Handler::with_state`]: + +``` +use tower::Service; +use axum::{ + extract::{State, Request}, + body::Body, + handler::{HandlerWithoutStateExt, Handler}, +}; + +// this handler doesn't require any state +async fn one() {} +// so it can be converted to a service with `HandlerWithoutStateExt::into_service` +assert_service(one.into_service()); + +// this handler requires state +async fn two(_: State) {} +// so we have to provide it +let handler_with_state = two.with_state(String::new()); +// which gives us a `Service` +assert_service(handler_with_state); + +// helper to check that a value implements `Service` +fn assert_service(service: S) +where + S: Service, +{} +``` +## Debugging handler type errors + +For a function to be used as a handler it must implement the [`Handler`] trait. +axum provides blanket implementations for functions that: + +- Are `async fn`s. +- Take no more than 16 arguments that all implement `Send`. + - All except the last argument implement [`FromRequestParts`]. + - The last argument implements [`FromRequest`]. +- Returns something that implements [`IntoResponse`]. +- If a closure is used it must implement `Clone + Send` and be +`'static`. +- Returns a future that is `Send`. The most common way to accidentally make a +future `!Send` is to hold a `!Send` type across an await. + +Unfortunately Rust gives poor error messages if you try to use a function +that doesn't quite match what's required by [`Handler`]. + +You might get an error like this: + +```not_rust +error[E0277]: the trait bound `fn(bool) -> impl Future {handler}: Handler<_, _>` is not satisfied + --> src/main.rs:13:44 + | +13 | let app = Router::new().route("/", get(handler)); + | ^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(bool) -> impl Future {handler}` + | + ::: axum/src/handler/mod.rs:116:8 + | +116 | H: Handler, + | ------------- required by this bound in `axum::routing::get` +``` + +This error doesn't tell you _why_ your function doesn't implement +[`Handler`]. It's possible to improve the error with the [`debug_handler`] +proc-macro from the [axum-macros] crate. + +[axum-macros]: https://docs.rs/axum-macros +[`debug_handler`]: https://docs.rs/axum-macros/latest/axum_macros/attr.debug_handler.html + +# Handlers that aren't functions + +The `Handler` trait is also implemented for `T: IntoResponse`. That allows easily returning +fixed data for routes: + +``` +use axum::{ + Router, + routing::{get, post}, + Json, + http::StatusCode, +}; +use serde_json::json; + +let app = Router::new() + // respond with a fixed string + .route("/", get("Hello, World!")) + // or return some mock data + .route("/users", post(( + StatusCode::CREATED, + Json(json!({ "id": 1, "username": "alice" })), + ))); +# let _: Router = app; +``` + +# About type parameter `T` + +**Generally you shouldn't need to worry about `T`**; when calling methods such as +[`post`](crate::routing::method_routing::post) it will be automatically inferred and this is +the intended way for this parameter to be provided in application code. + +If you are implementing your own methods that accept implementations of `Handler` as +arguments, then the following may be useful: + +The type parameter `T` is a workaround for trait coherence rules, allowing us to +write blanket implementations of `Handler` over many types of handler functions +with different numbers of arguments, without the compiler forbidding us from doing +so because one type `F` can in theory implement both `Fn(A) -> X` and `Fn(A, B) -> Y`. +`T` is a placeholder taking on a representation of the parameters of the handler function, +as well as other similar 'coherence rule workaround' discriminators, +allowing us to select one function signature to use as a `Handler`. + +```rust +pub trait Handler: Clone + Send + Sync + Sized + ''static { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Future`: The type of future calling this handler returns. + +###### Required Methods + +- `call`: Call the handler with the given request. + +##### Provided Methods + +- ```rust + fn layer(self: Self, layer: L) -> Layered +where + L: Layer> + Clone, + ::Service: Service { /* ... */ } + ``` + Apply a [`tower::Layer`] to the handler. + +- ```rust + fn with_state(self: Self, state: S) -> HandlerService { /* ... */ } + ``` + Convert the handler into a [`Service`] by providing the state + +##### Implementations + +This trait is implemented for the following types: + +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `F` with +- `Layered` with +- `MethodRouter` with + +#### Trait `HandlerWithoutStateExt` + +Extension trait for [`Handler`]s that don't have state. + +This provides convenience methods to convert the [`Handler`] into a [`Service`] or [`MakeService`]. + +[`MakeService`]: tower::make::MakeService + +```rust +pub trait HandlerWithoutStateExt: Handler { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `into_service`: Convert the handler into a [`Service`] and no state. +- `into_make_service`: Convert the handler into a [`MakeService`] and no state. +- `into_make_service_with_connect_info`: Convert the handler into a [`MakeService`] which stores information + +##### Implementations + +This trait is implemented for the following types: + +- `H` with + +### Re-exports + +#### Re-export `HandlerService` + +```rust +pub use self::service::HandlerService; +``` + +## Module `middleware` + +Utilities for writing middleware + +# Intro + +axum is unique in that it doesn't have its own bespoke middleware system and +instead integrates with [`tower`]. This means the ecosystem of [`tower`] and +[`tower-http`] middleware all work with axum. + +While it's not necessary to fully understand tower to write or use middleware +with axum, having at least a basic understanding of tower's concepts is +recommended. See [tower's guides][tower-guides] for a general introduction. +Reading the documentation for [`tower::ServiceBuilder`] is also recommended. + +# Applying middleware + +axum allows you to add middleware just about anywhere + +- To entire routers with [`Router::layer`] and [`Router::route_layer`]. +- To method routers with [`MethodRouter::layer`] and [`MethodRouter::route_layer`]. +- To individual handlers with [`Handler::layer`]. + +## Applying multiple middleware + +It's recommended to use [`tower::ServiceBuilder`] to apply multiple middleware at +once, instead of calling `layer` (or `route_layer`) repeatedly: + +```rust +use axum::{ + routing::get, + Extension, + Router, +}; +use tower_http::{trace::TraceLayer}; +use tower::ServiceBuilder; + +async fn handler() {} + +#[derive(Clone)] +struct State {} + +let app = Router::new() + .route("/", get(handler)) + .layer( + ServiceBuilder::new() + .layer(TraceLayer::new_for_http()) + .layer(Extension(State {})) + ); +# let _: Router = app; +``` + +# Commonly used middleware + +Some commonly used middleware are: + +- [`TraceLayer`](tower_http::trace) for high level tracing/logging. +- [`CorsLayer`](tower_http::cors) for handling CORS. +- [`CompressionLayer`](tower_http::compression) for automatic compression of responses. +- [`RequestIdLayer`](tower_http::request_id) and + [`PropagateRequestIdLayer`](tower_http::request_id) set and propagate request + ids. +- [`TimeoutLayer`](tower_http::timeout::TimeoutLayer) for timeouts. + +# Ordering + +When you add middleware with [`Router::layer`] (or similar) all previously added +routes will be wrapped in the middleware. Generally speaking, this results in +middleware being executed from bottom to top. + +So if you do this: + +```rust +use axum::{routing::get, Router}; + +async fn handler() {} + +# let layer_one = axum::Extension(()); +# let layer_two = axum::Extension(()); +# let layer_three = axum::Extension(()); +# +let app = Router::new() + .route("/", get(handler)) + .layer(layer_one) + .layer(layer_two) + .layer(layer_three); +# let _: Router = app; +``` + +Think of the middleware as being layered like an onion where each new layer +wraps all previous layers: + +```not_rust + requests + | + v ++----- layer_three -----+ +| +---- layer_two ----+ | +| | +-- layer_one --+ | | +| | | | | | +| | | handler | | | +| | | | | | +| | +-- layer_one --+ | | +| +---- layer_two ----+ | ++----- layer_three -----+ + | + v + responses +``` + +That is: + +- First `layer_three` receives the request +- It then does its thing and passes the request onto `layer_two` +- Which passes the request onto `layer_one` +- Which passes the request onto `handler` where a response is produced +- That response is then passed to `layer_one` +- Then to `layer_two` +- And finally to `layer_three` where it's returned out of your app + +It's a little more complicated in practice because any middleware is free to +return early and not call the next layer, for example if a request cannot be +authorized, but it's a useful mental model to have. + +As previously mentioned it's recommended to add multiple middleware using +`tower::ServiceBuilder`, however this impacts ordering: + +```rust +use tower::ServiceBuilder; +use axum::{routing::get, Router}; + +async fn handler() {} + +# let layer_one = axum::Extension(()); +# let layer_two = axum::Extension(()); +# let layer_three = axum::Extension(()); +# +let app = Router::new() + .route("/", get(handler)) + .layer( + ServiceBuilder::new() + .layer(layer_one) + .layer(layer_two) + .layer(layer_three), + ); +# let _: Router = app; +``` + +`ServiceBuilder` works by composing all layers into one such that they run top +to bottom. So with the previous code `layer_one` would receive the request +first, then `layer_two`, then `layer_three`, then `handler`, and then the +response would bubble back up through `layer_three`, then `layer_two`, and +finally `layer_one`. + +Executing middleware top to bottom is generally easier to understand and follow +mentally which is one of the reasons `ServiceBuilder` is recommended. + +# Writing middleware + +axum offers many ways of writing middleware, at different levels of abstraction +and with different pros and cons. + +## `axum::middleware::from_fn` + +Use [`axum::middleware::from_fn`] to write your middleware when: + +- You're not comfortable with implementing your own futures and would rather use + the familiar `async`/`await` syntax. +- You don't intend to publish your middleware as a crate for others to use. + Middleware written like this are only compatible with axum. + +## `axum::middleware::from_extractor` + +Use [`axum::middleware::from_extractor`] to write your middleware when: + +- You have a type that you sometimes want to use as an extractor and sometimes + as a middleware. If you only need your type as a middleware prefer + [`middleware::from_fn`]. + +## tower's combinators + +tower has several utility combinators that can be used to perform simple +modifications to requests or responses. The most commonly used ones are + +- [`ServiceBuilder::map_request`] +- [`ServiceBuilder::map_response`] +- [`ServiceBuilder::then`] +- [`ServiceBuilder::and_then`] + +You should use these when + +- You want to perform a small ad hoc operation, such as adding a header. +- You don't intend to publish your middleware as a crate for others to use. + +## `tower::Service` and `Pin>` + +For maximum control (and a more low level API) you can write your own middleware +by implementing [`tower::Service`]: + +Use [`tower::Service`] with `Pin>` to write your middleware when: + +- Your middleware needs to be configurable for example via builder methods on + your [`tower::Layer`] such as [`tower_http::trace::TraceLayer`]. +- You do intend to publish your middleware as a crate for others to use. +- You're not comfortable with implementing your own futures. + +A decent template for such a middleware could be: + +```rust +use axum::{ + response::Response, + body::Body, + extract::Request, +}; +use futures_util::future::BoxFuture; +use tower::{Service, Layer}; +use std::task::{Context, Poll}; + +#[derive(Clone)] +struct MyLayer; + +impl Layer for MyLayer { + type Service = MyMiddleware; + + fn layer(&self, inner: S) -> Self::Service { + MyMiddleware { inner } + } +} + +#[derive(Clone)] +struct MyMiddleware { + inner: S, +} + +impl Service for MyMiddleware +where + S: Service + Send + 'static, + S::Future: Send + 'static, +{ + type Response = S::Response; + type Error = S::Error; + // `BoxFuture` is a type alias for `Pin>` + type Future = BoxFuture<'static, Result>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, request: Request) -> Self::Future { + let future = self.inner.call(request); + Box::pin(async move { + let response: Response = future.await?; + Ok(response) + }) + } +} +``` + +Note that your error type being defined as `S::Error` means that your middleware typically _returns no errors_. As a principle always try to return a response and try not to bail out with a custom error type. For example, if a 3rd party library you are using inside your new middleware returns its own specialized error type, try to convert it to some reasonable response and return `Ok` with that response. + +If you choose to implement a custom error type such as `type Error = BoxError` (a boxed opaque error), or any other error type that is not `Infallible`, you must use a `HandleErrorLayer`, here is an example using a `ServiceBuilder`: + +```ignore +ServiceBuilder::new() + .layer(HandleErrorLayer::new(|_: BoxError| async { + // because axum uses infallible errors, you must handle your custom error type from your middleware here + StatusCode::BAD_REQUEST + })) + .layer( + // + ); +``` + +## `tower::Service` and custom futures + +If you're comfortable implementing your own futures (or want to learn it) and +need as much control as possible then using `tower::Service` without boxed +futures is the way to go. + +Use [`tower::Service`] with manual futures to write your middleware when: + +- You want your middleware to have the lowest possible overhead. +- Your middleware needs to be configurable for example via builder methods on + your [`tower::Layer`] such as [`tower_http::trace::TraceLayer`]. +- You do intend to publish your middleware as a crate for others to use, perhaps + as part of tower-http. +- You're comfortable with implementing your own futures, or want to learn how + the lower levels of async Rust works. + +tower's ["Building a middleware from scratch"][tower-from-scratch-guide] +guide is a good place to learn how to do this. + +# Error handling for middleware + +axum's error handling model requires handlers to always return a response. +However middleware is one possible way to introduce errors into an application. +If hyper receives an error the connection will be closed without sending a +response. Thus axum requires those errors to be handled gracefully: + +```rust +use axum::{ + routing::get, + error_handling::HandleErrorLayer, + http::StatusCode, + BoxError, + Router, +}; +use tower::{ServiceBuilder, timeout::TimeoutLayer}; +use std::time::Duration; + +async fn handler() {} + +let app = Router::new() + .route("/", get(handler)) + .layer( + ServiceBuilder::new() + // this middleware goes above `TimeoutLayer` because it will receive + // errors returned by `TimeoutLayer` + .layer(HandleErrorLayer::new(|_: BoxError| async { + StatusCode::REQUEST_TIMEOUT + })) + .layer(TimeoutLayer::new(Duration::from_secs(10))) + ); +# let _: Router = app; +``` + +See [`error_handling`](crate::error_handling) for more details on axum's error +handling model. + +# Routing to services/middleware and backpressure + +Generally routing to one of multiple services and backpressure doesn't mix +well. Ideally you would want ensure a service is ready to receive a request +before calling it. However, in order to know which service to call, you need +the request... + +One approach is to not consider the router service itself ready until all +destination services are ready. That is the approach used by +[`tower::steer::Steer`]. + +Another approach is to always consider all services ready (always return +`Poll::Ready(Ok(()))`) from `Service::poll_ready` and then actually drive +readiness inside the response future returned by `Service::call`. This works +well when your services don't care about backpressure and are always ready +anyway. + +axum expects that all services used in your app won't care about +backpressure and so it uses the latter strategy. However that means you +should avoid routing to a service (or using a middleware) that _does_ care +about backpressure. At the very least you should [load shed][tower::load_shed] +so requests are dropped quickly and don't keep piling up. + +It also means that if `poll_ready` returns an error then that error will be +returned in the response future from `call` and _not_ from `poll_ready`. In +that case, the underlying service will _not_ be discarded and will continue +to be used for future requests. Services that expect to be discarded if +`poll_ready` fails should _not_ be used with axum. + +One possible approach is to only apply backpressure sensitive middleware +around your entire app. This is possible because axum applications are +themselves services: + +```rust +use axum::{ + routing::get, + Router, +}; +use tower::ServiceBuilder; +# let some_backpressure_sensitive_middleware = +# tower::layer::util::Identity::new(); + +async fn handler() { /* ... */ } + +let app = Router::new().route("/", get(handler)); + +let app = ServiceBuilder::new() + .layer(some_backpressure_sensitive_middleware) + .service(app); +# let _: Router = app; +``` + +However when applying middleware around your whole application in this way +you have to take care that errors are still being handled appropriately. + +Also note that handlers created from async functions don't care about +backpressure and are always ready. So if you're not using any Tower +middleware you don't have to worry about any of this. + +# Accessing state in middleware + +How to make state available to middleware depends on how the middleware is +written. + +## Accessing state in `axum::middleware::from_fn` + +Use [`axum::middleware::from_fn_with_state`](crate::middleware::from_fn_with_state). + +## Accessing state in custom `tower::Layer`s + +```rust +use axum::{ + Router, + routing::get, + middleware::{self, Next}, + response::Response, + extract::{State, Request}, +}; +use tower::{Layer, Service}; +use std::task::{Context, Poll}; + +#[derive(Clone)] +struct AppState {} + +#[derive(Clone)] +struct MyLayer { + state: AppState, +} + +impl Layer for MyLayer { + type Service = MyService; + + fn layer(&self, inner: S) -> Self::Service { + MyService { + inner, + state: self.state.clone(), + } + } +} + +#[derive(Clone)] +struct MyService { + inner: S, + state: AppState, +} + +impl Service> for MyService +where + S: Service>, +{ + type Response = S::Response; + type Error = S::Error; + type Future = S::Future; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, req: Request) -> Self::Future { + // Do something with `self.state`. + // + // See `axum::RequestExt` for how to run extractors directly from + // a `Request`. + + self.inner.call(req) + } +} + +async fn handler(_: State) {} + +let state = AppState {}; + +let app = Router::new() + .route("/", get(handler)) + .layer(MyLayer { state: state.clone() }) + .with_state(state); +# let _: axum::Router = app; +``` + +# Passing state from middleware to handlers + +State can be passed from middleware to handlers using [request extensions]: + +```rust +use axum::{ + Router, + http::StatusCode, + routing::get, + response::{IntoResponse, Response}, + middleware::{self, Next}, + extract::{Request, Extension}, +}; + +#[derive(Clone)] +struct CurrentUser { /* ... */ } + +async fn auth(mut req: Request, next: Next) -> Result { + let auth_header = req.headers() + .get(http::header::AUTHORIZATION) + .and_then(|header| header.to_str().ok()); + + let auth_header = if let Some(auth_header) = auth_header { + auth_header + } else { + return Err(StatusCode::UNAUTHORIZED); + }; + + if let Some(current_user) = authorize_current_user(auth_header).await { + // insert the current user into a request extension so the handler can + // extract it + req.extensions_mut().insert(current_user); + Ok(next.run(req).await) + } else { + Err(StatusCode::UNAUTHORIZED) + } +} + +async fn authorize_current_user(auth_token: &str) -> Option { + // ... + # unimplemented!() +} + +async fn handler( + // extract the current user, set by the middleware + Extension(current_user): Extension, +) { + // ... +} + +let app = Router::new() + .route("/", get(handler)) + .route_layer(middleware::from_fn(auth)); +# let _: Router = app; +``` + +[Response extensions] can also be used but note that request extensions are not +automatically moved to response extensions. You need to manually do that for the +extensions you need. + +# Rewriting request URI in middleware + +Middleware added with [`Router::layer`] will run after routing. That means it +cannot be used to run middleware that rewrites the request URI. By the time the +middleware runs the routing is already done. + +The workaround is to wrap the middleware around the entire `Router` (this works +because `Router` implements [`Service`]): + +```rust +use tower::Layer; +use axum::{ + Router, + ServiceExt, // for `into_make_service` + response::Response, + middleware::Next, + extract::Request, +}; + +fn rewrite_request_uri(req: Request) -> Request { + // ... + # req +} + +// this can be any `tower::Layer` +let middleware = tower::util::MapRequestLayer::new(rewrite_request_uri); + +let app = Router::new(); + +// apply the layer around the whole `Router` +// this way the middleware will run before `Router` receives the request +let app_with_middleware = middleware.layer(app); + +# async { +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app_with_middleware.into_make_service()).await.unwrap(); +# }; +``` + +[`tower`]: https://crates.io/crates/tower +[`tower-http`]: https://crates.io/crates/tower-http +[tower-guides]: https://github.com/tower-rs/tower/tree/master/guides +[`axum::middleware::from_fn`]: fn@crate::middleware::from_fn +[`middleware::from_fn`]: fn@crate::middleware::from_fn +[tower-from-scratch-guide]: https://github.com/tower-rs/tower/blob/master/guides/building-a-middleware-from-scratch.md +[`ServiceBuilder::map_request`]: tower::ServiceBuilder::map_request +[`ServiceBuilder::map_response`]: tower::ServiceBuilder::map_response +[`ServiceBuilder::then`]: tower::ServiceBuilder::then +[`ServiceBuilder::and_then`]: tower::ServiceBuilder::and_then +[`axum::middleware::from_extractor`]: fn@crate::middleware::from_extractor +[`Handler::layer`]: crate::handler::Handler::layer +[`Router::layer`]: crate::routing::Router::layer +[`MethodRouter::layer`]: crate::routing::MethodRouter::layer +[`Router::route_layer`]: crate::routing::Router::route_layer +[`MethodRouter::route_layer`]: crate::routing::MethodRouter::route_layer +[request extensions]: https://docs.rs/http/latest/http/request/struct.Request.html#method.extensions +[Response extensions]: https://docs.rs/http/latest/http/response/struct.Response.html#method.extensions +[`State`]: crate::extract::State +[`Service`]: tower::Service + +```rust +pub mod middleware { /* ... */ } +``` + +### Modules + +## Module `future` + +Future types. + +```rust +pub mod future { /* ... */ } +``` + +### Re-exports + +#### Re-export `ResponseFuture` + +```rust +pub use super::from_extractor::ResponseFuture as FromExtractorResponseFuture; +``` + +#### Re-export `ResponseFuture` + +```rust +pub use super::from_fn::ResponseFuture as FromFnResponseFuture; +``` + +#### Re-export `ResponseFuture` + +```rust +pub use super::map_request::ResponseFuture as MapRequestResponseFuture; +``` + +#### Re-export `ResponseFuture` + +```rust +pub use super::map_response::ResponseFuture as MapResponseResponseFuture; +``` + +### Re-exports + +#### Re-export `from_extractor` + +```rust +pub use self::from_extractor::from_extractor; +``` + +#### Re-export `from_extractor_with_state` + +```rust +pub use self::from_extractor::from_extractor_with_state; +``` + +#### Re-export `FromExtractor` + +```rust +pub use self::from_extractor::FromExtractor; +``` + +#### Re-export `FromExtractorLayer` + +```rust +pub use self::from_extractor::FromExtractorLayer; +``` + +#### Re-export `from_fn` + +```rust +pub use self::from_fn::from_fn; +``` + +#### Re-export `from_fn_with_state` + +```rust +pub use self::from_fn::from_fn_with_state; +``` + +#### Re-export `FromFn` + +```rust +pub use self::from_fn::FromFn; +``` + +#### Re-export `FromFnLayer` + +```rust +pub use self::from_fn::FromFnLayer; +``` + +#### Re-export `Next` + +```rust +pub use self::from_fn::Next; +``` + +#### Re-export `map_request` + +```rust +pub use self::map_request::map_request; +``` + +#### Re-export `map_request_with_state` + +```rust +pub use self::map_request::map_request_with_state; +``` + +#### Re-export `IntoMapRequestResult` + +```rust +pub use self::map_request::IntoMapRequestResult; +``` + +#### Re-export `MapRequest` + +```rust +pub use self::map_request::MapRequest; +``` + +#### Re-export `MapRequestLayer` + +```rust +pub use self::map_request::MapRequestLayer; +``` + +#### Re-export `map_response` + +```rust +pub use self::map_response::map_response; +``` + +#### Re-export `map_response_with_state` + +```rust +pub use self::map_response::map_response_with_state; +``` + +#### Re-export `MapResponse` + +```rust +pub use self::map_response::MapResponse; +``` + +#### Re-export `MapResponseLayer` + +```rust +pub use self::map_response::MapResponseLayer; +``` + +#### Re-export `ResponseAxumBody` + +```rust +pub use self::response_axum_body::ResponseAxumBody; +``` + +#### Re-export `ResponseAxumBodyFuture` + +```rust +pub use self::response_axum_body::ResponseAxumBodyFuture; +``` + +#### Re-export `ResponseAxumBodyLayer` + +```rust +pub use self::response_axum_body::ResponseAxumBodyLayer; +``` + +#### Re-export `AddExtension` + +```rust +pub use crate::extension::AddExtension; +``` + +## Module `response` + +Types and traits for generating responses. + +# Building responses + +Anything that implements [`IntoResponse`] can be returned from a handler. axum +provides implementations for common types: + +```rust,no_run +use axum::{ + Json, + response::{Html, IntoResponse}, + http::{StatusCode, Uri, header::{self, HeaderMap, HeaderName}}, +}; + +// `()` gives an empty response +async fn empty() {} + +// String will get a `text/plain; charset=utf-8` content-type +async fn plain_text(uri: Uri) -> String { + format!("Hi from {}", uri.path()) +} + +// Bytes will get a `application/octet-stream` content-type +async fn bytes() -> Vec { + vec![1, 2, 3, 4] +} + +// `Json` will get a `application/json` content-type and work with anything that +// implements `serde::Serialize` +async fn json() -> Json> { + Json(vec!["foo".to_owned(), "bar".to_owned()]) +} + +// `Html` will get a `text/html` content-type +async fn html() -> Html<&'static str> { + Html("

Hello, World!

") +} + +// `StatusCode` gives an empty response with that status code +async fn status() -> StatusCode { + StatusCode::NOT_FOUND +} + +// `HeaderMap` gives an empty response with some headers +async fn headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(header::SERVER, "axum".parse().unwrap()); + headers +} + +// An array of tuples also gives headers +async fn array_headers() -> [(HeaderName, &'static str); 2] { + [ + (header::SERVER, "axum"), + (header::CONTENT_TYPE, "text/plain") + ] +} + +// Use `impl IntoResponse` to avoid writing the whole type +async fn impl_trait() -> impl IntoResponse { + [ + (header::SERVER, "axum"), + (header::CONTENT_TYPE, "text/plain") + ] +} +``` + +Additionally you can return tuples to build more complex responses from +individual parts. + +```rust,no_run +use axum::{ + Json, + response::IntoResponse, + http::{StatusCode, HeaderMap, Uri, header}, + extract::Extension, +}; + +// `(StatusCode, impl IntoResponse)` will override the status code of the response +async fn with_status(uri: Uri) -> (StatusCode, String) { + (StatusCode::NOT_FOUND, format!("Not Found: {}", uri.path())) +} + +// Use `impl IntoResponse` to avoid having to type the whole type +async fn impl_trait(uri: Uri) -> impl IntoResponse { + (StatusCode::NOT_FOUND, format!("Not Found: {}", uri.path())) +} + +// `(HeaderMap, impl IntoResponse)` to add additional headers +async fn with_headers() -> impl IntoResponse { + let mut headers = HeaderMap::new(); + headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap()); + (headers, "foo") +} + +// Or an array of tuples to more easily build the headers +async fn with_array_headers() -> impl IntoResponse { + ([(header::CONTENT_TYPE, "text/plain")], "foo") +} + +// Use string keys for custom headers +async fn with_array_headers_custom() -> impl IntoResponse { + ([("x-custom", "custom")], "foo") +} + +// `(StatusCode, headers, impl IntoResponse)` to set status and add headers +// `headers` can be either a `HeaderMap` or an array of tuples +async fn with_status_and_array_headers() -> impl IntoResponse { + ( + StatusCode::NOT_FOUND, + [(header::CONTENT_TYPE, "text/plain")], + "foo", + ) +} + +// `(Extension<_>, impl IntoResponse)` to set response extensions +async fn with_status_extensions() -> impl IntoResponse { + ( + Extension(Foo("foo")), + "foo", + ) +} + +#[derive(Clone)] +struct Foo(&'static str); + +// Or mix and match all the things +async fn all_the_things(uri: Uri) -> impl IntoResponse { + let mut header_map = HeaderMap::new(); + if uri.path() == "/" { + header_map.insert(header::SERVER, "axum".parse().unwrap()); + } + + ( + // set status code + StatusCode::NOT_FOUND, + // headers with an array + [("x-custom", "custom")], + // some extensions + Extension(Foo("foo")), + Extension(Foo("bar")), + // more headers, built dynamically + header_map, + // and finally the body + "foo", + ) +} +``` + +In general you can return tuples like: + +- `(StatusCode, impl IntoResponse)` +- `(Parts, impl IntoResponse)` +- `(Response<()>, impl IntoResponse)` +- `(T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`]. +- `(StatusCode, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`]. +- `(Parts, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`]. +- `(Response<()>, T1, .., Tn, impl IntoResponse)` where `T1` to `Tn` all implement [`IntoResponseParts`]. + +This means you cannot accidentally override the status or body as [`IntoResponseParts`] only allows +setting headers and extensions. + +Use [`Response`] for more low level control: + +```rust,no_run +use axum::{ + Json, + response::{IntoResponse, Response}, + body::Body, + http::StatusCode, +}; + +async fn response() -> Response { + Response::builder() + .status(StatusCode::NOT_FOUND) + .header("x-foo", "custom header") + .body(Body::from("not found")) + .unwrap() +} +``` + +# Returning different response types + +If you need to return multiple response types, and `Result` isn't appropriate, you can call +`.into_response()` to turn things into `axum::response::Response`: + +```rust +use axum::{ + response::{IntoResponse, Redirect, Response}, + http::StatusCode, +}; + +async fn handle() -> Response { + if something() { + "All good!".into_response() + } else if something_else() { + ( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong...", + ).into_response() + } else { + Redirect::to("/").into_response() + } +} + +fn something() -> bool { + // ... + # true +} + +fn something_else() -> bool { + // ... + # true +} +``` + +# Regarding `impl IntoResponse` + +You can use `impl IntoResponse` as the return type from handlers to avoid +typing large types. For example + +```rust +use axum::http::StatusCode; + +async fn handler() -> (StatusCode, [(&'static str, &'static str); 1], &'static str) { + (StatusCode::OK, [("x-foo", "bar")], "Hello, World!") +} +``` + +Becomes easier using `impl IntoResponse`: + +```rust +use axum::{http::StatusCode, response::IntoResponse}; + +async fn impl_into_response() -> impl IntoResponse { + (StatusCode::OK, [("x-foo", "bar")], "Hello, World!") +} +``` + +However `impl IntoResponse` has a few limitations. Firstly it can only be used +to return a single type: + +```rust,compile_fail +use axum::{http::StatusCode, response::IntoResponse}; + +async fn handler() -> impl IntoResponse { + if check_something() { + StatusCode::NOT_FOUND + } else { + "Hello, World!" + } +} + +fn check_something() -> bool { + # false + // ... +} +``` + +This function returns either a `StatusCode` or a `&'static str` which `impl +Trait` doesn't allow. + +Secondly `impl IntoResponse` can lead to type inference issues when used with +`Result` and `?`: + +```rust,compile_fail +use axum::{http::StatusCode, response::IntoResponse}; + +async fn handler() -> impl IntoResponse { + create_thing()?; + Ok(StatusCode::CREATED) +} + +fn create_thing() -> Result<(), StatusCode> { + # Ok(()) + // ... +} +``` + +This is because `?` supports using the [`From`] trait to convert to a different +error type but it doesn't know which type to convert to, because we only +specified `impl IntoResponse` as the return type. + +`Result` doesn't always work either: + +```rust,compile_fail +use axum::{http::StatusCode, response::IntoResponse}; + +async fn handler() -> Result { + create_thing()?; + Ok(StatusCode::CREATED) +} + +fn create_thing() -> Result<(), StatusCode> { + # Ok(()) + // ... +} +``` + +The solution is to use a concrete error type, such as `Result`: + +```rust +use axum::{http::StatusCode, response::IntoResponse}; + +async fn handler() -> Result { + create_thing()?; + Ok(StatusCode::CREATED) +} + +fn create_thing() -> Result<(), StatusCode> { + # Ok(()) + // ... +} +``` + +Because of this it is generally not recommended to use `impl IntoResponse` +unless you're familiar with the details of how `impl Trait` works. + +[`IntoResponse`]: crate::response::IntoResponse +[`IntoResponseParts`]: crate::response::IntoResponseParts +[`StatusCode`]: http::StatusCode + +```rust +pub mod response { /* ... */ } +``` + +### Modules + +## Module `sse` + +Server-Sent Events (SSE) responses. + +# Example + +``` +use axum::{ + Router, + routing::get, + response::sse::{Event, KeepAlive, Sse}, +}; +use std::{time::Duration, convert::Infallible}; +use tokio_stream::StreamExt as _ ; +use futures_util::stream::{self, Stream}; + +let app = Router::new().route("/sse", get(sse_handler)); + +async fn sse_handler() -> Sse>> { + // A `Stream` that repeats an event every second + let stream = stream::repeat_with(|| Event::default().data("hi!")) + .map(Ok) + .throttle(Duration::from_secs(1)); + + Sse::new(stream).keep_alive(KeepAlive::default()) +} +# let _: Router = app; +``` + +```rust +pub mod sse { /* ... */ } +``` + +### Types + +#### Struct `Sse` + +**Attributes:** + +- `MustUse { reason: None }` + +An SSE response + +```rust +pub struct Sse { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(stream: S) -> Self +where + S: TryStream + Send + ''static, + ::Error: Into { /* ... */ } + ``` + Create a new [`Sse`] response that will respond with the given stream of + +- ```rust + pub fn keep_alive(self: Self, keep_alive: KeepAlive) -> Sse> { /* ... */ } + ``` + Configure the interval between keep-alive messages. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Sse { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **HandlerWithoutStateExt** + - ```rust + fn into_service(self: Self) -> HandlerService { /* ... */ } + ``` + + - ```rust + fn into_make_service(self: Self) -> IntoMakeService> { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo, C> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `Event` + +**Attributes:** + +- `MustUse { reason: None }` + +Server-sent event + +```rust +pub struct Event { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_data_writer(self: Self) -> EventDataWriter { /* ... */ } + ``` + Use this [`Event`] as a [`EventDataWriter`] to write custom data. + +- ```rust + pub fn data(self: Self, data: T) -> Self +where + T: AsRef { /* ... */ } + ``` + Set the event's data data field(s) (`data: `) + +- ```rust + pub fn json_data(self: Self, data: T) -> Result +where + T: serde_core::Serialize { /* ... */ } + ``` + Set the event's data field to a value serialized as unformatted JSON (`data: `). + +- ```rust + pub fn comment(self: Self, comment: T) -> Event +where + T: AsRef { /* ... */ } + ``` + Set the event's comment field (`:`). + +- ```rust + pub fn event(self: Self, event: T) -> Event +where + T: AsRef { /* ... */ } + ``` + Set the event's name field (`event:`). + +- ```rust + pub fn retry(self: Self, duration: Duration) -> Event { /* ... */ } + ``` + Set the event's retry timeout field (`retry: `). + +- ```rust + pub fn id(self: Self, id: T) -> Event +where + T: AsRef { /* ... */ } + ``` + Set the event's identifier field (`id:`). + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Event { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `EventDataWriter` + +**Attributes:** + +- `MustUse { reason: None }` + +Expose [`Event`] as a [`std::fmt::Write`] +such that any form of data can be written as data safely. + +This also ensures that newline characters `\r` and `\n` +correctly trigger a split with a new `data: ` prefix. + +# Panics + +Panics if any `data` has already been written prior to the first write +of this [`EventDataWriter`] instance. + +```rust +pub struct EventDataWriter { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_event(self: Self) -> Event { /* ... */ } + ``` + Consume the [`EventDataWriter`] and return the [`Event`] once again. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +- **Write** + - ```rust + fn write_str(self: &mut Self, s: &str) -> fmt::Result { /* ... */ } + ``` + +#### Struct `KeepAlive` + +**Attributes:** + +- `MustUse { reason: None }` + +Configure the interval between keep-alive messages, the content +of each message, and the associated stream. + +```rust +pub struct KeepAlive { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Create a new `KeepAlive`. + +- ```rust + pub fn interval(self: Self, time: Duration) -> Self { /* ... */ } + ``` + Customize the interval between keep-alive messages. + +- ```rust + pub fn text(self: Self, text: I) -> Self +where + I: AsRef { /* ... */ } + ``` + Customize the text of the keep-alive message. + +- ```rust + pub fn event(self: Self, event: Event) -> Self { /* ... */ } + ``` + Customize the event of the keep-alive message. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> KeepAlive { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `KeepAliveStream` + +A wrapper around a stream that produces keep-alive events + +```rust +pub struct KeepAliveStream { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Stream** + - ```rust + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll::Item>> { /* ... */ } + ``` + +- **StreamExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **TryStream** + - ```rust + fn try_poll_next(self: Pin<&mut S>, cx: &mut Context<''_>) -> Poll::Ok, ::Error>>> { /* ... */ } + ``` + +- **TryStreamExt** +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Types + +#### Struct `Html` + +**Attributes:** + +- `MustUse { reason: None }` + +An HTML response. + +Will automatically get `Content-Type: text/html`. + +```rust +pub struct Html(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Html { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(t: never) -> T { /* ... */ } + ``` + + - ```rust + fn from(inner: T) -> Self { /* ... */ } + ``` + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **HandlerWithoutStateExt** + - ```rust + fn into_service(self: Self) -> HandlerService { /* ... */ } + ``` + + - ```rust + fn into_make_service(self: Self) -> IntoMakeService> { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo, C> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `NoContent` + +An empty response with 204 No Content status. + +Due to historical and implementation reasons, the `IntoResponse` implementation of `()` +(unit type) returns an empty response with 200 [`StatusCode::OK`] status. +If you specifically want a 204 [`StatusCode::NO_CONTENT`] status, you can use either `StatusCode` type +directly, or this shortcut struct for self-documentation. + +``` +use axum::{extract::Path, response::NoContent}; + +async fn delete_user(Path(user): Path) -> Result { + // ...access database... +# drop(user); + Ok(NoContent) +} +``` + +```rust +pub struct NoContent; +``` + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> NoContent { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **HandlerWithoutStateExt** + - ```rust + fn into_service(self: Self) -> HandlerService { /* ... */ } + ``` + + - ```rust + fn into_make_service(self: Self) -> IntoMakeService> { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo, C> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoResponse** + - ```rust + fn into_response(self: Self) -> Response { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Re-exports + +#### Re-export `Json` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` +- `Other("#[(feature = \"json\")]")` + +```rust +pub use crate::Json; +``` + +#### Re-export `Form` + +**Attributes:** + +- `Other("#[(feature = \"form\")]")` +- `Other("#[doc(no_inline)]")` + +```rust +pub use crate::form::Form; +``` + +#### Re-export `Extension` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use crate::Extension; +``` + +#### Re-export `AppendHeaders` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::AppendHeaders; +``` + +#### Re-export `ErrorResponse` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::ErrorResponse; +``` + +#### Re-export `IntoResponse` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::IntoResponse; +``` + +#### Re-export `IntoResponseParts` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::IntoResponseParts; +``` + +#### Re-export `Response` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::Response; +``` + +#### Re-export `ResponseParts` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::ResponseParts; +``` + +#### Re-export `Result` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::response::Result; +``` + +#### Re-export `Redirect` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::redirect::Redirect; +``` + +#### Re-export `Sse` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use sse::Sse; +``` + +## Module `routing` + +Routing between [`Service`]s and handlers. + +```rust +pub mod routing { /* ... */ } +``` + +### Modules + +## Module `future` + +Future types. + +```rust +pub mod future { /* ... */ } +``` + +### Re-exports + +#### Re-export `IntoMakeServiceFuture` + +```rust +pub use super::into_make_service::IntoMakeServiceFuture; +``` + +#### Re-export `InfallibleRouteFuture` + +```rust +pub use super::route::InfallibleRouteFuture; +``` + +#### Re-export `RouteFuture` + +```rust +pub use super::route::RouteFuture; +``` + +## Module `method_routing` + +Route to services and handlers based on HTTP methods. + +```rust +pub mod method_routing { /* ... */ } +``` + +### Types + +#### Struct `MethodRouter` + +**Attributes:** + +- `MustUse { reason: None }` + +A [`Service`] that accepts requests based on a [`MethodFilter`] and +allows chaining additional handlers and services. + +# When does `MethodRouter` implement [`Service`]? + +Whether or not `MethodRouter` implements [`Service`] depends on the state type it requires. + +``` +use tower::Service; +use axum::{routing::get, extract::{State, Request}, body::Body}; + +// this `MethodRouter` doesn't require any state, i.e. the state is `()`, +let method_router = get(|| async {}); +// and thus it implements `Service` +assert_service(method_router); + +// this requires a `String` and doesn't implement `Service` +let method_router = get(|_: State| async {}); +// until you provide the `String` with `.with_state(...)` +let method_router_with_state = method_router.with_state(String::new()); +// and then it implements `Service` +assert_service(method_router_with_state); + +// helper to check that a value implements `Service` +fn assert_service(service: S) +where + S: Service, +{} +``` + +```rust +pub struct MethodRouter { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn on(self: Self, filter: MethodFilter, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will accept requests matching the given + +- ```rust + pub fn connect(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `CONNECT` requests. + +- ```rust + pub fn delete(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `DELETE` requests. + +- ```rust + pub fn get(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `GET` requests. + +- ```rust + pub fn head(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `HEAD` requests. + +- ```rust + pub fn options(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `OPTIONS` requests. + +- ```rust + pub fn patch(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `PATCH` requests. + +- ```rust + pub fn post(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `POST` requests. + +- ```rust + pub fn put(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `PUT` requests. + +- ```rust + pub fn trace(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Chain an additional handler that will only accept `TRACE` requests. + +- ```rust + pub fn fallback(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static, + S: Send + Sync + ''static { /* ... */ } + ``` + Add a fallback [`Handler`] to the router. + +- ```rust + pub fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + Convert the router into a [`MakeService`]. + +- ```rust + pub fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + Convert the router into a [`MakeService`] which stores information + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Create a default `MethodRouter` that will respond with `405 Method Not Allowed` to all + +- ```rust + pub fn with_state(self: Self, state: S) -> MethodRouter { /* ... */ } + ``` + Provide the state for the router. + +- ```rust + pub fn on_service(self: Self, filter: MethodFilter, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will accept requests matching the given + +- ```rust + pub fn connect_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `CONNECT` requests. + +- ```rust + pub fn delete_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `DELETE` requests. + +- ```rust + pub fn get_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `GET` requests. + +- ```rust + pub fn head_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `HEAD` requests. + +- ```rust + pub fn options_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `OPTIONS` requests. + +- ```rust + pub fn patch_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `PATCH` requests. + +- ```rust + pub fn post_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `POST` requests. + +- ```rust + pub fn put_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `PUT` requests. + +- ```rust + pub fn trace_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Chain an additional service that will only accept `TRACE` requests. + +- ```rust + pub fn fallback_service(self: Self, svc: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static { /* ... */ } + ``` + Add a fallback service to the router. + +- ```rust + pub fn layer(self: Self, layer: L) -> MethodRouter +where + L: Layer> + Clone + Send + Sync + ''static, + ::Service: Service + Clone + Send + Sync + ''static, + <::Service as Service>::Response: IntoResponse + ''static, + <::Service as Service>::Error: Into + ''static, + <::Service as Service>::Future: Send + ''static, + E: ''static, + S: ''static, + NewError: ''static { /* ... */ } + ``` + Apply a [`tower::Layer`] to all routes in the router. + +- ```rust + pub fn route_layer(self: Self, layer: L) -> MethodRouter +where + L: Layer> + Clone + Send + Sync + ''static, + ::Service: Service + Clone + Send + Sync + ''static, + <::Service as Service>::Response: IntoResponse + ''static, + <::Service as Service>::Future: Send + ''static, + E: ''static, + S: ''static { /* ... */ } + ``` + Apply a [`tower::Layer`] to the router that will only run if the request matches + +- ```rust + pub fn merge(self: Self, other: MethodRouter) -> Self { /* ... */ } + ``` + Merge two routers into one. + +- ```rust + pub fn handle_error(self: Self, f: F) -> MethodRouter +where + F: Clone + Send + Sync + ''static, + HandleError, F, T>: Service, + , F, T> as Service>::Future: Send, + , F, T> as Service>::Response: IntoResponse + Send, + T: ''static, + E: ''static, + S: ''static { /* ... */ } + ``` + Apply a [`HandleErrorLayer`]. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Handler** + - ```rust + fn call(self: Self, req: Request, state: S) -> ::Future { /* ... */ } + ``` + +- **HandlerWithoutStateExt** + - ```rust + fn into_service(self: Self) -> HandlerService { /* ... */ } + ``` + + - ```rust + fn into_make_service(self: Self) -> IntoMakeService> { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo, C> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **MakeService** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll>::MakeError>> { /* ... */ } + ``` + + - ```rust + fn make_service(self: &mut Self, target: Target) -> >::Future { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, _req: serve::IncomingStream<''_, L>) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Functions + +#### Function `connect_service` + +Route `CONNECT` requests to the given service. + +See [`MethodFilter::CONNECT`] for when you'd want to use this, +and [`get_service`] for an example. + +```rust +pub fn connect_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `delete_service` + +Route `DELETE` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn delete_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `get_service` + +Route `GET` requests to the given service. + +# Example + +```rust +use axum::{ + extract::Request, + Router, + routing::get_service, + body::Body, +}; +use http::Response; +use std::convert::Infallible; + +let service = tower::service_fn(|request: Request| async { + Ok::<_, Infallible>(Response::new(Body::empty())) +}); + +// Requests to `GET /` will go to `service`. +let app = Router::new().route("/", get_service(service)); +# let _: Router = app; +``` + +Note that `get` routes will also be called for `HEAD` requests but will have +the response body removed. Make sure to add explicit `HEAD` routes +afterwards. + +```rust +pub fn get_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `head_service` + +Route `HEAD` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn head_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `options_service` + +Route `OPTIONS` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn options_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `patch_service` + +Route `PATCH` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn patch_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `post_service` + +Route `POST` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn post_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `put_service` + +Route `PUT` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn put_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `trace_service` + +Route `TRACE` requests to the given service. + + See [`get_service`] for an example. + +```rust +pub fn trace_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `on_service` + +Route requests with the given method to the service. + +# Example + +```rust +use axum::{ + extract::Request, + routing::on, + Router, + body::Body, + routing::{MethodFilter, on_service}, +}; +use http::Response; +use std::convert::Infallible; + +let service = tower::service_fn(|request: Request| async { + Ok::<_, Infallible>(Response::new(Body::empty())) +}); + +// Requests to `POST /` will go to `service`. +let app = Router::new().route("/", on_service(MethodFilter::POST, service)); +# let _: Router = app; +``` + +```rust +pub fn on_service(filter: crate::routing::MethodFilter, svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `any_service` + +Route requests to the given service regardless of its method. + +# Example + +```rust +use axum::{ + extract::Request, + Router, + routing::any_service, + body::Body, +}; +use http::Response; +use std::convert::Infallible; + +let service = tower::service_fn(|request: Request| async { + Ok::<_, Infallible>(Response::new(Body::empty())) +}); + +// All requests to `/` will go to `service`. +let app = Router::new().route("/", any_service(service)); +# let _: Router = app; +``` + +Additional methods can still be chained: + +```rust +use axum::{ + extract::Request, + Router, + routing::any_service, + body::Body, +}; +use http::Response; +use std::convert::Infallible; + +let service = tower::service_fn(|request: Request| async { + # Ok::<_, Infallible>(Response::new(Body::empty())) + // ... +}); + +let other_service = tower::service_fn(|request: Request| async { + # Ok::<_, Infallible>(Response::new(Body::empty())) + // ... +}); + +// `POST /` goes to `other_service`. All other requests go to `service` +let app = Router::new().route("/", any_service(service).post_service(other_service)); +# let _: Router = app; +``` + +```rust +pub fn any_service(svc: T) -> MethodRouter::Error> +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse + ''static, + ::Future: Send + ''static, + S: Clone { /* ... */ } +``` + +#### Function `connect` + +Route `CONNECT` requests to the given handler. + +See [`MethodFilter::CONNECT`] for when you'd want to use this, +and [`get`] for an example. + +```rust +pub fn connect(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `delete` + +Route `DELETE` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn delete(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `get` + +Route `GET` requests to the given handler. + +# Example + +```rust +use axum::{ + routing::get, + Router, +}; + +async fn handler() {} + +// Requests to `GET /` will go to `handler`. +let app = Router::new().route("/", get(handler)); +# let _: Router = app; +``` + +Note that `get` routes will also be called for `HEAD` requests but will have +the response body removed. Make sure to add explicit `HEAD` routes +afterwards. + +```rust +pub fn get(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `head` + +Route `HEAD` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn head(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `options` + +Route `OPTIONS` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn options(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `patch` + +Route `PATCH` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn patch(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `post` + +Route `POST` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn post(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `put` + +Route `PUT` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn put(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `trace` + +Route `TRACE` requests to the given handler. + + See [`get`] for an example. + +```rust +pub fn trace(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `on` + +Route requests with the given method to the handler. + +# Example + +```rust +use axum::{ + routing::on, + Router, + routing::MethodFilter, +}; + +async fn handler() {} + +// Requests to `POST /` will go to `handler`. +let app = Router::new().route("/", on(MethodFilter::POST, handler)); +# let _: Router = app; +``` + +```rust +pub fn on(filter: crate::routing::MethodFilter, handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +#### Function `any` + +Route requests with the given handler regardless of the method. + +# Example + +```rust +use axum::{ + routing::any, + Router, +}; + +async fn handler() {} + +// All requests to `/` will go to `handler`. +let app = Router::new().route("/", any(handler)); +# let _: Router = app; +``` + +Additional methods can still be chained: + +```rust +use axum::{ + routing::any, + Router, +}; + +async fn handler() {} + +async fn other_handler() {} + +// `POST /` goes to `other_handler`. All other requests go to `handler` +let app = Router::new().route("/", any(handler).post(other_handler)); +# let _: Router = app; +``` + +```rust +pub fn any(handler: H) -> MethodRouter +where + H: Handler, + T: ''static, + S: Clone + Send + Sync + ''static { /* ... */ } +``` + +### Types + +#### Struct `Router` + +**Attributes:** + +- `MustUse { reason: None }` + +The router type for composing handlers and services. + +`Router` means a router that is _missing_ a state of type `S` to be able +to handle requests. Thus, only `Router<()>` (i.e. without missing state) can +be passed to [`serve`]. See [`Router::with_state`] for more details. + +[`serve`]: crate::serve() + +```rust +pub struct Router { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Create a new `Router`. + +- ```rust + pub fn without_v07_checks(self: Self) -> Self { /* ... */ } + ``` + Turn off checks for compatibility with route matching syntax from 0.7. + +- ```rust + pub fn route(self: Self, path: &str, method_router: MethodRouter) -> Self { /* ... */ } + ``` + Add another route to the router. + +- ```rust + pub fn route_service(self: Self, path: &str, service: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse, + ::Future: Send + ''static { /* ... */ } + ``` + Add another route to the router that calls a [`Service`]. + +- ```rust + pub fn nest(self: Self, path: &str, router: Router) -> Self { /* ... */ } + ``` + Nest a [`Router`] at some path. + +- ```rust + pub fn nest_service(self: Self, path: &str, service: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse, + ::Future: Send + ''static { /* ... */ } + ``` + Like [`nest`](Self::nest), but accepts an arbitrary `Service`. + +- ```rust + pub fn merge(self: Self, other: R) -> Self +where + R: Into> { /* ... */ } + ``` + Merge the paths and fallbacks of two routers into a single [`Router`]. + +- ```rust + pub fn layer(self: Self, layer: L) -> Router +where + L: Layer + Clone + Send + Sync + ''static, + ::Service: Service + Clone + Send + Sync + ''static, + <::Service as Service>::Response: IntoResponse + ''static, + <::Service as Service>::Error: Into + ''static, + <::Service as Service>::Future: Send + ''static { /* ... */ } + ``` + Apply a [`tower::Layer`] to all routes in the router. + +- ```rust + pub fn route_layer(self: Self, layer: L) -> Self +where + L: Layer + Clone + Send + Sync + ''static, + ::Service: Service + Clone + Send + Sync + ''static, + <::Service as Service>::Response: IntoResponse + ''static, + <::Service as Service>::Error: Into + ''static, + <::Service as Service>::Future: Send + ''static { /* ... */ } + ``` + Apply a [`tower::Layer`] to the router that will only run if the request matches + +- ```rust + pub fn has_routes(self: &Self) -> bool { /* ... */ } + ``` + True if the router currently has at least one route added. + +- ```rust + pub fn fallback(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static { /* ... */ } + ``` + Add a fallback [`Handler`] to the router. + +- ```rust + pub fn fallback_service(self: Self, service: T) -> Self +where + T: Service + Clone + Send + Sync + ''static, + ::Response: IntoResponse, + ::Future: Send + ''static { /* ... */ } + ``` + Add a fallback [`Service`] to the router. + +- ```rust + pub fn method_not_allowed_fallback(self: Self, handler: H) -> Self +where + H: Handler, + T: ''static { /* ... */ } + ``` + Add a fallback [`Handler`] for the case where a route exists, but the method of the request is not supported. + +- ```rust + pub fn reset_fallback(self: Self) -> Self { /* ... */ } + ``` + Reset the fallback to its default. + +- ```rust + pub fn with_state(self: Self, state: S) -> Router { /* ... */ } + ``` + Provide the state for the router. State passed to this method is global and will be used + +- ```rust + pub fn as_service(self: &mut Self) -> RouterAsService<''_, B, S> { /* ... */ } + ``` + Convert the router into a borrowed [`Service`] with a fixed request body type, to aid type + +- ```rust + pub fn into_service(self: Self) -> RouterIntoService { /* ... */ } + ``` + Convert the router into an owned [`Service`] with a fixed request body type, to aid type + +- ```rust + pub fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + Convert this router into a [`MakeService`], that is a [`Service`] whose + +- ```rust + pub fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + Convert this router into a [`MakeService`], that will store `C`'s + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **MakeService** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll>::MakeError>> { /* ... */ } + ``` + + - ```rust + fn make_service(self: &mut Self, target: Target) -> >::Future { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, _req: serve::IncomingStream<''_, L>) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `RouterAsService` + +A [`Router`] converted into a borrowed [`Service`] with a fixed body type. + +See [`Router::as_service`] for more details. + +```rust +pub struct RouterAsService<''a, B, S = ()> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `RouterIntoService` + +A [`Router`] converted into an owned [`Service`] with a fixed body type. + +See [`Router::into_service`] for more details. + +```rust +pub struct RouterIntoService { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromRef** + - ```rust + fn from_ref(input: &T) -> T { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, req: Request) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** + - ```rust + fn into_make_service(self: Self) -> IntoMakeService { /* ... */ } + ``` + + - ```rust + fn into_make_service_with_connect_info(self: Self) -> IntoMakeServiceWithConnectInfo { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Re-exports + +#### Re-export `IntoMakeService` + +```rust +pub use self::into_make_service::IntoMakeService; +``` + +#### Re-export `MethodFilter` + +```rust +pub use self::method_filter::MethodFilter; +``` + +#### Re-export `Route` + +```rust +pub use self::route::Route; +``` + +#### Re-export `any` + +```rust +pub use self::method_routing::any; +``` + +#### Re-export `any_service` + +```rust +pub use self::method_routing::any_service; +``` + +#### Re-export `connect` + +```rust +pub use self::method_routing::connect; +``` + +#### Re-export `connect_service` + +```rust +pub use self::method_routing::connect_service; +``` + +#### Re-export `delete` + +```rust +pub use self::method_routing::delete; +``` + +#### Re-export `delete_service` + +```rust +pub use self::method_routing::delete_service; +``` + +#### Re-export `get` + +```rust +pub use self::method_routing::get; +``` + +#### Re-export `get_service` + +```rust +pub use self::method_routing::get_service; +``` + +#### Re-export `head` + +```rust +pub use self::method_routing::head; +``` + +#### Re-export `head_service` + +```rust +pub use self::method_routing::head_service; +``` + +#### Re-export `on` + +```rust +pub use self::method_routing::on; +``` + +#### Re-export `on_service` + +```rust +pub use self::method_routing::on_service; +``` + +#### Re-export `options` + +```rust +pub use self::method_routing::options; +``` + +#### Re-export `options_service` + +```rust +pub use self::method_routing::options_service; +``` + +#### Re-export `patch` + +```rust +pub use self::method_routing::patch; +``` + +#### Re-export `patch_service` + +```rust +pub use self::method_routing::patch_service; +``` + +#### Re-export `post` + +```rust +pub use self::method_routing::post; +``` + +#### Re-export `post_service` + +```rust +pub use self::method_routing::post_service; +``` + +#### Re-export `put` + +```rust +pub use self::method_routing::put; +``` + +#### Re-export `put_service` + +```rust +pub use self::method_routing::put_service; +``` + +#### Re-export `trace` + +```rust +pub use self::method_routing::trace; +``` + +#### Re-export `trace_service` + +```rust +pub use self::method_routing::trace_service; +``` + +#### Re-export `MethodRouter` + +```rust +pub use self::method_routing::MethodRouter; +``` + +## Module `serve` + +**Attributes:** + +- `Other("#[(all(feature = \"tokio\",\nany(feature = \"http1\", feature = \"http2\")))]")` + +Serve services. + +```rust +pub mod serve { /* ... */ } +``` + +### Types + +#### Struct `Serve` + +**Attributes:** + +- `Other("#[(all(feature = \"tokio\",\nany(feature = \"http1\", feature = \"http2\")))]")` +- `MustUse { reason: Some("futures must be awaited or polled") }` + +Future returned by [`serve`]. + +```rust +pub struct Serve { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn with_graceful_shutdown(self: Self, signal: F) -> WithGracefulShutdown +where + F: Future + Send + ''static { /* ... */ } + ``` + Prepares a server to handle graceful shutdown when the provided future completes. + +- ```rust + pub fn local_addr(self: &Self) -> io::Result<::Addr> { /* ... */ } + ``` + Returns the local address this server is bound to. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `WithGracefulShutdown` + +**Attributes:** + +- `Other("#[(all(feature = \"tokio\",\nany(feature = \"http1\", feature = \"http2\")))]")` +- `MustUse { reason: Some("futures must be awaited or polled") }` + +Serve future with graceful shutdown enabled. + +```rust +pub struct WithGracefulShutdown { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn local_addr(self: &Self) -> io::Result<::Addr> { /* ... */ } + ``` + Returns the local address this server is bound to. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +#### Struct `IncomingStream` + +An incoming stream. + +Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`]. + +[`IntoMakeServiceWithConnectInfo`]: crate::extract::connect_info::IntoMakeServiceWithConnectInfo + +```rust +pub struct IncomingStream<''a, L> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn io(self: &Self) -> &::Io { /* ... */ } + ``` + Get a reference to the inner IO type. + +- ```rust + pub fn remote_addr(self: &Self) -> &::Addr { /* ... */ } + ``` + Returns the remote address that this stream is bound to. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Connected** + - ```rust + fn connect_info(stream: serve::IncomingStream<''_, TcpListener>) -> Self { /* ... */ } + ``` + + - ```rust + fn connect_info(stream: serve::IncomingStream<''a, serve::TapIo>) -> Self { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **ErasedDestructor** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PolicyExt** + - ```rust + fn and(self: Self, other: P) -> And +where + T: Policy, + P: Policy { /* ... */ } + ``` + + - ```rust + fn or(self: Self, other: P) -> Or +where + T: Policy, + P: Policy { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Same** +- **Send** +- **Service** + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, _req: serve::IncomingStream<''_, L>) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, _req: serve::IncomingStream<''_, L>) -> ::Future { /* ... */ } + ``` + + - ```rust + fn poll_ready(self: &mut Self, _cx: &mut Context<''_>) -> Poll::Error>> { /* ... */ } + ``` + + - ```rust + fn call(self: &mut Self, _req: serve::IncomingStream<''_, L>) -> ::Future { /* ... */ } + ``` + +- **ServiceExt** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **VZip** + - ```rust + fn vzip(self: Self) -> V { /* ... */ } + ``` + +- **WithSubscriber** +### Functions + +#### Function `serve` + +**Attributes:** + +- `Other("#[(all(feature = \"tokio\",\nany(feature = \"http1\", feature = \"http2\")))]")` + +Serve the service with the supplied listener. + +This method of running a service is intentionally simple and doesn't support any configuration. +Use hyper or hyper-util if you need configuration. + +It supports both HTTP/1 as well as HTTP/2. + +# Examples + +Serving a [`Router`]: + +``` +use axum::{Router, routing::get}; + +# async { +let router = Router::new().route("/", get(|| async { "Hello, World!" })); + +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, router).await.unwrap(); +# }; +``` + +See also [`Router::into_make_service_with_connect_info`]. + +Serving a [`MethodRouter`]: + +``` +use axum::routing::get; + +# async { +let router = get(|| async { "Hello, World!" }); + +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, router).await.unwrap(); +# }; +``` + +See also [`MethodRouter::into_make_service_with_connect_info`]. + +Serving a [`Handler`]: + +``` +use axum::handler::HandlerWithoutStateExt; + +# async { +async fn handler() -> &'static str { + "Hello, World!" +} + +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, handler.into_make_service()).await.unwrap(); +# }; +``` + +See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and +[`HandlerService::into_make_service_with_connect_info`]. + +# Return Value + +Although this future resolves to `io::Result<()>`, it will never actually complete or return an +error. Errors on the TCP socket will be handled by sleeping for a short while (currently, one +second). + +[`Router`]: crate::Router +[`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info +[`MethodRouter`]: crate::routing::MethodRouter +[`MethodRouter::into_make_service_with_connect_info`]: crate::routing::MethodRouter::into_make_service_with_connect_info +[`Handler`]: crate::handler::Handler +[`HandlerWithoutStateExt::into_make_service_with_connect_info`]: crate::handler::HandlerWithoutStateExt::into_make_service_with_connect_info +[`HandlerService::into_make_service_with_connect_info`]: crate::handler::HandlerService::into_make_service_with_connect_info + +```rust +pub fn serve(listener: L, make_service: M) -> Serve +where + L: Listener, + M: for<''a> Service, Error = std::convert::Infallible, Response = S>, + S: Service + Clone + Send + ''static, + ::Future: Send { /* ... */ } +``` + +### Re-exports + +#### Re-export `Listener` + +```rust +pub use self::listener::Listener; +``` + +#### Re-export `ListenerExt` + +```rust +pub use self::listener::ListenerExt; +``` + +#### Re-export `TapIo` + +```rust +pub use self::listener::TapIo; +``` + +## Module `test_helpers` + +**Attributes:** + +- `Other("#[(any(test, feature = \"__private\"))]")` +- `Other("#[allow(missing_docs, missing_debug_implementations, clippy::print_stdout)]")` +- `Other("#[allow(clippy::disallowed_names)]")` + +```rust +pub mod test_helpers { /* ... */ } +``` + +### Re-exports + +#### Re-export `self::test_client::*` + +```rust +pub use self::test_client::*; +``` + +## Re-exports + +### Re-export `http` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use http; +``` + +### Re-export `Extension` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::extension::Extension; +``` + +### Re-export `Json` + +**Attributes:** + +- `Other("#[doc(inline)]")` +- `Other("#[(feature = \"json\")]")` + +```rust +pub use self::json::Json; +``` + +### Re-export `Router` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use self::routing::Router; +``` + +### Re-export `Form` + +**Attributes:** + +- `Other("#[doc(inline)]")` +- `Other("#[(feature = \"form\")]")` + +```rust +pub use self::form::Form; +``` + +### Re-export `BoxError` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::BoxError; +``` + +### Re-export `Error` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::Error; +``` + +### Re-export `RequestExt` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::RequestExt; +``` + +### Re-export `RequestPartsExt` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use axum_core::RequestPartsExt; +``` + +### Re-export `debug_handler` + +**Attributes:** + +- `Other("#[(feature = \"macros\")]")` + +```rust +pub use axum_macros::debug_handler; +``` + +### Re-export `debug_middleware` + +**Attributes:** + +- `Other("#[(feature = \"macros\")]")` + +```rust +pub use axum_macros::debug_middleware; +``` + +### Re-export `serve` + +**Attributes:** + +- `Other("#[(all(feature = \"tokio\",\nany(feature = \"http1\", feature = \"http2\")))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use self::serve::serve; +``` + +### Re-export `ServiceExt` + +```rust +pub use self::service_ext::ServiceExt; +``` + diff --git a/doc/mediasoup.md b/doc/mediasoup.md new file mode 100644 index 0000000..fd79f11 --- /dev/null +++ b/doc/mediasoup.md @@ -0,0 +1,4203 @@ +# Crate Documentation + +**Version:** 0.20.0 + +**Format Version:** 55 + +# Module `mediasoup` + +Rust port of [mediasoup](https://github.com/versatica/mediasoup) TypeScript library! + +For general information go to readme in repository. + +# For TypeScript users +If you were using mediasoup in TypeScript before, most of the API should be familiar to you. +However, this is not one-to-one port, API was adjusted to more idiomatic Rust style leveraging +powerful type system and ownership system to make API more robust and more misuse-resistant. + +So you will find specific types in most places where plain strings were used, instead of +`close()` you will see `Drop` implementation for major entities that will close everything +gracefully when it goes out of scope. + +# Before you start +This is very low-level **library**. Which means it doesn't come with a ready to use signaling +mechanism or easy to customize app scaffold (see +[design goals](https://github.com/versatica/mediasoup/tree/v3/rust/readme.md#design-goals)). + +It is recommended to visit mediasoup website and read +[design overview](https://mediasoup.org/documentation/v3/mediasoup/design/) first. + +There are some requirements for building underlying C++ `mediasoup-worker`, please find them in +[installation instructions](https://mediasoup.org/documentation/v3/mediasoup/installation/) + +# Examples +There are some examples in `examples` and `examples-frontend` directories (for server- and +client-side respectively), you may want to look at those to get a general idea of what API looks +like and what needs to be done in what order (check WebSocket messages in browser DevTools for +better understanding of what is happening under the hood). + +# How to start +With that in mind, you want start with creating [`WorkerManager`](worker_manager::WorkerManager) +instance and then 1 or more workers. Workers a responsible for low-level job of sending media +and data back and forth. Each worker is backed by single-core C++ worker thread. On each worker +you create one or more routers that enable injection, selection and forwarding of media and data +through [`transport`] instances. There are a few different transports available, but most likely +you'll want to use [`WebRtcTransport`](webrtc_transport::WebRtcTransport) most often. With +transport created you can start creating [`Producer`](producer::Producer)s to send data to +[`Router`](router::Router) and [`Consumer`](consumer::Consumer) instances to extract data from +[`Router`](router::Router). + +Some of the more advanced cases involve multiple routers and even workers that can user more +than one core on the machine or even scale beyond single host. Check +[scalability page](https://mediasoup.org/documentation/v3/scalability/) of the official +documentation. + +Please check integration and unit tests for usage examples, they cover all major functionality +and are a good place to start until we have demo apps built in Rust). + +## Modules + +## Module `prelude` + +mediasoup prelude. + +Re-exports commonly used traits and structs from this crate. + +# Examples + +Import the prelude with: + +``` +# #[allow(unused_imports)] +use mediasoup::prelude::*; +``` + +```rust +pub mod prelude { /* ... */ } +``` + +### Re-exports + +#### Re-export `WorkerManager` + +```rust +pub use crate::worker_manager::WorkerManager; +``` + +#### Re-export `Worker` + +```rust +pub use crate::worker::Worker; +``` + +#### Re-export `WorkerSettings` + +```rust +pub use crate::worker::WorkerSettings; +``` + +#### Re-export `PipeDataProducerToRouterError` + +```rust +pub use crate::router::PipeDataProducerToRouterError; +``` + +#### Re-export `PipeDataProducerToRouterPair` + +```rust +pub use crate::router::PipeDataProducerToRouterPair; +``` + +#### Re-export `PipeProducerToRouterError` + +```rust +pub use crate::router::PipeProducerToRouterError; +``` + +#### Re-export `PipeProducerToRouterPair` + +```rust +pub use crate::router::PipeProducerToRouterPair; +``` + +#### Re-export `PipeToRouterOptions` + +```rust +pub use crate::router::PipeToRouterOptions; +``` + +#### Re-export `Router` + +```rust +pub use crate::router::Router; +``` + +#### Re-export `RouterOptions` + +```rust +pub use crate::router::RouterOptions; +``` + +#### Re-export `WebRtcServer` + +```rust +pub use crate::webrtc_server::WebRtcServer; +``` + +#### Re-export `WebRtcServerId` + +```rust +pub use crate::webrtc_server::WebRtcServerId; +``` + +#### Re-export `WebRtcServerListenInfos` + +```rust +pub use crate::webrtc_server::WebRtcServerListenInfos; +``` + +#### Re-export `WebRtcServerOptions` + +```rust +pub use crate::webrtc_server::WebRtcServerOptions; +``` + +#### Re-export `DirectTransport` + +```rust +pub use crate::direct_transport::DirectTransport; +``` + +#### Re-export `DirectTransportOptions` + +```rust +pub use crate::direct_transport::DirectTransportOptions; +``` + +#### Re-export `WeakDirectTransport` + +```rust +pub use crate::direct_transport::WeakDirectTransport; +``` + +#### Re-export `PipeTransport` + +```rust +pub use crate::pipe_transport::PipeTransport; +``` + +#### Re-export `PipeTransportOptions` + +```rust +pub use crate::pipe_transport::PipeTransportOptions; +``` + +#### Re-export `PipeTransportRemoteParameters` + +```rust +pub use crate::pipe_transport::PipeTransportRemoteParameters; +``` + +#### Re-export `WeakPipeTransport` + +```rust +pub use crate::pipe_transport::WeakPipeTransport; +``` + +#### Re-export `PlainTransport` + +```rust +pub use crate::plain_transport::PlainTransport; +``` + +#### Re-export `PlainTransportOptions` + +```rust +pub use crate::plain_transport::PlainTransportOptions; +``` + +#### Re-export `PlainTransportRemoteParameters` + +```rust +pub use crate::plain_transport::PlainTransportRemoteParameters; +``` + +#### Re-export `WeakPlainTransport` + +```rust +pub use crate::plain_transport::WeakPlainTransport; +``` + +#### Re-export `ConsumeDataError` + +```rust +pub use crate::transport::ConsumeDataError; +``` + +#### Re-export `ConsumeError` + +```rust +pub use crate::transport::ConsumeError; +``` + +#### Re-export `ProduceDataError` + +```rust +pub use crate::transport::ProduceDataError; +``` + +#### Re-export `ProduceError` + +```rust +pub use crate::transport::ProduceError; +``` + +#### Re-export `Transport` + +```rust +pub use crate::transport::Transport; +``` + +#### Re-export `TransportGeneric` + +```rust +pub use crate::transport::TransportGeneric; +``` + +#### Re-export `TransportId` + +```rust +pub use crate::transport::TransportId; +``` + +#### Re-export `WebRtcTransport` + +```rust +pub use crate::webrtc_transport::WebRtcTransport; +``` + +#### Re-export `WebRtcTransportListenInfos` + +```rust +pub use crate::webrtc_transport::WebRtcTransportListenInfos; +``` + +#### Re-export `WebRtcTransportOptions` + +```rust +pub use crate::webrtc_transport::WebRtcTransportOptions; +``` + +#### Re-export `WebRtcTransportRemoteParameters` + +```rust +pub use crate::webrtc_transport::WebRtcTransportRemoteParameters; +``` + +#### Re-export `ActiveSpeakerObserver` + +```rust +pub use crate::active_speaker_observer::ActiveSpeakerObserver; +``` + +#### Re-export `ActiveSpeakerObserverDominantSpeaker` + +```rust +pub use crate::active_speaker_observer::ActiveSpeakerObserverDominantSpeaker; +``` + +#### Re-export `ActiveSpeakerObserverOptions` + +```rust +pub use crate::active_speaker_observer::ActiveSpeakerObserverOptions; +``` + +#### Re-export `WeakActiveSpeakerObserver` + +```rust +pub use crate::active_speaker_observer::WeakActiveSpeakerObserver; +``` + +#### Re-export `AudioLevelObserver` + +```rust +pub use crate::audio_level_observer::AudioLevelObserver; +``` + +#### Re-export `AudioLevelObserverOptions` + +```rust +pub use crate::audio_level_observer::AudioLevelObserverOptions; +``` + +#### Re-export `AudioLevelObserverVolume` + +```rust +pub use crate::audio_level_observer::AudioLevelObserverVolume; +``` + +#### Re-export `WeakAudioLevelObserver` + +```rust +pub use crate::audio_level_observer::WeakAudioLevelObserver; +``` + +#### Re-export `RtpObserver` + +```rust +pub use crate::rtp_observer::RtpObserver; +``` + +#### Re-export `RtpObserverAddProducerOptions` + +```rust +pub use crate::rtp_observer::RtpObserverAddProducerOptions; +``` + +#### Re-export `RtpObserverId` + +```rust +pub use crate::rtp_observer::RtpObserverId; +``` + +#### Re-export `Consumer` + +```rust +pub use crate::consumer::Consumer; +``` + +#### Re-export `ConsumerId` + +```rust +pub use crate::consumer::ConsumerId; +``` + +#### Re-export `ConsumerLayers` + +```rust +pub use crate::consumer::ConsumerLayers; +``` + +#### Re-export `ConsumerOptions` + +```rust +pub use crate::consumer::ConsumerOptions; +``` + +#### Re-export `WeakConsumer` + +```rust +pub use crate::consumer::WeakConsumer; +``` + +#### Re-export `DataConsumer` + +```rust +pub use crate::data_consumer::DataConsumer; +``` + +#### Re-export `DataConsumerId` + +```rust +pub use crate::data_consumer::DataConsumerId; +``` + +#### Re-export `DataConsumerOptions` + +```rust +pub use crate::data_consumer::DataConsumerOptions; +``` + +#### Re-export `DirectDataConsumer` + +```rust +pub use crate::data_consumer::DirectDataConsumer; +``` + +#### Re-export `RegularDataConsumer` + +```rust +pub use crate::data_consumer::RegularDataConsumer; +``` + +#### Re-export `WeakDataConsumer` + +```rust +pub use crate::data_consumer::WeakDataConsumer; +``` + +#### Re-export `DataProducer` + +```rust +pub use crate::data_producer::DataProducer; +``` + +#### Re-export `DataProducerId` + +```rust +pub use crate::data_producer::DataProducerId; +``` + +#### Re-export `DataProducerOptions` + +```rust +pub use crate::data_producer::DataProducerOptions; +``` + +#### Re-export `DirectDataProducer` + +```rust +pub use crate::data_producer::DirectDataProducer; +``` + +#### Re-export `NonClosingDataProducer` + +```rust +pub use crate::data_producer::NonClosingDataProducer; +``` + +#### Re-export `RegularDataProducer` + +```rust +pub use crate::data_producer::RegularDataProducer; +``` + +#### Re-export `WeakDataProducer` + +```rust +pub use crate::data_producer::WeakDataProducer; +``` + +#### Re-export `Producer` + +```rust +pub use crate::producer::Producer; +``` + +#### Re-export `ProducerId` + +```rust +pub use crate::producer::ProducerId; +``` + +#### Re-export `ProducerOptions` + +```rust +pub use crate::producer::ProducerOptions; +``` + +#### Re-export `WeakProducer` + +```rust +pub use crate::producer::WeakProducer; +``` + +#### Re-export `AppData` + +```rust +pub use mediasoup_types::data_structures::AppData; +``` + +#### Re-export `DtlsParameters` + +```rust +pub use mediasoup_types::data_structures::DtlsParameters; +``` + +#### Re-export `IceCandidate` + +```rust +pub use mediasoup_types::data_structures::IceCandidate; +``` + +#### Re-export `IceParameters` + +```rust +pub use mediasoup_types::data_structures::IceParameters; +``` + +#### Re-export `ListenInfo` + +```rust +pub use mediasoup_types::data_structures::ListenInfo; +``` + +#### Re-export `Protocol` + +```rust +pub use mediasoup_types::data_structures::Protocol; +``` + +#### Re-export `WebRtcMessage` + +```rust +pub use mediasoup_types::data_structures::WebRtcMessage; +``` + +#### Re-export `MediaKind` + +```rust +pub use mediasoup_types::rtp_parameters::MediaKind; +``` + +#### Re-export `MimeTypeAudio` + +```rust +pub use mediasoup_types::rtp_parameters::MimeTypeAudio; +``` + +#### Re-export `MimeTypeVideo` + +```rust +pub use mediasoup_types::rtp_parameters::MimeTypeVideo; +``` + +#### Re-export `RtcpFeedback` + +```rust +pub use mediasoup_types::rtp_parameters::RtcpFeedback; +``` + +#### Re-export `RtcpParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtcpParameters; +``` + +#### Re-export `RtpCapabilities` + +```rust +pub use mediasoup_types::rtp_parameters::RtpCapabilities; +``` + +#### Re-export `RtpCapabilitiesFinalized` + +```rust +pub use mediasoup_types::rtp_parameters::RtpCapabilitiesFinalized; +``` + +#### Re-export `RtpCodecCapability` + +```rust +pub use mediasoup_types::rtp_parameters::RtpCodecCapability; +``` + +#### Re-export `RtpCodecParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtpCodecParameters; +``` + +#### Re-export `RtpCodecParametersParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtpCodecParametersParameters; +``` + +#### Re-export `RtpEncodingParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtpEncodingParameters; +``` + +#### Re-export `RtpEncodingParametersRtx` + +```rust +pub use mediasoup_types::rtp_parameters::RtpEncodingParametersRtx; +``` + +#### Re-export `RtpHeaderExtensionParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtpHeaderExtensionParameters; +``` + +#### Re-export `RtpHeaderExtensionUri` + +```rust +pub use mediasoup_types::rtp_parameters::RtpHeaderExtensionUri; +``` + +#### Re-export `RtpParameters` + +```rust +pub use mediasoup_types::rtp_parameters::RtpParameters; +``` + +#### Re-export `SctpStreamParameters` + +```rust +pub use mediasoup_types::sctp_parameters::SctpStreamParameters; +``` + +#### Re-export `SrtpCryptoSuite` + +```rust +pub use mediasoup_types::srtp_parameters::SrtpCryptoSuite; +``` + +## Module `router` + +A router enables injection, selection and forwarding of media streams through [`Transport`] +instances created on it. + +Developers may think of a mediasoup router as if it were a "multi-party conference room", +although mediasoup is much more low level than that and doesn't constrain itself to specific +high level use cases (for instance, a "multi-party conference room" could involve various +mediasoup routers, even in different physicals hosts). + +```rust +pub mod router { /* ... */ } +``` + +### Types + +#### Struct `RouterId` + +[`Router`] identifier. + +```rust +pub struct RouterId(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> RouterId { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserialize** + - ```rust + fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result::Error> +where + __D: _serde::Deserializer<''de> { /* ... */ } + ``` + +- **DeserializeOwned** +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(id: RouterId) -> Self { /* ... */ } + ``` + +- **FromStr** + - ```rust + fn from_str(s: &str) -> Result::Err> { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Ord** + - ```rust + fn cmp(self: &Self, other: &RouterId) -> $crate::cmp::Ordering { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &RouterId) -> bool { /* ... */ } + ``` + +- **PartialOrd** + - ```rust + fn partial_cmp(self: &Self, other: &RouterId) -> $crate::option::Option<$crate::cmp::Ordering> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `RouterOptions` + +**Attributes:** + +- `NonExhaustive` + +[`Router`] options. + +# Notes on usage + +* Feature codecs such as `RTX` MUST NOT be placed into the mediaCodecs list. +* If `preferred_payload_type` is given in a [`RtpCodecCapability`] (although it's unnecessary) + it's extremely recommended to use a value in the 96-127 range. + +```rust +pub struct RouterOptions { + pub media_codecs: Vec, + pub app_data: mediasoup_types::data_structures::AppData, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `media_codecs` | `Vec` | Router media codecs. | +| `app_data` | `mediasoup_types::data_structures::AppData` | Custom application data. | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(media_codecs: Vec) -> Self { /* ... */ } + ``` + Create router options with given list of declared media codecs. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `PipeToRouterOptions` + +Options used for piping media or data producer to into another router on the same host. + +# Notes on usage +* SCTP arguments will only apply the first time the underlying transports are created. + +```rust +pub struct PipeToRouterOptions { + pub router: Router, + pub enable_sctp: bool, + pub num_sctp_streams: mediasoup_types::sctp_parameters::NumSctpStreams, + pub enable_rtx: bool, + pub enable_srtp: bool, + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `router` | `Router` | Target Router instance. | +| `enable_sctp` | `bool` | Create a SCTP association.

Default `true`. | +| `num_sctp_streams` | `mediasoup_types::sctp_parameters::NumSctpStreams` | SCTP streams number. | +| `enable_rtx` | `bool` | Enable RTX and NACK for RTP retransmission.

Default `false`. | +| `enable_srtp` | `bool` | Enable SRTP.

Default `false`. | +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(router: Router) -> Self { /* ... */ } + ``` + Crate pipe options for piping into given local router. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `PipeProducerToRouterPair` + +Container for pipe consumer and pipe producer pair. + +# Notes on usage +Pipe consumer and Pipe producer will not be closed on drop, to control this manually get pipe +producer out of non-closing variant with [`PipedProducer::into_inner()`] call, +otherwise pipe consumer and pipe producer lifetime will be tied to source producer lifetime. + +Pipe consumer is always tied to the lifetime of pipe producer. + +```rust +pub struct PipeProducerToRouterPair { + pub pipe_consumer: crate::consumer::Consumer, + pub pipe_producer: crate::producer::PipedProducer, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `pipe_consumer` | `crate::consumer::Consumer` | The Consumer created in the current Router. | +| `pipe_producer` | `crate::producer::PipedProducer` | The Producer created in the target Router, get regular instance with
[`PipedProducer::into_inner()`] call. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `PipeProducerToRouterError` + +Error that caused [`Router::pipe_producer_to_router()`] to fail. + +```rust +pub enum PipeProducerToRouterError { + SameRouter, + ProducerNotFound(crate::producer::ProducerId), + TransportFailed(crate::worker::RequestError), + ConsumeFailed(crate::transport::ConsumeError), + ProduceFailed(crate::transport::ProduceError), +} +``` + +##### Variants + +###### `SameRouter` + +Destination router must be different + +###### `ProducerNotFound` + +Producer with specified id not found + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::producer::ProducerId` | | + +###### `TransportFailed` + +Failed to create or connect Pipe transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::worker::RequestError` | | + +###### `ConsumeFailed` + +Failed to consume + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::transport::ConsumeError` | | + +###### `ProduceFailed` + +Failed to produce + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::transport::ProduceError` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(error: RequestError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(error: ConsumeError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(error: ProduceError) -> Self { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `PipeDataProducerToRouterPair` + +Container for pipe data consumer and pipe data producer pair. + +# Notes on usage +Pipe data consumer and pipe data producer will not be closed on drop, to control this manually +get pipe data producer out of non-closing variant with [`NonClosingDataProducer::into_inner()`] +call, otherwise pipe data consumer and pipe data producer lifetime will be tied to source data +producer lifetime. + +Pipe data consumer is always tied to the lifetime of pipe data producer. + +```rust +pub struct PipeDataProducerToRouterPair { + pub pipe_data_consumer: crate::data_consumer::DataConsumer, + pub pipe_data_producer: crate::data_producer::NonClosingDataProducer, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `pipe_data_consumer` | `crate::data_consumer::DataConsumer` | The DataConsumer created in the current Router. | +| `pipe_data_producer` | `crate::data_producer::NonClosingDataProducer` | The DataProducer created in the target Router, get regular instance with
[`NonClosingDataProducer::into_inner()`] call. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `PipeDataProducerToRouterError` + +Error that caused [`Router::pipe_data_producer_to_router()`] to fail. + +```rust +pub enum PipeDataProducerToRouterError { + SameRouter, + DataProducerNotFound(crate::data_producer::DataProducerId), + TransportFailed(crate::worker::RequestError), + ConsumeFailed(crate::transport::ConsumeDataError), + ProduceFailed(crate::transport::ProduceDataError), +} +``` + +##### Variants + +###### `SameRouter` + +Destination router must be different + +###### `DataProducerNotFound` + +Data producer with specified id not found + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::data_producer::DataProducerId` | | + +###### `TransportFailed` + +Failed to create or connect Pipe transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::worker::RequestError` | | + +###### `ConsumeFailed` + +Failed to consume + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::transport::ConsumeDataError` | | + +###### `ProduceFailed` + +Failed to produce + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `crate::transport::ProduceDataError` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(error: RequestError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(error: ConsumeDataError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(error: ProduceDataError) -> Self { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `UpdateMediaCodecsError` + +Error that caused [`Router::update_media_codecs`] to fail. + +```rust +pub enum UpdateMediaCodecsError { + FailedRtpCapabilitiesGeneration(ortc::RtpCapabilitiesError), +} +``` + +##### Variants + +###### `FailedRtpCapabilitiesGeneration` + +RTP capabilities generation error + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `ortc::RtpCapabilitiesError` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `NewTransport` + +New transport that was just created. + +```rust +pub enum NewTransport<''a> { + Direct(&''a crate::direct_transport::DirectTransport), + Pipe(&''a crate::pipe_transport::PipeTransport), + Plain(&''a crate::plain_transport::PlainTransport), + WebRtc(&''a crate::webrtc_transport::WebRtcTransport), +} +``` + +##### Variants + +###### `Direct` + +Direct transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::direct_transport::DirectTransport` | | + +###### `Pipe` + +Pipe transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::pipe_transport::PipeTransport` | | + +###### `Plain` + +Plain transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::plain_transport::PlainTransport` | | + +###### `WebRtc` + +WebRtc transport + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::webrtc_transport::WebRtcTransport` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Receiver** +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `NewRtpObserver` + +New RTP observer that was just created. + +```rust +pub enum NewRtpObserver<''a> { + AudioLevel(&''a crate::audio_level_observer::AudioLevelObserver), + ActiveSpeaker(&''a crate::active_speaker_observer::ActiveSpeakerObserver), +} +``` + +##### Variants + +###### `AudioLevel` + +Audio level observer + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::audio_level_observer::AudioLevelObserver` | | + +###### `ActiveSpeaker` + +Active speaker observer + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a crate::active_speaker_observer::ActiveSpeakerObserver` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Receiver** +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `Router` + +**Attributes:** + +- `MustUse { reason: Some("Router will be closed on drop, make sure to keep it around for as long as needed") }` + +A router enables injection, selection and forwarding of media streams through [`Transport`] +instances created on it. + +Developers may think of a mediasoup router as if it were a "multi-party conference room", +although mediasoup is much more low level than that and doesn't constrain itself to specific +high level use cases (for instance, a "multi-party conference room" could involve various +mediasoup routers, even in different physicals hosts). + +```rust +pub struct Router { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn id(self: &Self) -> RouterId { /* ... */ } + ``` + Router id. + +- ```rust + pub fn worker(self: &Self) -> &Worker { /* ... */ } + ``` + Worker to which router belongs. + +- ```rust + pub fn app_data(self: &Self) -> &AppData { /* ... */ } + ``` + Custom application data. + +- ```rust + pub fn closed(self: &Self) -> bool { /* ... */ } + ``` + Whether router is closed. + +- ```rust + pub fn rtp_capabilities(self: &Self) -> RtpCapabilitiesFinalized { /* ... */ } + ``` + RTP capabilities of the router. These capabilities are typically needed by mediasoup clients + +- ```rust + pub async fn create_direct_transport(self: &Self, direct_transport_options: DirectTransportOptions) -> Result { /* ... */ } + ``` + Create a [`DirectTransport`]. + +- ```rust + pub async fn create_webrtc_transport(self: &Self, webrtc_transport_options: WebRtcTransportOptions) -> Result { /* ... */ } + ``` + Create a [`WebRtcTransport`]. + +- ```rust + pub async fn create_pipe_transport(self: &Self, pipe_transport_options: PipeTransportOptions) -> Result { /* ... */ } + ``` + Create a [`PipeTransport`]. + +- ```rust + pub async fn create_plain_transport(self: &Self, plain_transport_options: PlainTransportOptions) -> Result { /* ... */ } + ``` + Create a [`PlainTransport`]. + +- ```rust + pub async fn create_audio_level_observer(self: &Self, audio_level_observer_options: AudioLevelObserverOptions) -> Result { /* ... */ } + ``` + Create an [`AudioLevelObserver`]. + +- ```rust + pub async fn create_active_speaker_observer(self: &Self, active_speaker_observer_options: ActiveSpeakerObserverOptions) -> Result { /* ... */ } + ``` + Create an [`ActiveSpeakerObserver`]. + +- ```rust + pub async fn pipe_producer_to_router(self: &Self, producer_id: ProducerId, pipe_to_router_options: PipeToRouterOptions) -> Result { /* ... */ } + ``` + Pipes [`Producer`] with the given `producer_id` into another [`Router`] on same host. + +- ```rust + pub async fn pipe_data_producer_to_router(self: &Self, data_producer_id: DataProducerId, pipe_to_router_options: PipeToRouterOptions) -> Result { /* ... */ } + ``` + Pipes [`DataProducer`] with the given `data_producer_id` into another [`Router`] on same + +- ```rust + pub fn can_consume(self: &Self, producer_id: &ProducerId, rtp_capabilities: &RtpCapabilities) -> bool { /* ... */ } + ``` + Check whether the given RTP capabilities are valid to consume the given producer. + +- ```rust + pub fn update_media_codecs(self: &mut Self, media_codecs: Vec) -> Result<(), UpdateMediaCodecsError> { /* ... */ } + ``` + Update the Router media codecs. Once called, the return value of + +- ```rust + pub fn on_new_transport) + Send + Sync + ''static>(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when a new transport is created. + +- ```rust + pub fn on_new_rtp_observer) + Send + Sync + ''static>(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when a new RTP observer is created. + +- ```rust + pub fn on_worker_close(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the worker this router belongs to is closed for whatever reason. + +- ```rust + pub fn on_close(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the router is closed for whatever reason. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Router { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +## Module `supported_rtp_capabilities` + +RTP capabilities supported by mediasoup. + +```rust +pub mod supported_rtp_capabilities { /* ... */ } +``` + +### Functions + +#### Function `get_supported_rtp_capabilities` + +**Attributes:** + +- `MustUse { reason: None }` + +Get a mediasoup supported RTP capabilities. + +# Notes on usage +Those are NOT the RTP capabilities needed by mediasoup-client's +[device.load()](https://mediasoup.org/documentation/v3/mediasoup-client/api/#device-load) and +libmediasoupclient's +[device.Load()](https://mediasoup.org/documentation/v3/libmediasoupclient/api/#device-Load) +methods. There you must use +[`Router::rtp_capabilities`](crate::router::Router::rtp_capabilities) getter instead. + +```rust +pub fn get_supported_rtp_capabilities() -> mediasoup_types::rtp_parameters::RtpCapabilities { /* ... */ } +``` + +## Module `webrtc_server` + +A WebRTC server brings the ability to listen on a single UDP/TCP port for multiple +`WebRtcTransport`s. + +A WebRTC server exists within the context of a [`Worker`], meaning that if your app launches N +workers it also needs to create N WebRTC servers listening on different ports (to not collide). +The WebRTC transport implementation of mediasoup is +[ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not initiate +ICE connections but expects ICE Binding Requests from endpoints. + +```rust +pub mod webrtc_server { /* ... */ } +``` + +### Types + +#### Struct `WebRtcServerId` + +[`WebRtcServer`] identifier. + +```rust +pub struct WebRtcServerId(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WebRtcServerId { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserialize** + - ```rust + fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result::Error> +where + __D: _serde::Deserializer<''de> { /* ... */ } + ``` + +- **DeserializeOwned** +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(id: WebRtcServerId) -> Self { /* ... */ } + ``` + +- **FromStr** + - ```rust + fn from_str(s: &str) -> Result::Err> { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Ord** + - ```rust + fn cmp(self: &Self, other: &WebRtcServerId) -> $crate::cmp::Ordering { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &WebRtcServerId) -> bool { /* ... */ } + ``` + +- **PartialOrd** + - ```rust + fn partial_cmp(self: &Self, other: &WebRtcServerId) -> $crate::option::Option<$crate::cmp::Ordering> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WebRtcServerListenInfos` + +Struct that protects an invariant of having non-empty list of listen infos. + +```rust +pub struct WebRtcServerListenInfos(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(listen_info: ListenInfo) -> Self { /* ... */ } + ``` + Create WebRTC server listen infos with given info populated initially. + +- ```rust + pub fn insert(self: Self, listen_info: ListenInfo) -> Self { /* ... */ } + ``` + Insert another listen info. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WebRtcServerListenInfos { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &::Target { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &WebRtcServerListenInfos) -> bool { /* ... */ } + ``` + +- **Receiver** +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + + - ```rust + fn try_from(listen_infos: Vec) -> Result::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `EmptyListError` + +**Attributes:** + +- `Other("#[error(\"Empty list of listen infos provided, should have at least one element\")]")` + +Empty list of listen infos provided, should have at least one element. + +```rust +pub struct EmptyListError; +``` + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &EmptyListError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WebRtcServerOptions` + +**Attributes:** + +- `NonExhaustive` + +[`WebRtcServer`] options. + +```rust +pub struct WebRtcServerOptions { + pub listen_infos: WebRtcServerListenInfos, + pub app_data: mediasoup_types::data_structures::AppData, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `listen_infos` | `WebRtcServerListenInfos` | Listening infos in order of preference (first one is the preferred one). | +| `app_data` | `mediasoup_types::data_structures::AppData` | Custom application data. | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(listen_infos: WebRtcServerListenInfos) -> Self { /* ... */ } + ``` + Create [`WebRtcServer`] options with given listen infos. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WebRtcServer` + +A WebRTC server brings the ability to listen on a single UDP/TCP port for multiple +`WebRtcTransport`s. + +A WebRTC server exists within the context of a [`Worker`], meaning that if your app launches N +workers it also needs to create N WebRTC servers listening on different ports (to not collide). +The WebRTC transport implementation of mediasoup is +[ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not initiate +ICE connections but expects ICE Binding Requests from endpoints. + +```rust +pub struct WebRtcServer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn id(self: &Self) -> WebRtcServerId { /* ... */ } + ``` + Router id. + +- ```rust + pub fn worker(self: &Self) -> &Worker { /* ... */ } + ``` + Worker to which WebRTC server belongs. + +- ```rust + pub fn app_data(self: &Self) -> &AppData { /* ... */ } + ``` + Custom application data. + +- ```rust + pub fn closed(self: &Self) -> bool { /* ... */ } + ``` + Whether WebRTC server is closed. + +- ```rust + pub fn on_worker_close(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the worker this WebRTC server belongs to is closed for whatever + +- ```rust + pub fn on_new_webrtc_transport(self: &Self, callback: F) -> HandlerId +where + F: Fn(&WebRtcTransport) + Send + ''static { /* ... */ } + ``` + Callback is called when new [`WebRtcTransport`] is added that uses this WebRTC server. + +- ```rust + pub fn on_close(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the WebRTC server is closed for whatever reason. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WebRtcServer { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +## Module `worker` + +A worker represents a mediasoup C++ thread that runs on a single CPU core and handles +[`Router`] instances. + +```rust +pub mod worker { /* ... */ } +``` + +### Types + +#### Struct `WorkerId` + +Worker identifier. + +```rust +pub struct WorkerId(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerId { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserialize** + - ```rust + fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result::Error> +where + __D: _serde::Deserializer<''de> { /* ... */ } + ``` + +- **DeserializeOwned** +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut std::fmt::Formatter<''_>) -> std::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(id: WorkerId) -> Self { /* ... */ } + ``` + +- **FromStr** + - ```rust + fn from_str(s: &str) -> Result::Err> { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Ord** + - ```rust + fn cmp(self: &Self, other: &WorkerId) -> $crate::cmp::Ordering { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &WorkerId) -> bool { /* ... */ } + ``` + +- **PartialOrd** + - ```rust + fn partial_cmp(self: &Self, other: &WorkerId) -> $crate::option::Option<$crate::cmp::Ordering> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `RequestError` + +Error that caused request to mediasoup-worker request to fail. + +```rust +pub enum RequestError { + ChannelClosed, + TimedOut, + Response { + reason: String, + }, + FailedToParse { + error: String, + }, + NoData, + ResponseConversion(Box), +} +``` + +##### Variants + +###### `ChannelClosed` + +Channel already closed. + +###### `TimedOut` + +Request timed out. + +###### `Response` + +Received response error. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `reason` | `String` | Error reason. | + +###### `FailedToParse` + +Failed to parse response from worker. + +Fields: + +| Name | Type | Documentation | +|------|------|---------------| +| `error` | `String` | Error reason. | + +###### `NoData` + +Worker did not return any data in response. + +###### `ResponseConversion` + +Response conversion error. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `Box` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(error: RequestError) -> Self { /* ... */ } + ``` + + - ```rust + fn from(error: RequestError) -> Self { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `WorkerLogLevel` + +**Attributes:** + +- `Other("#[serde(rename_all = \"lowercase\")]")` + +Logging level for logs generated by the media worker thread (check the +[Debugging](https://mediasoup.org/documentation/v3/mediasoup/debugging/) +documentation on TypeScript implementation and generic +[Rust-specific](https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/log.html) [docs](https://docs.rs/env_logger)). + +Default [`WorkerLogLevel::Error`]. + +```rust +pub enum WorkerLogLevel { + Debug, + Warn, + Error, + None, +} +``` + +##### Variants + +###### `Debug` + +Log all severities. + +###### `Warn` + +Log "warn" and "error" severities. + +###### `Error` + +Log "error" severity. + +###### `None` + +Do not log anything. + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerLogLevel { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Ord** + - ```rust + fn cmp(self: &Self, other: &WorkerLogLevel) -> $crate::cmp::Ordering { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &WorkerLogLevel) -> bool { /* ... */ } + ``` + +- **PartialOrd** + - ```rust + fn partial_cmp(self: &Self, other: &WorkerLogLevel) -> $crate::option::Option<$crate::cmp::Ordering> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `WorkerLogTag` + +**Attributes:** + +- `Other("#[serde(rename_all = \"lowercase\")]")` + +Log tags for debugging. Check the meaning of each available tag in the +[Debugging](https://mediasoup.org/documentation/v3/mediasoup/debugging/) documentation. + +```rust +pub enum WorkerLogTag { + Info, + Ice, + Dtls, + Rtp, + Srtp, + Rtcp, + Rtx, + Bwe, + Score, + Simulcast, + Svc, + Sctp, + Message, +} +``` + +##### Variants + +###### `Info` + +Logs about software/library versions, configuration and process information. + +###### `Ice` + +Logs about ICE. + +###### `Dtls` + +Logs about DTLS. + +###### `Rtp` + +Logs about RTP. + +###### `Srtp` + +Logs about SRTP encryption/decryption. + +###### `Rtcp` + +Logs about RTCP. + +###### `Rtx` + +Logs about RTP retransmission, including NACK/PLI/FIR. + +###### `Bwe` + +Logs about transport bandwidth estimation. + +###### `Score` + +Logs related to the scores of Producers and Consumers. + +###### `Simulcast` + +Logs about video simulcast. + +###### `Svc` + +Logs about video SVC. + +###### `Sctp` + +Logs about SCTP (DataChannel). + +###### `Message` + +Logs about messages (can be SCTP messages or direct messages). + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerLogTag { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Ord** + - ```rust + fn cmp(self: &Self, other: &WorkerLogTag) -> $crate::cmp::Ordering { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &WorkerLogTag) -> bool { /* ... */ } + ``` + +- **PartialOrd** + - ```rust + fn partial_cmp(self: &Self, other: &WorkerLogTag) -> $crate::option::Option<$crate::cmp::Ordering> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WorkerDtlsFiles` + +DTLS certificate and private key. + +```rust +pub struct WorkerDtlsFiles { + pub certificate: std::path::PathBuf, + pub private_key: std::path::PathBuf, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `certificate` | `std::path::PathBuf` | Path to the DTLS public certificate file in PEM format. | +| `private_key` | `std::path::PathBuf` | Path to the DTLS certificate private key file in PEM format. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerDtlsFiles { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WorkerSettings` + +**Attributes:** + +- `NonExhaustive` + +Settings for worker to be created with. + +```rust +pub struct WorkerSettings { + pub log_level: WorkerLogLevel, + pub log_tags: Vec, + pub rtc_port_range: std::ops::RangeInclusive, + pub dtls_files: Option, + pub enable_liburing: bool, + pub thread_initializer: Option>, + pub app_data: mediasoup_types::data_structures::AppData, + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `log_level` | `WorkerLogLevel` | Logging level for logs generated by the media worker thread.

Default [`WorkerLogLevel::Error`]. | +| `log_tags` | `Vec` | Log tags for debugging. Check the meaning of each available tag in the
[Debugging](https://mediasoup.org/documentation/v3/mediasoup/debugging/) documentation. | +| `rtc_port_range` | `std::ops::RangeInclusive` | RTC port range for ICE, DTLS, RTP, etc. Default 10000..=59999. | +| `dtls_files` | `Option` | DTLS certificate and private key.

If `None`, a certificate is dynamically created. | +| `enable_liburing` | `bool` | Enable liburing This option is ignored if io_uring is not supported by
current host.

Default `true`. | +| `thread_initializer` | `Option>` | Function that will be called under worker thread before worker starts, can be used for
pinning worker threads to CPU cores. | +| `app_data` | `mediasoup_types::data_structures::AppData` | Custom application data. | +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerSettings { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `WorkerUpdateSettings` + +**Attributes:** + +- `Other("#[serde(rename_all = \"camelCase\")]")` +- `NonExhaustive` + +Worker settings that can be updated in runtime. + +```rust +pub struct WorkerUpdateSettings { + pub log_level: Option, + pub log_tags: Option>, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `log_level` | `Option` | Logging level for logs generated by the media worker thread.

If `None`, logging level will not be updated. | +| `log_tags` | `Option>` | Log tags for debugging. Check the meaning of each available tag in the
[Debugging](https://mediasoup.org/documentation/v3/mediasoup/debugging/) documentation.

If `None`, log tags will not be updated. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerUpdateSettings { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> WorkerUpdateSettings { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error> +where + __S: _serde::Serializer { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `CreateWebRtcServerError` + +Error that caused [`Worker::create_webrtc_server`] to fail. + +```rust +pub enum CreateWebRtcServerError { + Request(RequestError), +} +``` + +##### Variants + +###### `Request` + +Request to worker failed + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `RequestError` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `CreateRouterError` + +Error that caused [`Worker::create_router`] to fail. + +```rust +pub enum CreateRouterError { + FailedRtpCapabilitiesGeneration(RtpCapabilitiesError), + Request(RequestError), +} +``` + +##### Variants + +###### `FailedRtpCapabilitiesGeneration` + +RTP capabilities generation error + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `RtpCapabilitiesError` | | + +###### `Request` + +Request to worker failed + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `RequestError` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, __formatter: &mut ::core::fmt::Formatter<''_>) -> ::core::fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `Worker` + +**Attributes:** + +- `MustUse { reason: Some("Worker will be destroyed on drop, make sure to keep it around for as long as needed") }` + +A worker represents a mediasoup C++ thread that runs on a single CPU core and handles +[`Router`] instances. + +```rust +pub struct Worker { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn id(self: &Self) -> WorkerId { /* ... */ } + ``` + Worker id. + +- ```rust + pub fn worker_manager(self: &Self) -> &WorkerManager { /* ... */ } + ``` + Worker manager to which worker belongs. + +- ```rust + pub fn app_data(self: &Self) -> &AppData { /* ... */ } + ``` + Custom application data. + +- ```rust + pub fn closed(self: &Self) -> bool { /* ... */ } + ``` + Whether the worker is closed. + +- ```rust + pub async fn update_settings(self: &Self, data: WorkerUpdateSettings) -> Result<(), RequestError> { /* ... */ } + ``` + Updates the worker settings in runtime. Just a subset of the worker settings can be updated. + +- ```rust + pub async fn create_webrtc_server(self: &Self, webrtc_server_options: WebRtcServerOptions) -> Result { /* ... */ } + ``` + Create a WebRtcServer. + +- ```rust + pub async fn create_router(self: &Self, router_options: RouterOptions) -> Result { /* ... */ } + ``` + Create a Router. + +- ```rust + pub fn on_new_webrtc_server(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when a new WebRTC server is created. + +- ```rust + pub fn on_new_router(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when a new router is created. + +- ```rust + pub fn on_dead) + Send + Sync + ''static>(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the worker thread unexpectedly dies. + +- ```rust + pub fn on_close(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when the worker is closed for whatever reason. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Worker { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Re-exports + +#### Re-export `RtpCapabilitiesError` + +```rust +pub use crate::ortc::RtpCapabilitiesError; +``` + +#### Re-export `ExitError` + +```rust +pub use crate::worker::utils::ExitError; +``` + +## Module `worker_manager` + +Container that creates [`Worker`] instances. + +```rust +pub mod worker_manager { /* ... */ } +``` + +### Types + +#### Struct `WorkerManager` + +**Attributes:** + +- `MustUse { reason: None }` + +Container that creates [`Worker`] instances. + +# Examples +```no_run +use futures_lite::future; +use mediasoup::worker::WorkerSettings; +use mediasoup::worker_manager::WorkerManager; + +// Create a manager that will use specified binary for spawning new worker thread +let worker_manager = WorkerManager::new(); + +future::block_on(async move { + // Create a new worker with default settings + let worker = worker_manager + .create_worker(WorkerSettings::default()) + .await + .unwrap(); +}) +``` + +If you already happen to have [`async_executor::Executor`] instance available or need a +multi-threaded executor, [`WorkerManager::with_executor()`] can be used to create an instance +instead. + +```rust +pub struct WorkerManager { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Create new worker manager, internally a new single-threaded executor will be created. + +- ```rust + pub fn with_executor(executor: Arc>) -> Self { /* ... */ } + ``` + Create new worker manager, uses externally provided executor. + +- ```rust + pub async fn create_worker(self: &Self, worker_settings: WorkerSettings) -> io::Result { /* ... */ } + ``` + Creates a new worker with the given settings. + +- ```rust + pub fn on_new_worker(self: &Self, callback: F) -> HandlerId { /* ... */ } + ``` + Callback is called when a new worker is created. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WorkerManager { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +## Module `audio_level_observer` + +An audio level observer monitors the volume of the selected audio producers. + +```rust +pub mod audio_level_observer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::audio_level_observer::*` + +```rust +pub use crate::router::audio_level_observer::*; +``` + +## Module `active_speaker_observer` + +An active speaker observer monitors the speaking activity of the selected audio producers. + +```rust +pub mod active_speaker_observer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::active_speaker_observer::*` + +```rust +pub use crate::router::active_speaker_observer::*; +``` + +## Module `consumer` + +A consumer represents an audio or video source being forwarded from a mediasoup router to an +endpoint. It's created on top of a transport that defines how the media packets are carried. + +```rust +pub mod consumer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::consumer::*` + +```rust +pub use crate::router::consumer::*; +``` + +## Module `data_consumer` + +A data consumer represents an endpoint capable of receiving data messages from a mediasoup +[`Router`](router::Router). + +A data consumer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA +DataChannel) to receive those messages, or can directly receive them in the Rust application +if the data consumer was created on top of a +[`DirectTransport`](direct_transport::DirectTransport). + +```rust +pub mod data_consumer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::data_consumer::*` + +```rust +pub use crate::router::data_consumer::*; +``` + +## Module `producer` + +A producer represents an audio or video source being injected into a mediasoup router. It's +created on top of a transport that defines how the media packets are carried. + +```rust +pub mod producer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::producer::*` + +```rust +pub use crate::router::producer::*; +``` + +## Module `data_producer` + +A data producer represents an endpoint capable of injecting data messages into a mediasoup +[`Router`](router::Router). + +A data producer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA DataChannel) to +deliver those messages, or can directly send them from the Rust application if the data +producer was created on top of a [`DirectTransport`](direct_transport::DirectTransport). + +```rust +pub mod data_producer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::data_producer::*` + +```rust +pub use crate::router::data_producer::*; +``` + +## Module `transport` + +A transport connects an endpoint with a mediasoup router and enables transmission of media +in both directions by means of [`Producer`](producer::Producer), +[`Consumer`](consumer::Consumer), [`DataProducer`](data_producer::DataProducer) and +[`DataConsumer`](data_consumer::DataConsumer) instances created on it. + +mediasoup implements the following transports: +* [`WebRtcTransport`](webrtc_transport::WebRtcTransport) +* [`PlainTransport`](plain_transport::PlainTransport) +* [`PipeTransport`](pipe_transport::PipeTransport) +* [`DirectTransport`](direct_transport::DirectTransport) + +```rust +pub mod transport { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::transport::*` + +```rust +pub use crate::router::transport::*; +``` + +## Module `direct_transport` + +A direct transport represents a direct connection between the mediasoup Rust process and a +[`Router`](router::Router) instance in a mediasoup-worker thread. + +A direct transport can be used to directly send and receive data messages from/to Rust by +means of [`DataProducer`](data_producer::DataProducer)s and +[`DataConsumer`](data_consumer::DataConsumer)s of type `Direct` created on a direct +transport. +Direct messages sent by a [`DataProducer`](data_producer::DataProducer) in a direct +transport can be consumed by endpoints connected through a SCTP capable transport +([`WebRtcTransport`](webrtc_transport::WebRtcTransport), +[`PlainTransport`](plain_transport::PlainTransport), +[`PipeTransport`](pipe_transport::PipeTransport) and also by the Rust application by means +of a [`DataConsumer`](data_consumer::DataConsumer) created on a [`DirectTransport`] (and +vice-versa: messages sent over SCTP/DataChannel can be consumed by the Rust application by +means of a [`DataConsumer`](data_consumer::DataConsumer) created on a [`DirectTransport`]). + +A direct transport can also be used to inject and directly consume RTP and RTCP packets in +Rust by using the [`DirectProducer::send`](producer::DirectProducer::send) and +[`Consumer::on_rtp`](consumer::Consumer::on_rtp) API (plus [`DirectTransport::send_rtcp`] +and [`DirectTransport::on_rtcp`] API). + +```rust +pub mod direct_transport { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::direct_transport::*` + +```rust +pub use crate::router::direct_transport::*; +``` + +## Module `pipe_transport` + +A pipe transport represents a network path through which RTP, RTCP (optionally secured with +SRTP) and SCTP (DataChannel) is transmitted. Pipe transports are intended to +intercommunicate two [`Router`](router::Router) instances collocated on the same host or on +separate hosts. + +# Notes on usage +When calling [`PipeTransport::consume`](transport::Transport::consume), all RTP streams of +the [`Producer`](producer::Producer) are transmitted verbatim (in contrast to what happens +in [`WebRtcTransport`](webrtc_transport::WebRtcTransport) and +[`PlainTransport`](plain_transport::PlainTransport) in which a single and continuous RTP +stream is sent to the consuming endpoint). + +```rust +pub mod pipe_transport { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::pipe_transport::*` + +```rust +pub use crate::router::pipe_transport::*; +``` + +## Module `plain_transport` + +A plain transport represents a network path through which RTP, RTCP (optionally secured with +SRTP) and SCTP (DataChannel) is transmitted. + +```rust +pub mod plain_transport { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::plain_transport::*` + +```rust +pub use crate::router::plain_transport::*; +``` + +## Module `rtp_observer` + +An RTP observer inspects the media received by a set of selected producers. + +mediasoup implements the following RTP observers: +* [`AudioLevelObserver`](audio_level_observer::AudioLevelObserver) + +```rust +pub mod rtp_observer { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::rtp_observer::*` + +```rust +pub use crate::router::rtp_observer::*; +``` + +## Module `webrtc_transport` + +A WebRTC transport represents a network path negotiated by both, a WebRTC endpoint and +mediasoup, via ICE and DTLS procedures. A WebRTC transport may be used to receive media, to +send media or to both receive and send. There is no limitation in mediasoup. However, due to +their design, mediasoup-client and libmediasoupclient require separate WebRTC transports for +sending and receiving. + +# Notes on usage +The WebRTC transport implementation of mediasoup is +[ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not +initiate ICE connections but expects ICE Binding Requests from endpoints. + +```rust +pub mod webrtc_transport { /* ... */ } +``` + +### Re-exports + +#### Re-export `crate::router::webrtc_transport::*` + +```rust +pub use crate::router::webrtc_transport::*; +``` + +## Re-exports + +### Re-export `mediasoup_types` + +```rust +pub use mediasoup_types as types; +``` + diff --git a/doc/serde.md b/doc/serde.md new file mode 100644 index 0000000..b366160 --- /dev/null +++ b/doc/serde.md @@ -0,0 +1,11869 @@ +# Crate Documentation + +**Version:** 1.0.228 + +**Format Version:** 56 + +# Module `serde` + +# Serde + +Serde is a framework for ***ser***ializing and ***de***serializing Rust data +structures efficiently and generically. + +The Serde ecosystem consists of data structures that know how to serialize +and deserialize themselves along with data formats that know how to +serialize and deserialize other things. Serde provides the layer by which +these two groups interact with each other, allowing any supported data +structure to be serialized and deserialized using any supported data format. + +See the Serde website for additional documentation and +usage examples. + +## Design + +Where many other languages rely on runtime reflection for serializing data, +Serde is instead built on Rust's powerful trait system. A data structure +that knows how to serialize and deserialize itself is one that implements +Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive +attribute to automatically generate implementations at compile time). This +avoids any overhead of reflection or runtime type information. In fact in +many situations the interaction between data structure and data format can +be completely optimized away by the Rust compiler, leaving Serde +serialization to perform the same speed as a handwritten serializer for the +specific selection of data structure and data format. + +## Data formats + +The following is a partial list of data formats that have been implemented +for Serde by the community. + +- [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs. +- [Postcard], a no\_std and embedded-systems friendly compact binary format. +- [CBOR], a Concise Binary Object Representation designed for small message + size without the need for version negotiation. +- [YAML], a self-proclaimed human-friendly configuration language that ain't + markup language. +- [MessagePack], an efficient binary format that resembles a compact JSON. +- [TOML], a minimal configuration format used by [Cargo]. +- [Pickle], a format common in the Python world. +- [RON], a Rusty Object Notation. +- [BSON], the data storage and network transfer format used by MongoDB. +- [Avro], a binary format used within Apache Hadoop, with support for schema + definition. +- [JSON5], a superset of JSON including some productions from ES5. +- [URL] query strings, in the x-www-form-urlencoded format. +- [Starlark], the format used for describing build targets by the Bazel and + Buck build systems. *(serialization only)* +- [Envy], a way to deserialize environment variables into Rust structs. + *(deserialization only)* +- [Envy Store], a way to deserialize [AWS Parameter Store] parameters into + Rust structs. *(deserialization only)* +- [S-expressions], the textual representation of code and data used by the + Lisp language family. +- [D-Bus]'s binary wire format. +- [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy + serialization format. +- [Bencode], a simple binary format used in the BitTorrent protocol. +- [Token streams], for processing Rust procedural macro input. + *(deserialization only)* +- [DynamoDB Items], the format used by [rusoto_dynamodb] to transfer data to + and from DynamoDB. +- [Hjson], a syntax extension to JSON designed around human reading and + editing. *(deserialization only)* +- [CSV], Comma-separated values is a tabular text file format. + +[JSON]: https://github.com/serde-rs/json +[Postcard]: https://github.com/jamesmunns/postcard +[CBOR]: https://github.com/enarx/ciborium +[YAML]: https://github.com/dtolnay/serde-yaml +[MessagePack]: https://github.com/3Hren/msgpack-rust +[TOML]: https://docs.rs/toml +[Pickle]: https://github.com/birkenfeld/serde-pickle +[RON]: https://github.com/ron-rs/ron +[BSON]: https://github.com/mongodb/bson-rust +[Avro]: https://docs.rs/apache-avro +[JSON5]: https://github.com/callum-oakley/json5-rs +[URL]: https://docs.rs/serde_qs +[Starlark]: https://github.com/dtolnay/serde-starlark +[Envy]: https://github.com/softprops/envy +[Envy Store]: https://github.com/softprops/envy-store +[Cargo]: https://doc.rust-lang.org/cargo/reference/manifest.html +[AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html +[S-expressions]: https://github.com/rotty/lexpr-rs +[D-Bus]: https://docs.rs/zvariant +[FlexBuffers]: https://github.com/google/flatbuffers/tree/master/rust/flexbuffers +[Bencode]: https://github.com/P3KI/bendy +[Token streams]: https://github.com/oxidecomputer/serde_tokenstream +[DynamoDB Items]: https://docs.rs/serde_dynamo +[rusoto_dynamodb]: https://docs.rs/rusoto_dynamodb +[Hjson]: https://github.com/Canop/deser-hjson +[CSV]: https://docs.rs/csv + +## Modules + +## Module `de` + +**Attributes:** + +- `Other("#[(all(docsrs, if_docsrs_then_no_serde_core), path =\n\"core/de/mod.rs\")]")` +- `Other("#[attr = Path(\"core/de/mod.rs\")]")` + +Generic data structure deserialization framework. + +The two most important traits in this module are [`Deserialize`] and +[`Deserializer`]. + + - **A type that implements `Deserialize` is a data structure** that can be + deserialized from any data format supported by Serde, and conversely + - **A type that implements `Deserializer` is a data format** that can + deserialize any data structure supported by Serde. + +# The Deserialize trait + +Serde provides [`Deserialize`] implementations for many Rust primitive and +standard library types. The complete list is below. All of these can be +deserialized using Serde out of the box. + +Additionally, Serde provides a procedural macro called [`serde_derive`] to +automatically generate [`Deserialize`] implementations for structs and enums +in your program. See the [derive section of the manual] for how to use this. + +In rare cases it may be necessary to implement [`Deserialize`] manually for +some type in your program. See the [Implementing `Deserialize`] section of +the manual for more about this. + +Third-party crates may provide [`Deserialize`] implementations for types +that they expose. For example the [`linked-hash-map`] crate provides a +[`LinkedHashMap`] type that is deserializable by Serde because the +crate provides an implementation of [`Deserialize`] for it. + +# The Deserializer trait + +[`Deserializer`] implementations are provided by third-party crates, for +example [`serde_json`], [`serde_yaml`] and [`postcard`]. + +A partial list of well-maintained formats is given on the [Serde +website][data formats]. + +# Implementations of Deserialize provided by Serde + +This is a slightly different set of types than what is supported for +serialization. Some types can be serialized by Serde but not deserialized. +One example is `OsStr`. + + - **Primitive types**: + - bool + - i8, i16, i32, i64, i128, isize + - u8, u16, u32, u64, u128, usize + - f32, f64 + - char + - **Compound types**: + - \[T; 0\] through \[T; 32\] + - tuples up to size 16 + - **Common standard library types**: + - String + - Option\ + - Result\ + - PhantomData\ + - **Wrapper types**: + - Box\ + - Box\<\[T\]\> + - Box\ + - Cow\<'a, T\> + - Cell\ + - RefCell\ + - Mutex\ + - RwLock\ + - Rc\ *(if* features = \["rc"\] *is enabled)* + - Arc\ *(if* features = \["rc"\] *is enabled)* + - **Collection types**: + - BTreeMap\ + - BTreeSet\ + - BinaryHeap\ + - HashMap\ + - HashSet\ + - LinkedList\ + - VecDeque\ + - Vec\ + - **Zero-copy types**: + - &str + - &\[u8\] + - **FFI types**: + - CString + - Box\ + - OsString + - **Miscellaneous standard library types**: + - Duration + - SystemTime + - Path + - PathBuf + - Range\ + - RangeInclusive\ + - Bound\ + - num::NonZero* + - `!` *(unstable)* + - **Net types**: + - IpAddr + - Ipv4Addr + - Ipv6Addr + - SocketAddr + - SocketAddrV4 + - SocketAddrV6 + +[Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html +[`Deserialize`]: crate::Deserialize +[`Deserializer`]: crate::Deserializer +[`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +[`postcard`]: https://github.com/jamesmunns/postcard +[`linked-hash-map`]: https://crates.io/crates/linked-hash-map +[`serde_derive`]: https://crates.io/crates/serde_derive +[`serde_json`]: https://github.com/serde-rs/json +[`serde_yaml`]: https://github.com/dtolnay/serde-yaml +[derive section of the manual]: https://serde.rs/derive.html +[data formats]: https://serde.rs/#data-formats + +```rust +pub mod de { /* ... */ } +``` + +### Modules + +## Module `value` + +Building blocks for deserializing basic values using the `IntoDeserializer` +trait. + +```edition2021 +use serde::de::{value, Deserialize, IntoDeserializer}; +use serde_derive::Deserialize; +use std::str::FromStr; + +#[derive(Deserialize)] +enum Setting { + On, + Off, +} + +impl FromStr for Setting { + type Err = value::Error; + + fn from_str(s: &str) -> Result { + Self::deserialize(s.into_deserializer()) + } +} +``` + +```rust +pub mod value { /* ... */ } +``` + +### Types + +#### Struct `Error` + +A minimal representation of all possible errors that can occur using the +`IntoDeserializer` trait. + +```rust +pub struct Error { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Error { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Error** + - ```rust + fn custom(msg: T) -> Self +where + T: Display { /* ... */ } + ``` + + - ```rust + fn custom(msg: T) -> Self +where + T: Display { /* ... */ } + ``` + + - ```rust + fn description(self: &Self) -> &str { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Error) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `UnitDeserializer` + +A deserializer holding a `()`. + +```rust +pub struct UnitDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `NeverDeserializer` + +**Attributes:** + +- `Other("#[(feature = \"unstable\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"unstable\")))]")` +- `Other("#[doc(cfg(feature = \"unstable\"))]")` + +A deserializer that cannot be instantiated. + +```rust +pub struct NeverDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, _visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `BoolDeserializer` + +A deserializer holding +a `bool`. + +```rust +pub struct BoolDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: bool) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `I8Deserializer` + +A deserializer holding +an `i8`. + +```rust +pub struct I8Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: i8) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `I16Deserializer` + +A deserializer holding +an `i16`. + +```rust +pub struct I16Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: i16) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `I32Deserializer` + +A deserializer holding +an `i32`. + +```rust +pub struct I32Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: i32) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `I64Deserializer` + +A deserializer holding +an `i64`. + +```rust +pub struct I64Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: i64) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `I128Deserializer` + +A deserializer holding +an `i128`. + +```rust +pub struct I128Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: i128) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `IsizeDeserializer` + +A deserializer holding +an `isize`. + +```rust +pub struct IsizeDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: isize) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `U8Deserializer` + +A deserializer holding +a `u8`. + +```rust +pub struct U8Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: u8) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `U16Deserializer` + +A deserializer holding +a `u16`. + +```rust +pub struct U16Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: u16) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `U64Deserializer` + +A deserializer holding +a `u64`. + +```rust +pub struct U64Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: u64) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `U128Deserializer` + +A deserializer holding +a `u128`. + +```rust +pub struct U128Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: u128) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `UsizeDeserializer` + +A deserializer holding +a `usize`. + +```rust +pub struct UsizeDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: usize) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `F32Deserializer` + +A deserializer holding +an `f32`. + +```rust +pub struct F32Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: f32) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `F64Deserializer` + +A deserializer holding +an `f64`. + +```rust +pub struct F64Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: f64) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `CharDeserializer` + +A deserializer holding +a `char`. + +```rust +pub struct CharDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: char) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `U32Deserializer` + +A deserializer holding a `u32`. + +```rust +pub struct U32Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: u32) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &str, variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `StrDeserializer` + +A deserializer holding a `&str`. + +```rust +pub struct StrDeserializer<''a, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: &''a str) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &str, variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `BorrowedStrDeserializer` + +A deserializer holding a `&str` with a lifetime tied to another +deserializer. + +```rust +pub struct BorrowedStrDeserializer<''de, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: &''de str) -> BorrowedStrDeserializer<''de, E> { /* ... */ } + ``` + Create a new borrowed deserializer from the given string. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &str, variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `StringDeserializer` + +**Attributes:** + +- `Other("#[(any(feature = \"std\", feature = \"alloc\"))]")` +- `Other("#[(docsrs, doc(cfg(any(feature = \"std\", feature = \"alloc\"))))]")` +- `Other("#[doc(cfg(any(feature = \"std\", feature = \"alloc\")))]")` + +A deserializer holding a `String`. + +```rust +pub struct StringDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: String) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &str, variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `CowStrDeserializer` + +**Attributes:** + +- `Other("#[(any(feature = \"std\", feature = \"alloc\"))]")` +- `Other("#[(docsrs, doc(cfg(any(feature = \"std\", feature = \"alloc\"))))]")` +- `Other("#[doc(cfg(any(feature = \"std\", feature = \"alloc\")))]")` + +A deserializer holding a `Cow`. + +```rust +pub struct CowStrDeserializer<''a, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: Cow<''a, str>) -> Self { /* ... */ } + ``` + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &str, variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `BytesDeserializer` + +A deserializer holding a `&[u8]`. Always calls [`Visitor::visit_bytes`]. + +```rust +pub struct BytesDeserializer<''a, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: &''a [u8]) -> Self { /* ... */ } + ``` + Create a new deserializer from the given bytes. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `BorrowedBytesDeserializer` + +A deserializer holding a `&[u8]` with a lifetime tied to another +deserializer. Always calls [`Visitor::visit_borrowed_bytes`]. + +```rust +pub struct BorrowedBytesDeserializer<''de, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(value: &''de [u8]) -> Self { /* ... */ } + ``` + Create a new borrowed deserializer from the given borrowed bytes. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `SeqDeserializer` + +A deserializer that iterates over a sequence. + +```rust +pub struct SeqDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(iter: I) -> Self { /* ... */ } + ``` + Construct a new `SeqDeserializer`. + +- ```rust + pub fn end(self: Self) -> Result<(), E> { /* ... */ } + ``` + Check for remaining elements after passing a `SeqDeserializer` to + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SeqDeserializer { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **SeqAccess** + - ```rust + fn next_element_seed(self: &mut Self, seed: V) -> Result::Value>, ::Error> +where + V: de::DeserializeSeed<''de> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> Option { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `SeqAccessDeserializer` + +A deserializer holding a `SeqAccess`. + +```rust +pub struct SeqAccessDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(seq: A) -> Self { /* ... */ } + ``` + Construct a new `SeqAccessDeserializer`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SeqAccessDeserializer { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `MapDeserializer` + +A deserializer that iterates over a map. + +```rust +pub struct MapDeserializer<''de, I, E> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(iter: I) -> Self { /* ... */ } + ``` + Construct a new `MapDeserializer`. + +- ```rust + pub fn end(self: Self) -> Result<(), E> { /* ... */ } + ``` + Check for remaining elements after passing a `MapDeserializer` to + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **MapAccess** + - ```rust + fn next_key_seed(self: &mut Self, seed: T) -> Result::Value>, ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + + - ```rust + fn next_value_seed(self: &mut Self, seed: T) -> Result<::Value, ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + + - ```rust + fn next_entry_seed(self: &mut Self, kseed: TK, vseed: TV) -> Result::Value, ::Value)>, ::Error> +where + TK: de::DeserializeSeed<''de>, + TV: de::DeserializeSeed<''de> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> Option { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **SeqAccess** + - ```rust + fn next_element_seed(self: &mut Self, seed: T) -> Result::Value>, ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> Option { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `MapAccessDeserializer` + +A deserializer holding a `MapAccess`. + +```rust +pub struct MapAccessDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(map: A) -> Self { /* ... */ } + ``` + Construct a new `MapAccessDeserializer`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> MapAccessDeserializer { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, _name: &str, _variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **EnumAccess** + - ```rust + fn variant_seed(self: Self, seed: T) -> Result<(::Value, ::Variant), ::Error> +where + T: de::DeserializeSeed<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `EnumAccessDeserializer` + +A deserializer holding an `EnumAccess`. + +```rust +pub struct EnumAccessDeserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(access: A) -> Self { /* ... */ } + ``` + Construct a new `EnumAccessDeserializer`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> EnumAccessDeserializer { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> Self { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Types + +#### Enum `Unexpected` + +`Unexpected` represents an unexpected invocation of any one of the `Visitor` +trait methods. + +This is used as an argument to the `invalid_type`, `invalid_value`, and +`invalid_length` methods of the `Error` trait to build error messages. + +```edition2021 +# use std::fmt; +# +# use serde::de::{self, Unexpected, Visitor}; +# +# struct Example; +# +# impl<'de> Visitor<'de> for Example { +# type Value = (); +# +# fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +# write!(formatter, "definitely not a boolean") +# } +# +fn visit_bool(self, v: bool) -> Result +where + E: de::Error, +{ + Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +} +# } +``` + +```rust +pub enum Unexpected<''a> { + Bool(bool), + Unsigned(u64), + Signed(i64), + Float(f64), + Char(char), + Str(&''a str), + Bytes(&''a [u8]), + Unit, + Option, + NewtypeStruct, + Seq, + Map, + Enum, + UnitVariant, + NewtypeVariant, + TupleVariant, + StructVariant, + Other(&''a str), +} +``` + +##### Variants + +###### `Bool` + +The input contained a boolean value that was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `bool` | | + +###### `Unsigned` + +The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that +was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `u64` | | + +###### `Signed` + +The input contained a signed integer `i8`, `i16`, `i32` or `i64` that +was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `i64` | | + +###### `Float` + +The input contained a floating point `f32` or `f64` that was not +expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `f64` | | + +###### `Char` + +The input contained a `char` that was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `char` | | + +###### `Str` + +The input contained a `&str` or `String` that was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a str` | | + +###### `Bytes` + +The input contained a `&[u8]` or `Vec` that was not expected. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a [u8]` | | + +###### `Unit` + +The input contained a unit `()` that was not expected. + +###### `Option` + +The input contained an `Option` that was not expected. + +###### `NewtypeStruct` + +The input contained a newtype struct that was not expected. + +###### `Seq` + +The input contained a sequence that was not expected. + +###### `Map` + +The input contained a map that was not expected. + +###### `Enum` + +The input contained an enum that was not expected. + +###### `UnitVariant` + +The input contained a unit variant that was not expected. + +###### `NewtypeVariant` + +The input contained a newtype variant that was not expected. + +###### `TupleVariant` + +The input contained a tuple variant that was not expected. + +###### `StructVariant` + +The input contained a struct variant that was not expected. + +###### `Other` + +A message stating what uncategorized thing the input contained that was +not expected. + +The message should be a noun or noun phrase, not capitalized and without +a period. An example message is "unoriginal superhero". + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `&''a str` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Unexpected<''a> { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Unexpected<''a>) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Traits + +#### Trait `Error` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace), diagnostic ::\non_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Error` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Error` is not satisfied\",)]")` + +The `Error` trait allows `Deserialize` implementations to create descriptive +error messages belonging to the `Deserializer` against which they are +currently running. + +Every `Deserializer` declares an `Error` type that encompasses both +general-purpose deserialization errors as well as errors specific to the +particular deserialization format. For example the `Error` type of +`serde_json` can represent errors like an invalid JSON escape sequence or an +unterminated string literal, in addition to the error cases that are part of +this trait. + +Most deserializers should only need to provide the `Error::custom` method +and inherit the default behavior for the other methods. + +# Example implementation + +The [example data format] presented on the website shows an error +type appropriate for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait Error: Sized + StdError { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `custom`: Raised when there is general error when deserializing a type. + +##### Provided Methods + +- ```rust + fn invalid_type(unexp: Unexpected<''_>, exp: &dyn Expected) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` receives a type different from what it was + +- ```rust + fn invalid_value(unexp: Unexpected<''_>, exp: &dyn Expected) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` receives a value of the right type but that + +- ```rust + fn invalid_length(len: usize, exp: &dyn Expected) -> Self { /* ... */ } + ``` + Raised when deserializing a sequence or map and the input data contains + +- ```rust + fn unknown_variant(variant: &str, expected: &''static [&''static str]) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` enum type received a variant with an + +- ```rust + fn unknown_field(field: &str, expected: &''static [&''static str]) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` struct type received a field with an + +- ```rust + fn missing_field(field: &''static str) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` struct type expected to receive a required + +- ```rust + fn duplicate_field(field: &''static str) -> Self { /* ... */ } + ``` + Raised when a `Deserialize` struct type received more than one of the + +##### Implementations + +This trait is implemented for the following types: + +- `Error` + +#### Trait `Expected` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Expected` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Expected` is not satisfied\",)]")` + +`Expected` represents an explanation of what data a `Visitor` was expecting +to receive. + +This is used as an argument to the `invalid_type`, `invalid_value`, and +`invalid_length` methods of the `Error` trait to build error messages. The +message should be a noun or noun phrase that completes the sentence "This +Visitor expects to receive ...", for example the message could be "an +integer between 0 and 64". The message should not be capitalized and should +not end with a period. + +Within the context of a `Visitor` implementation, the `Visitor` itself +(`&self`) is an implementation of this trait. + +```edition2021 +# use serde::de::{self, Unexpected, Visitor}; +# use std::fmt; +# +# struct Example; +# +# impl<'de> Visitor<'de> for Example { +# type Value = (); +# +# fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +# write!(formatter, "definitely not a boolean") +# } +# +fn visit_bool(self, v: bool) -> Result +where + E: de::Error, +{ + Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +} +# } +``` + +Outside of a `Visitor`, `&"..."` can be used. + +```edition2021 +# use serde::de::{self, Unexpected}; +# +# fn example() -> Result<(), E> +# where +# E: de::Error, +# { +# let v = true; +return Err(de::Error::invalid_type( + Unexpected::Bool(v), + &"a negative integer", +)); +# } +``` + +```rust +pub trait Expected { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `fmt`: Format an explanation of what data was being expected. Same signature as + +##### Implementations + +This trait is implemented for the following types: + +- `T` with <''de, T> +- `&str` + +#### Trait `Deserialize` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Deserialize<'de>` is not satisfied\", note =\n\"for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type\",\nnote =\n\"for types from other crates check whether the crate offers a `serde` feature flag\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Deserialize<'de>` is not satisfied\", note =\n\"for local types consider adding `#[derive(serde::Deserialize)]` to your `{Self}` type\",\nnote =\n\"for types from other crates check whether the crate offers a `serde` feature flag\",)]")` + +A **data structure** that can be deserialized from any data format supported +by Serde. + +Serde provides `Deserialize` implementations for many Rust primitive and +standard library types. The complete list is [here][crate::de]. All of these +can be deserialized using Serde out of the box. + +Additionally, Serde provides a procedural macro called `serde_derive` to +automatically generate `Deserialize` implementations for structs and enums +in your program. See the [derive section of the manual][derive] for how to +use this. + +In rare cases it may be necessary to implement `Deserialize` manually for +some type in your program. See the [Implementing +`Deserialize`][impl-deserialize] section of the manual for more about this. + +Third-party crates may provide `Deserialize` implementations for types that +they expose. For example the `linked-hash-map` crate provides a +`LinkedHashMap` type that is deserializable by Serde because the crate +provides an implementation of `Deserialize` for it. + +[derive]: https://serde.rs/derive.html +[impl-deserialize]: https://serde.rs/impl-deserialize.html + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by `Self` when deserialized. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +```rust +pub trait Deserialize<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `deserialize`: Deserialize this value from the given Serde deserializer. + +##### Implementations + +This trait is implemented for the following types: + +- `IgnoredAny` with <''de> +- `()` with <''de> +- `never` with <''de> +- `bool` with <''de> +- `i8` with <''de> +- `num::NonZeroI8` with <''de> +- `Saturating` with <''de> +- `i16` with <''de> +- `num::NonZeroI16` with <''de> +- `Saturating` with <''de> +- `i32` with <''de> +- `num::NonZeroI32` with <''de> +- `Saturating` with <''de> +- `i64` with <''de> +- `num::NonZeroI64` with <''de> +- `Saturating` with <''de> +- `isize` with <''de> +- `num::NonZeroIsize` with <''de> +- `Saturating` with <''de> +- `u8` with <''de> +- `num::NonZeroU8` with <''de> +- `Saturating` with <''de> +- `u16` with <''de> +- `num::NonZeroU16` with <''de> +- `Saturating` with <''de> +- `u32` with <''de> +- `num::NonZeroU32` with <''de> +- `Saturating` with <''de> +- `u64` with <''de> +- `num::NonZeroU64` with <''de> +- `Saturating` with <''de> +- `usize` with <''de> +- `num::NonZeroUsize` with <''de> +- `Saturating` with <''de> +- `f32` with <''de> +- `f64` with <''de> +- `i128` with <''de> +- `num::NonZeroI128` with <''de> +- `Saturating` with <''de> +- `u128` with <''de> +- `num::NonZeroU128` with <''de> +- `Saturating` with <''de> +- `char` with <''de> +- `String` with <''de> +- `&''a str` with <''de: ''a, ''a> +- `&''a [u8]` with <''de: ''a, ''a> +- `CString` with <''de> +- `Box` with <''de> +- `Reverse` with <''de, T: Deserialize<''de>> +- `Option` with <''de, T> +- `PhantomData` with <''de, T> +- `BinaryHeap` with <''de, T> +- `BTreeSet` with <''de, T> +- `LinkedList` with <''de, T> +- `HashSet` with <''de, T, S> +- `VecDeque` with <''de, T> +- `Vec` with <''de, T> +- `[T; 0]` with <''de, T> +- `[T; 1]` with <''de, T> +- `[T; 2]` with <''de, T> +- `[T; 3]` with <''de, T> +- `[T; 4]` with <''de, T> +- `[T; 5]` with <''de, T> +- `[T; 6]` with <''de, T> +- `[T; 7]` with <''de, T> +- `[T; 8]` with <''de, T> +- `[T; 9]` with <''de, T> +- `[T; 10]` with <''de, T> +- `[T; 11]` with <''de, T> +- `[T; 12]` with <''de, T> +- `[T; 13]` with <''de, T> +- `[T; 14]` with <''de, T> +- `[T; 15]` with <''de, T> +- `[T; 16]` with <''de, T> +- `[T; 17]` with <''de, T> +- `[T; 18]` with <''de, T> +- `[T; 19]` with <''de, T> +- `[T; 20]` with <''de, T> +- `[T; 21]` with <''de, T> +- `[T; 22]` with <''de, T> +- `[T; 23]` with <''de, T> +- `[T; 24]` with <''de, T> +- `[T; 25]` with <''de, T> +- `[T; 26]` with <''de, T> +- `[T; 27]` with <''de, T> +- `[T; 28]` with <''de, T> +- `[T; 29]` with <''de, T> +- `[T; 30]` with <''de, T> +- `[T; 31]` with <''de, T> +- `[T; 32]` with <''de, T> +- `(T)` with <''de, T> +- `BTreeMap` with <''de, K, V> +- `HashMap` with <''de, K, V, S> +- `net::IpAddr` with <''de> +- `net::Ipv4Addr` with <''de> +- `net::Ipv6Addr` with <''de> +- `net::SocketAddr` with <''de> +- `net::SocketAddrV4` with <''de> +- `net::SocketAddrV6` with <''de> +- `&''a Path` with <''de: ''a, ''a> +- `PathBuf` with <''de> +- `Box` with <''de> +- `OsString` with <''de> +- `Box` with <''de, T: Deserialize<''de>> +- `Box<[T]>` with <''de, T: Deserialize<''de>> +- `Box` with <''de> +- `Box` with <''de> +- `Cow<''a, T>` with <''de, ''a, T> +- `RcWeak` with <''de, T> +- `ArcWeak` with <''de, T> +- `Rc` with <''de, T> +- `Arc` with <''de, T> +- `Cell` with <''de, T> +- `RefCell` with <''de, T: Deserialize<''de>> +- `Mutex` with <''de, T: Deserialize<''de>> +- `RwLock` with <''de, T: Deserialize<''de>> +- `Duration` with <''de> +- `SystemTime` with <''de> +- `Range` with <''de, Idx> +- `RangeInclusive` with <''de, Idx> +- `RangeFrom` with <''de, Idx> +- `RangeTo` with <''de, Idx> +- `Bound` with <''de, T> +- `Wrapping` with <''de, T> +- `AtomicBool` with <''de> +- `AtomicI8` with <''de> +- `AtomicI16` with <''de> +- `AtomicI32` with <''de> +- `AtomicIsize` with <''de> +- `AtomicU8` with <''de> +- `AtomicU16` with <''de> +- `AtomicU32` with <''de> +- `AtomicUsize` with <''de> +- `AtomicI64` with <''de> +- `AtomicU64` with <''de> + +#### Trait `DeserializeOwned` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::DeserializeOwned` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::DeserializeOwned` is not satisfied\",)]")` + +A data structure that can be deserialized without borrowing any data from +the deserializer. + +This is primarily useful for trait bounds on functions. For example a +`from_str` function may be able to deserialize a data structure that borrows +from the input string, but a `from_reader` function may only deserialize +owned data. + +```edition2021 +# use serde::de::{Deserialize, DeserializeOwned}; +# use std::io::{Read, Result}; +# +# trait Ignore { +fn from_str<'a, T>(s: &'a str) -> Result +where + T: Deserialize<'a>; + +fn from_reader(rdr: R) -> Result +where + R: Read, + T: DeserializeOwned; +# } +``` + +# Lifetime + +The relationship between `Deserialize` and `DeserializeOwned` in trait +bounds is explained in more detail on the page [Understanding deserializer +lifetimes]. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +```rust +pub trait DeserializeOwned: for<''de> Deserialize<''de> { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Implementations + +This trait is implemented for the following types: + +- `T` with + +#### Trait `DeserializeSeed` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::DeserializeSeed<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::DeserializeSeed<'de>` is not satisfied\",)]")` + +`DeserializeSeed` is the stateful form of the `Deserialize` trait. If you +ever find yourself looking for a way to pass data into a `Deserialize` impl, +this trait is the way to do it. + +As one example of stateful deserialization consider deserializing a JSON +array into an existing buffer. Using the `Deserialize` trait we could +deserialize a JSON array into a `Vec` but it would be a freshly allocated +`Vec`; there is no way for `Deserialize` to reuse a previously allocated +buffer. Using `DeserializeSeed` instead makes this possible as in the +example code below. + +The canonical API for stateless deserialization looks like this: + +```edition2021 +# use serde::Deserialize; +# +# enum Error {} +# +fn func<'de, T: Deserialize<'de>>() -> Result +# { +# unimplemented!() +# } +``` + +Adjusting an API like this to support stateful deserialization is a matter +of accepting a seed as input: + +```edition2021 +# use serde::de::DeserializeSeed; +# +# enum Error {} +# +fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result +# { +# let _ = seed; +# unimplemented!() +# } +``` + +In practice the majority of deserialization is stateless. An API expecting a +seed can be appeased by passing `std::marker::PhantomData` as a seed in the +case of stateless deserialization. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by `Self::Value` when deserialized. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example + +Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need +to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. +Allocating a brand new `Vec` for each subarray would be slow. Instead we +would like to allocate a single `Vec` and then deserialize each subarray +into it. This requires stateful deserialization using the `DeserializeSeed` +trait. + +```edition2021 +use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor}; +use std::fmt; +use std::marker::PhantomData; + +// A DeserializeSeed implementation that uses stateful deserialization to +// append array elements onto the end of an existing vector. The preexisting +// state ("seed") in this case is the Vec. The `deserialize` method of +// `ExtendVec` will be traversing the inner arrays of the JSON input and +// appending each integer into the existing Vec. +struct ExtendVec<'a, T: 'a>(&'a mut Vec); + +impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T> +where + T: Deserialize<'de>, +{ + // The return type of the `deserialize` method. This implementation + // appends onto an existing vector but does not create any new data + // structure, so the return type is (). + type Value = (); + + fn deserialize(self, deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // Visitor implementation that will walk an inner array of the JSON + // input. + struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec); + + impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "an array of integers") + } + + fn visit_seq(self, mut seq: A) -> Result<(), A::Error> + where + A: SeqAccess<'de>, + { + // Decrease the number of reallocations if there are many elements + if let Some(size_hint) = seq.size_hint() { + self.0.reserve(size_hint); + } + + // Visit each element in the inner array and push it onto + // the existing vector. + while let Some(elem) = seq.next_element()? { + self.0.push(elem); + } + Ok(()) + } + } + + deserializer.deserialize_seq(ExtendVecVisitor(self.0)) + } +} + +// Visitor implementation that will walk the outer array of the JSON input. +struct FlattenedVecVisitor(PhantomData); + +impl<'de, T> Visitor<'de> for FlattenedVecVisitor +where + T: Deserialize<'de>, +{ + // This Visitor constructs a single Vec to hold the flattened + // contents of the inner arrays. + type Value = Vec; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "an array of arrays") + } + + fn visit_seq(self, mut seq: A) -> Result, A::Error> + where + A: SeqAccess<'de>, + { + // Create a single Vec to hold the flattened contents. + let mut vec = Vec::new(); + + // Each iteration through this loop is one inner array. + while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? { + // Nothing to do; inner array has been appended into `vec`. + } + + // Return the finished vec. + Ok(vec) + } +} + +# fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +# where +# D: Deserializer<'de>, +# { +let visitor = FlattenedVecVisitor(PhantomData); +let flattened: Vec = deserializer.deserialize_seq(visitor)?; +# Ok(()) +# } +``` + +```rust +pub trait DeserializeSeed<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Value`: The type produced by using this seed. + +###### Required Methods + +- `deserialize`: Equivalent to the more common `Deserialize::deserialize` method, except + +##### Implementations + +This trait is implemented for the following types: + +- `PhantomData` with <''de, T> + +#### Trait `Deserializer` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Deserializer<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Deserializer<'de>` is not satisfied\",)]")` + +A **data format** that can deserialize any data structure supported by +Serde. + +The role of this trait is to define the deserialization half of the [Serde +data model], which is a way to categorize every Rust data type into one of +29 possible types. Each method of the `Deserializer` trait corresponds to one +of the types of the data model. + +Implementations of `Deserialize` map themselves into this data model by +passing to the `Deserializer` a `Visitor` implementation that can receive +these various types. + +The types that make up the Serde data model are: + + - **14 primitive types** + - bool + - i8, i16, i32, i64, i128 + - u8, u16, u32, u64, u128 + - f32, f64 + - char + - **string** + - UTF-8 bytes with a length and no null terminator. + - When serializing, all strings are handled equally. When deserializing, + there are three flavors of strings: transient, owned, and borrowed. + - **byte array** - \[u8\] + - Similar to strings, during deserialization byte arrays can be + transient, owned, or borrowed. + - **option** + - Either none or some value. + - **unit** + - The type of `()` in Rust. It represents an anonymous value containing + no data. + - **unit_struct** + - For example `struct Unit` or `PhantomData`. It represents a named + value containing no data. + - **unit_variant** + - For example the `E::A` and `E::B` in `enum E { A, B }`. + - **newtype_struct** + - For example `struct Millimeters(u8)`. + - **newtype_variant** + - For example the `E::N` in `enum E { N(u8) }`. + - **seq** + - A variably sized heterogeneous sequence of values, for example `Vec` + or `HashSet`. When serializing, the length may or may not be known + before iterating through all the data. When deserializing, the length + is determined by looking at the serialized data. + - **tuple** + - A statically sized heterogeneous sequence of values for which the + length will be known at deserialization time without looking at the + serialized data, for example `(u8,)` or `(String, u64, Vec)` or + `[u64; 10]`. + - **tuple_struct** + - A named tuple, for example `struct Rgb(u8, u8, u8)`. + - **tuple_variant** + - For example the `E::T` in `enum E { T(u8, u8) }`. + - **map** + - A heterogeneous key-value pairing, for example `BTreeMap`. + - **struct** + - A heterogeneous key-value pairing in which the keys are strings and + will be known at deserialization time without looking at the serialized + data, for example `struct S { r: u8, g: u8, b: u8 }`. + - **struct_variant** + - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. + +The `Deserializer` trait supports two entry point styles which enables +different kinds of deserialization. + +1. The `deserialize_any` method. Self-describing data formats like JSON are + able to look at the serialized data and tell what it represents. For + example the JSON deserializer may see an opening curly brace (`{`) and + know that it is seeing a map. If the data format supports + `Deserializer::deserialize_any`, it will drive the Visitor using whatever + type it sees in the input. JSON uses this approach when deserializing + `serde_json::Value` which is an enum that can represent any JSON + document. Without knowing what is in a JSON document, we can deserialize + it to `serde_json::Value` by going through + `Deserializer::deserialize_any`. + +2. The various `deserialize_*` methods. Non-self-describing formats like + Postcard need to be told what is in the input in order to deserialize it. + The `deserialize_*` methods are hints to the deserializer for how to + interpret the next piece of input. Non-self-describing formats are not + able to deserialize something like `serde_json::Value` which relies on + `Deserializer::deserialize_any`. + +When implementing `Deserialize`, you should avoid relying on +`Deserializer::deserialize_any` unless you need to be told by the +Deserializer what type is in the input. Know that relying on +`Deserializer::deserialize_any` means your data type will be able to +deserialize from self-describing formats only, ruling out Postcard and many +others. + +[Serde data model]: https://serde.rs/data-model.html + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed from the input when deserializing. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example implementation + +The [example data format] presented on the website contains example code for +a basic JSON `Deserializer`. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait Deserializer<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Error`: The error type that can be returned if some error occurs during + +###### Required Methods + +- `deserialize_any`: Require the `Deserializer` to figure out how to drive the visitor based +- `deserialize_bool`: Hint that the `Deserialize` type is expecting a `bool` value. +- `deserialize_i8`: Hint that the `Deserialize` type is expecting an `i8` value. +- `deserialize_i16`: Hint that the `Deserialize` type is expecting an `i16` value. +- `deserialize_i32`: Hint that the `Deserialize` type is expecting an `i32` value. +- `deserialize_i64`: Hint that the `Deserialize` type is expecting an `i64` value. +- `deserialize_u8`: Hint that the `Deserialize` type is expecting a `u8` value. +- `deserialize_u16`: Hint that the `Deserialize` type is expecting a `u16` value. +- `deserialize_u32`: Hint that the `Deserialize` type is expecting a `u32` value. +- `deserialize_u64`: Hint that the `Deserialize` type is expecting a `u64` value. +- `deserialize_f32`: Hint that the `Deserialize` type is expecting a `f32` value. +- `deserialize_f64`: Hint that the `Deserialize` type is expecting a `f64` value. +- `deserialize_char`: Hint that the `Deserialize` type is expecting a `char` value. +- `deserialize_str`: Hint that the `Deserialize` type is expecting a string value and does +- `deserialize_string`: Hint that the `Deserialize` type is expecting a string value and would +- `deserialize_bytes`: Hint that the `Deserialize` type is expecting a byte array and does not +- `deserialize_byte_buf`: Hint that the `Deserialize` type is expecting a byte array and would +- `deserialize_option`: Hint that the `Deserialize` type is expecting an optional value. +- `deserialize_unit`: Hint that the `Deserialize` type is expecting a unit value. +- `deserialize_unit_struct`: Hint that the `Deserialize` type is expecting a unit struct with a +- `deserialize_newtype_struct`: Hint that the `Deserialize` type is expecting a newtype struct with a +- `deserialize_seq`: Hint that the `Deserialize` type is expecting a sequence of values. +- `deserialize_tuple`: Hint that the `Deserialize` type is expecting a sequence of values and +- `deserialize_tuple_struct`: Hint that the `Deserialize` type is expecting a tuple struct with a +- `deserialize_map`: Hint that the `Deserialize` type is expecting a map of key-value pairs. +- `deserialize_struct`: Hint that the `Deserialize` type is expecting a struct with a particular +- `deserialize_enum`: Hint that the `Deserialize` type is expecting an enum value with a +- `deserialize_identifier`: Hint that the `Deserialize` type is expecting the name of a struct +- `deserialize_ignored_any`: Hint that the `Deserialize` type needs to deserialize a value whose type + +##### Provided Methods + +- ```rust + fn deserialize_i128(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + Hint that the `Deserialize` type is expecting an `i128` value. + +- ```rust + fn deserialize_u128(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + Hint that the `Deserialize` type is expecting an `u128` value. + +- ```rust + fn is_human_readable(self: &Self) -> bool { /* ... */ } + ``` + Determine whether `Deserialize` implementations should expect to + +##### Implementations + +This trait is implemented for the following types: + +- `UnitDeserializer` with <''de, E> +- `NeverDeserializer` with <''de, E> +- `BoolDeserializer` with <''de, E> +- `I8Deserializer` with <''de, E> +- `I16Deserializer` with <''de, E> +- `I32Deserializer` with <''de, E> +- `I64Deserializer` with <''de, E> +- `I128Deserializer` with <''de, E> +- `IsizeDeserializer` with <''de, E> +- `U8Deserializer` with <''de, E> +- `U16Deserializer` with <''de, E> +- `U64Deserializer` with <''de, E> +- `U128Deserializer` with <''de, E> +- `UsizeDeserializer` with <''de, E> +- `F32Deserializer` with <''de, E> +- `F64Deserializer` with <''de, E> +- `CharDeserializer` with <''de, E> +- `U32Deserializer` with <''de, E> +- `StrDeserializer<''a, E>` with <''de, ''a, E> +- `BorrowedStrDeserializer<''de, E>` with <''de, E> +- `StringDeserializer` with <''de, E> +- `CowStrDeserializer<''a, E>` with <''de, ''a, E> +- `BytesDeserializer<''a, E>` with <''de, ''a, E> +- `BorrowedBytesDeserializer<''de, E>` with <''de, E> +- `SeqDeserializer` with <''de, I, T, E> +- `SeqAccessDeserializer` with <''de, A> +- `MapDeserializer<''de, I, E>` with <''de, I, E> +- `MapAccessDeserializer` with <''de, A> +- `EnumAccessDeserializer` with <''de, A> + +#### Trait `Visitor` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Visitor<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::Visitor<'de>` is not satisfied\",)]")` + +This trait represents a visitor that walks through a deserializer. + +# Lifetime + +The `'de` lifetime of this trait is the requirement for lifetime of data +that may be borrowed by `Self::Value`. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example + +```edition2021 +# use serde::de::{self, Unexpected, Visitor}; +# use std::fmt; +# +/// A visitor that deserializes a long string - a string containing at least +/// some minimum number of bytes. +struct LongString { + min: usize, +} + +impl<'de> Visitor<'de> for LongString { + type Value = String; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a string containing at least {} bytes", self.min) + } + + fn visit_str(self, s: &str) -> Result + where + E: de::Error, + { + if s.len() >= self.min { + Ok(s.to_owned()) + } else { + Err(de::Error::invalid_value(Unexpected::Str(s), &self)) + } + } +} +``` + +```rust +pub trait Visitor<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Value`: The value produced by this visitor. + +###### Required Methods + +- `expecting`: Format a message stating what data this Visitor expects to receive. + +##### Provided Methods + +- ```rust + fn visit_bool(self: Self, v: bool) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a boolean. + +- ```rust + fn visit_i8(self: Self, v: i8) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `i8`. + +- ```rust + fn visit_i16(self: Self, v: i16) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `i16`. + +- ```rust + fn visit_i32(self: Self, v: i32) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `i32`. + +- ```rust + fn visit_i64(self: Self, v: i64) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `i64`. + +- ```rust + fn visit_i128(self: Self, v: i128) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `i128`. + +- ```rust + fn visit_u8(self: Self, v: u8) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `u8`. + +- ```rust + fn visit_u16(self: Self, v: u16) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `u16`. + +- ```rust + fn visit_u32(self: Self, v: u32) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `u32`. + +- ```rust + fn visit_u64(self: Self, v: u64) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `u64`. + +- ```rust + fn visit_u128(self: Self, v: u128) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `u128`. + +- ```rust + fn visit_f32(self: Self, v: f32) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `f32`. + +- ```rust + fn visit_f64(self: Self, v: f64) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an `f64`. + +- ```rust + fn visit_char(self: Self, v: char) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a `char`. + +- ```rust + fn visit_str(self: Self, v: &str) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a string. The lifetime of the string is ephemeral and + +- ```rust + fn visit_borrowed_str(self: Self, v: &''de str) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a string that lives at least as long as the + +- ```rust + fn visit_string(self: Self, v: String) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a string and ownership of the string is being given + +- ```rust + fn visit_bytes(self: Self, v: &[u8]) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a byte array. The lifetime of the byte array is + +- ```rust + fn visit_borrowed_bytes(self: Self, v: &''de [u8]) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a byte array that lives at least as long as the + +- ```rust + fn visit_byte_buf(self: Self, v: Vec) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a byte array and ownership of the byte array is being + +- ```rust + fn visit_none(self: Self) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains an optional that is absent. + +- ```rust + fn visit_some(self: Self, deserializer: D) -> Result<::Value, ::Error> +where + D: Deserializer<''de> { /* ... */ } + ``` + The input contains an optional that is present. + +- ```rust + fn visit_unit(self: Self) -> Result<::Value, E> +where + E: Error { /* ... */ } + ``` + The input contains a unit `()`. + +- ```rust + fn visit_newtype_struct(self: Self, deserializer: D) -> Result<::Value, ::Error> +where + D: Deserializer<''de> { /* ... */ } + ``` + The input contains a newtype struct. + +- ```rust + fn visit_seq(self: Self, seq: A) -> Result<::Value, ::Error> +where + A: SeqAccess<''de> { /* ... */ } + ``` + The input contains a sequence of elements. + +- ```rust + fn visit_map(self: Self, map: A) -> Result<::Value, ::Error> +where + A: MapAccess<''de> { /* ... */ } + ``` + The input contains a key-value map. + +- ```rust + fn visit_enum(self: Self, data: A) -> Result<::Value, ::Error> +where + A: EnumAccess<''de> { /* ... */ } + ``` + The input contains an enum. + +##### Implementations + +This trait is implemented for the following types: + +- `IgnoredAny` with <''de> + +#### Trait `SeqAccess` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::SeqAccess<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::SeqAccess<'de>` is not satisfied\",)]")` + +Provides a `Visitor` access to each element of a sequence in the input. + +This is a trait that a `Deserializer` passes to a `Visitor` implementation, +which deserializes each item in a sequence. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by deserialized sequence elements. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SeqAccess` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SeqAccess<''de> { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Error`: The error type that can be returned if some error occurs during + +###### Required Methods + +- `next_element_seed`: This returns `Ok(Some(value))` for the next value in the sequence, or + +##### Provided Methods + +- ```rust + fn next_element(self: &mut Self) -> Result, ::Error> +where + T: Deserialize<''de> { /* ... */ } + ``` + This returns `Ok(Some(value))` for the next value in the sequence, or + +- ```rust + fn size_hint(self: &Self) -> Option { /* ... */ } + ``` + Returns the number of elements remaining in the sequence, if known. + +##### Implementations + +This trait is implemented for the following types: + +- `SeqDeserializer` with <''de, I, T, E> +- `MapDeserializer<''de, I, E>` with <''de, I, E> +- `&mut A` with <''de, A> + +#### Trait `MapAccess` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::MapAccess<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::MapAccess<'de>` is not satisfied\",)]")` + +Provides a `Visitor` access to each entry of a map in the input. + +This is a trait that a `Deserializer` passes to a `Visitor` implementation. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by deserialized map entries. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `MapAccess` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait MapAccess<''de> { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Error`: The error type that can be returned if some error occurs during + +###### Required Methods + +- `next_key_seed`: This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` +- `next_value_seed`: This returns a `Ok(value)` for the next value in the map. + +##### Provided Methods + +- ```rust + fn next_entry_seed(self: &mut Self, kseed: K, vseed: V) -> Result::Value, ::Value)>, ::Error> +where + K: DeserializeSeed<''de>, + V: DeserializeSeed<''de> { /* ... */ } + ``` + This returns `Ok(Some((key, value)))` for the next (key-value) pair in + +- ```rust + fn next_key(self: &mut Self) -> Result, ::Error> +where + K: Deserialize<''de> { /* ... */ } + ``` + This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + +- ```rust + fn next_value(self: &mut Self) -> Result::Error> +where + V: Deserialize<''de> { /* ... */ } + ``` + This returns a `Ok(value)` for the next value in the map. + +- ```rust + fn next_entry(self: &mut Self) -> Result, ::Error> +where + K: Deserialize<''de>, + V: Deserialize<''de> { /* ... */ } + ``` + This returns `Ok(Some((key, value)))` for the next (key-value) pair in + +- ```rust + fn size_hint(self: &Self) -> Option { /* ... */ } + ``` + Returns the number of entries remaining in the map, if known. + +##### Implementations + +This trait is implemented for the following types: + +- `MapDeserializer<''de, I, E>` with <''de, I, E> +- `&mut A` with <''de, A> + +#### Trait `EnumAccess` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::EnumAccess<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::EnumAccess<'de>` is not satisfied\",)]")` + +Provides a `Visitor` access to the data of an enum in the input. + +`EnumAccess` is created by the `Deserializer` and passed to the +`Visitor` in order to identify which variant of an enum to deserialize. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by the deserialized enum variant. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `EnumAccess` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait EnumAccess<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Error`: The error type that can be returned if some error occurs during +- `Variant`: The `Visitor` that will be used to deserialize the content of the enum + +###### Required Methods + +- `variant_seed`: `variant` is called to identify which variant to deserialize. + +##### Provided Methods + +- ```rust + fn variant(self: Self) -> Result<(V, ::Variant), ::Error> +where + V: Deserialize<''de> { /* ... */ } + ``` + `variant` is called to identify which variant to deserialize. + +##### Implementations + +This trait is implemented for the following types: + +- `U32Deserializer` with <''de, E> +- `StrDeserializer<''a, E>` with <''de, ''a, E> +- `BorrowedStrDeserializer<''de, E>` with <''de, E> +- `StringDeserializer` with <''de, E> +- `CowStrDeserializer<''a, E>` with <''de, ''a, E> +- `MapAccessDeserializer` with <''de, A> + +#### Trait `VariantAccess` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::VariantAccess<'de>` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::de::VariantAccess<'de>` is not satisfied\",)]")` + +`VariantAccess` is a visitor that is created by the `Deserializer` and +passed to the `Deserialize` to deserialize the content of a particular enum +variant. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed by the deserialized enum variant. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `VariantAccess` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait VariantAccess<''de>: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Error`: The error type that can be returned if some error occurs during + +###### Required Methods + +- `unit_variant`: Called when deserializing a variant with no values. +- `newtype_variant_seed`: Called when deserializing a variant with a single value. +- `tuple_variant`: Called when deserializing a tuple-like variant. +- `struct_variant`: Called when deserializing a struct-like variant. + +##### Provided Methods + +- ```rust + fn newtype_variant(self: Self) -> Result::Error> +where + T: Deserialize<''de> { /* ... */ } + ``` + Called when deserializing a variant with a single value. + +#### Trait `IntoDeserializer` + +Converts an existing value into a `Deserializer` from which other values can +be deserialized. + +# Lifetime + +The `'de` lifetime of this trait is the lifetime of data that may be +borrowed from the resulting `Deserializer`. See the page [Understanding +deserializer lifetimes] for a more detailed explanation of these lifetimes. + +[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html + +# Example + +```edition2021 +use serde::de::{value, Deserialize, IntoDeserializer}; +use serde_derive::Deserialize; +use std::str::FromStr; + +#[derive(Deserialize)] +enum Setting { + On, + Off, +} + +impl FromStr for Setting { + type Err = value::Error; + + fn from_str(s: &str) -> Result { + Self::deserialize(s.into_deserializer()) + } +} +``` + +```rust +pub trait IntoDeserializer<''de, E: Error = value::Error> { + /* Associated items */ +} +``` + +##### Required Items + +###### Associated Types + +- `Deserializer`: The type of the deserializer being converted into. + +###### Required Methods + +- `into_deserializer`: Convert this value into a deserializer. + +##### Implementations + +This trait is implemented for the following types: + +- `()` with <''de, E> +- `UnitDeserializer` with <''de, E> +- `never` with <''de, E> +- `NeverDeserializer` with <''de, E> +- `bool` with <''de, E> +- `BoolDeserializer` with <''de, E> +- `i8` with <''de, E> +- `I8Deserializer` with <''de, E> +- `i16` with <''de, E> +- `I16Deserializer` with <''de, E> +- `i32` with <''de, E> +- `I32Deserializer` with <''de, E> +- `i64` with <''de, E> +- `I64Deserializer` with <''de, E> +- `i128` with <''de, E> +- `I128Deserializer` with <''de, E> +- `isize` with <''de, E> +- `IsizeDeserializer` with <''de, E> +- `u8` with <''de, E> +- `U8Deserializer` with <''de, E> +- `u16` with <''de, E> +- `U16Deserializer` with <''de, E> +- `u64` with <''de, E> +- `U64Deserializer` with <''de, E> +- `u128` with <''de, E> +- `U128Deserializer` with <''de, E> +- `usize` with <''de, E> +- `UsizeDeserializer` with <''de, E> +- `f32` with <''de, E> +- `F32Deserializer` with <''de, E> +- `f64` with <''de, E> +- `F64Deserializer` with <''de, E> +- `char` with <''de, E> +- `CharDeserializer` with <''de, E> +- `u32` with <''de, E> +- `U32Deserializer` with <''de, E> +- `&''a str` with <''de, ''a, E> +- `StrDeserializer<''a, E>` with <''de, ''a, E> +- `BorrowedStrDeserializer<''de, E>` with <''de, E> +- `String` with <''de, E> +- `StringDeserializer` with <''de, E> +- `Cow<''a, str>` with <''de, ''a, E> +- `CowStrDeserializer<''a, E>` with <''de, ''a, E> +- `&''a [u8]` with <''de, ''a, E> +- `BytesDeserializer<''a, E>` with <''de, ''a, E> +- `BorrowedBytesDeserializer<''de, E>` with <''de, E> +- `SeqDeserializer` with <''de, I, T, E> +- `Vec` with <''de, T, E> +- `BTreeSet` with <''de, T, E> +- `HashSet` with <''de, T, S, E> +- `SeqAccessDeserializer` with <''de, A> +- `MapDeserializer<''de, I, E>` with <''de, I, E> +- `BTreeMap` with <''de, K, V, E> +- `HashMap` with <''de, K, V, S, E> +- `MapAccessDeserializer` with <''de, A> +- `EnumAccessDeserializer` with <''de, A> + +### Re-exports + +#### Re-export `IgnoredAny` + +```rust +pub use self::ignored_any::IgnoredAny; +``` + +#### Re-export `Error` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::error::Error as StdError; +``` + +## Module `ser` + +**Attributes:** + +- `Other("#[(all(docsrs, if_docsrs_then_no_serde_core), path =\n\"core/ser/mod.rs\")]")` +- `Other("#[attr = Path(\"core/ser/mod.rs\")]")` + +Generic data structure serialization framework. + +The two most important traits in this module are [`Serialize`] and +[`Serializer`]. + + - **A type that implements `Serialize` is a data structure** that can be + serialized to any data format supported by Serde, and conversely + - **A type that implements `Serializer` is a data format** that can + serialize any data structure supported by Serde. + +# The Serialize trait + +Serde provides [`Serialize`] implementations for many Rust primitive and +standard library types. The complete list is below. All of these can be +serialized using Serde out of the box. + +Additionally, Serde provides a procedural macro called [`serde_derive`] to +automatically generate [`Serialize`] implementations for structs and enums +in your program. See the [derive section of the manual] for how to use this. + +In rare cases it may be necessary to implement [`Serialize`] manually for +some type in your program. See the [Implementing `Serialize`] section of the +manual for more about this. + +Third-party crates may provide [`Serialize`] implementations for types that +they expose. For example the [`linked-hash-map`] crate provides a +[`LinkedHashMap`] type that is serializable by Serde because the crate +provides an implementation of [`Serialize`] for it. + +# The Serializer trait + +[`Serializer`] implementations are provided by third-party crates, for +example [`serde_json`], [`serde_yaml`] and [`postcard`]. + +A partial list of well-maintained formats is given on the [Serde +website][data formats]. + +# Implementations of Serialize provided by Serde + + - **Primitive types**: + - bool + - i8, i16, i32, i64, i128, isize + - u8, u16, u32, u64, u128, usize + - f32, f64 + - char + - str + - &T and &mut T + - **Compound types**: + - \[T\] + - \[T; 0\] through \[T; 32\] + - tuples up to size 16 + - **Common standard library types**: + - String + - Option\ + - Result\ + - PhantomData\ + - **Wrapper types**: + - Box\ + - Cow\<'a, T\> + - Cell\ + - RefCell\ + - Mutex\ + - RwLock\ + - Rc\ *(if* features = \["rc"\] *is enabled)* + - Arc\ *(if* features = \["rc"\] *is enabled)* + - **Collection types**: + - BTreeMap\ + - BTreeSet\ + - BinaryHeap\ + - HashMap\ + - HashSet\ + - LinkedList\ + - VecDeque\ + - Vec\ + - **FFI types**: + - CStr + - CString + - OsStr + - OsString + - **Miscellaneous standard library types**: + - Duration + - SystemTime + - Path + - PathBuf + - Range\ + - RangeInclusive\ + - Bound\ + - num::NonZero* + - `!` *(unstable)* + - **Net types**: + - IpAddr + - Ipv4Addr + - Ipv6Addr + - SocketAddr + - SocketAddrV4 + - SocketAddrV6 + +[Implementing `Serialize`]: https://serde.rs/impl-serialize.html +[`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +[`Serialize`]: crate::Serialize +[`Serializer`]: crate::Serializer +[`postcard`]: https://github.com/jamesmunns/postcard +[`linked-hash-map`]: https://crates.io/crates/linked-hash-map +[`serde_derive`]: https://crates.io/crates/serde_derive +[`serde_json`]: https://github.com/serde-rs/json +[`serde_yaml`]: https://github.com/dtolnay/serde-yaml +[derive section of the manual]: https://serde.rs/derive.html +[data formats]: https://serde.rs/#data-formats + +```rust +pub mod ser { /* ... */ } +``` + +### Traits + +#### Trait `Error` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace), diagnostic ::\non_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::Error` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::Error` is not satisfied\",)]")` + +Trait used by `Serialize` implementations to generically construct +errors belonging to the `Serializer` against which they are +currently running. + +# Example implementation + +The [example data format] presented on the website shows an error +type appropriate for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait Error: Sized + StdError { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `custom`: Used when a [`Serialize`] implementation encounters any error + +##### Implementations + +This trait is implemented for the following types: + +- `Error` +- `fmt::Error` + +#### Trait `Serialize` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Serialize` is not satisfied\", note =\n\"for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type\",\nnote =\n\"for types from other crates check whether the crate offers a `serde` feature flag\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Serialize` is not satisfied\", note =\n\"for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type\",\nnote =\n\"for types from other crates check whether the crate offers a `serde` feature flag\",)]")` + +A **data structure** that can be serialized into any data format supported +by Serde. + +Serde provides `Serialize` implementations for many Rust primitive and +standard library types. The complete list is [here][crate::ser]. All of +these can be serialized using Serde out of the box. + +Additionally, Serde provides a procedural macro called [`serde_derive`] to +automatically generate `Serialize` implementations for structs and enums in +your program. See the [derive section of the manual] for how to use this. + +In rare cases it may be necessary to implement `Serialize` manually for some +type in your program. See the [Implementing `Serialize`] section of the +manual for more about this. + +Third-party crates may provide `Serialize` implementations for types that +they expose. For example the [`linked-hash-map`] crate provides a +[`LinkedHashMap`] type that is serializable by Serde because the crate +provides an implementation of `Serialize` for it. + +[Implementing `Serialize`]: https://serde.rs/impl-serialize.html +[`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +[`linked-hash-map`]: https://crates.io/crates/linked-hash-map +[`serde_derive`]: https://crates.io/crates/serde_derive +[derive section of the manual]: https://serde.rs/derive.html + +```rust +pub trait Serialize { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `serialize`: Serialize this value into the given Serde serializer. + +##### Implementations + +This trait is implemented for the following types: + +- `bool` +- `isize` +- `i8` +- `i16` +- `i32` +- `i64` +- `i128` +- `usize` +- `u8` +- `u16` +- `u32` +- `u64` +- `u128` +- `f32` +- `f64` +- `char` +- `str` +- `String` +- `fmt::Arguments<''a>` with <''a> +- `CStr` +- `CString` +- `Option` with +- `PhantomData` with +- `[T; 0]` with +- `[T; 1]` with +- `[T; 2]` with +- `[T; 3]` with +- `[T; 4]` with +- `[T; 5]` with +- `[T; 6]` with +- `[T; 7]` with +- `[T; 8]` with +- `[T; 9]` with +- `[T; 10]` with +- `[T; 11]` with +- `[T; 12]` with +- `[T; 13]` with +- `[T; 14]` with +- `[T; 15]` with +- `[T; 16]` with +- `[T; 17]` with +- `[T; 18]` with +- `[T; 19]` with +- `[T; 20]` with +- `[T; 21]` with +- `[T; 22]` with +- `[T; 23]` with +- `[T; 24]` with +- `[T; 25]` with +- `[T; 26]` with +- `[T; 27]` with +- `[T; 28]` with +- `[T; 29]` with +- `[T; 30]` with +- `[T; 31]` with +- `[T; 32]` with +- `[T]` with +- `BinaryHeap` with +- `BTreeSet` with +- `HashSet` with +- `LinkedList` with +- `Vec` with +- `VecDeque` with +- `Range` with +- `RangeFrom` with +- `RangeInclusive` with +- `RangeTo` with +- `Bound` with +- `()` +- `never` +- `(T)` with +- `BTreeMap` with +- `HashMap` with +- `&''a T` with <''a, T> +- `&''a mut T` with <''a, T> +- `Box` with +- `Rc` with +- `Arc` with +- `Cow<''a, T>` with <''a, T> +- `RcWeak` with +- `ArcWeak` with +- `num::NonZeroI8` +- `num::NonZeroI16` +- `num::NonZeroI32` +- `num::NonZeroI64` +- `num::NonZeroI128` +- `num::NonZeroIsize` +- `num::NonZeroU8` +- `num::NonZeroU16` +- `num::NonZeroU32` +- `num::NonZeroU64` +- `num::NonZeroU128` +- `num::NonZeroUsize` +- `Cell` with +- `RefCell` with +- `Mutex` with +- `RwLock` with +- `Duration` +- `SystemTime` +- `net::IpAddr` +- `net::Ipv4Addr` +- `net::Ipv6Addr` +- `net::SocketAddr` +- `net::SocketAddrV4` +- `net::SocketAddrV6` +- `Path` +- `PathBuf` +- `OsStr` +- `OsString` +- `Wrapping` with +- `Saturating` with +- `Reverse` with +- `AtomicBool` +- `AtomicI8` +- `AtomicI16` +- `AtomicI32` +- `AtomicIsize` +- `AtomicU8` +- `AtomicU16` +- `AtomicU32` +- `AtomicUsize` +- `AtomicI64` +- `AtomicU64` + +#### Trait `Serializer` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Serializer` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::Serializer` is not satisfied\",)]")` + +A **data format** that can serialize any data structure supported by Serde. + +The role of this trait is to define the serialization half of the [Serde +data model], which is a way to categorize every Rust data structure into one +of 29 possible types. Each method of the `Serializer` trait corresponds to +one of the types of the data model. + +Implementations of `Serialize` map themselves into this data model by +invoking exactly one of the `Serializer` methods. + +The types that make up the Serde data model are: + + - **14 primitive types** + - bool + - i8, i16, i32, i64, i128 + - u8, u16, u32, u64, u128 + - f32, f64 + - char + - **string** + - UTF-8 bytes with a length and no null terminator. + - When serializing, all strings are handled equally. When deserializing, + there are three flavors of strings: transient, owned, and borrowed. + - **byte array** - \[u8\] + - Similar to strings, during deserialization byte arrays can be + transient, owned, or borrowed. + - **option** + - Either none or some value. + - **unit** + - The type of `()` in Rust. It represents an anonymous value containing + no data. + - **unit_struct** + - For example `struct Unit` or `PhantomData`. It represents a named + value containing no data. + - **unit_variant** + - For example the `E::A` and `E::B` in `enum E { A, B }`. + - **newtype_struct** + - For example `struct Millimeters(u8)`. + - **newtype_variant** + - For example the `E::N` in `enum E { N(u8) }`. + - **seq** + - A variably sized heterogeneous sequence of values, for example + `Vec` or `HashSet`. When serializing, the length may or may not + be known before iterating through all the data. When deserializing, + the length is determined by looking at the serialized data. + - **tuple** + - A statically sized heterogeneous sequence of values for which the + length will be known at deserialization time without looking at the + serialized data, for example `(u8,)` or `(String, u64, Vec)` or + `[u64; 10]`. + - **tuple_struct** + - A named tuple, for example `struct Rgb(u8, u8, u8)`. + - **tuple_variant** + - For example the `E::T` in `enum E { T(u8, u8) }`. + - **map** + - A heterogeneous key-value pairing, for example `BTreeMap`. + - **struct** + - A heterogeneous key-value pairing in which the keys are strings and + will be known at deserialization time without looking at the + serialized data, for example `struct S { r: u8, g: u8, b: u8 }`. + - **struct_variant** + - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. + +Many Serde serializers produce text or binary data as output, for example +JSON or Postcard. This is not a requirement of the `Serializer` trait, and +there are serializers that do not produce text or binary output. One example +is the `serde_json::value::Serializer` (distinct from the main `serde_json` +serializer) that produces a `serde_json::Value` data structure in memory as +output. + +[Serde data model]: https://serde.rs/data-model.html + +# Example implementation + +The [example data format] presented on the website contains example code for +a basic JSON `Serializer`. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait Serializer: Sized { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: The output type produced by this `Serializer` during successful +- `Error`: The error type when some error occurs during serialization. +- `SerializeSeq`: Type returned from [`serialize_seq`] for serializing the content of the +- `SerializeTuple`: Type returned from [`serialize_tuple`] for serializing the content of +- `SerializeTupleStruct`: Type returned from [`serialize_tuple_struct`] for serializing the +- `SerializeTupleVariant`: Type returned from [`serialize_tuple_variant`] for serializing the +- `SerializeMap`: Type returned from [`serialize_map`] for serializing the content of the +- `SerializeStruct`: Type returned from [`serialize_struct`] for serializing the content of +- `SerializeStructVariant`: Type returned from [`serialize_struct_variant`] for serializing the + +###### Required Methods + +- `serialize_bool`: Serialize a `bool` value. +- `serialize_i8`: Serialize an `i8` value. +- `serialize_i16`: Serialize an `i16` value. +- `serialize_i32`: Serialize an `i32` value. +- `serialize_i64`: Serialize an `i64` value. +- `serialize_u8`: Serialize a `u8` value. +- `serialize_u16`: Serialize a `u16` value. +- `serialize_u32`: Serialize a `u32` value. +- `serialize_u64`: Serialize a `u64` value. +- `serialize_f32`: Serialize an `f32` value. +- `serialize_f64`: Serialize an `f64` value. +- `serialize_char`: Serialize a character. +- `serialize_str`: Serialize a `&str`. +- `serialize_bytes`: Serialize a chunk of raw byte data. +- `serialize_none`: Serialize a [`None`] value. +- `serialize_some`: Serialize a [`Some(T)`] value. +- `serialize_unit`: Serialize a `()` value. +- `serialize_unit_struct`: Serialize a unit struct like `struct Unit` or `PhantomData`. +- `serialize_unit_variant`: Serialize a unit variant like `E::A` in `enum E { A, B }`. +- `serialize_newtype_struct`: Serialize a newtype struct like `struct Millimeters(u8)`. +- `serialize_newtype_variant`: Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. +- `serialize_seq`: Begin to serialize a variably sized sequence. This call must be +- `serialize_tuple`: Begin to serialize a statically sized sequence whose length will be +- `serialize_tuple_struct`: Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This +- `serialize_tuple_variant`: Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) +- `serialize_map`: Begin to serialize a map. This call must be followed by zero or more +- `serialize_struct`: Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. +- `serialize_struct_variant`: Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, + +##### Provided Methods + +- ```rust + fn serialize_i128(self: Self, v: i128) -> Result<::Ok, ::Error> { /* ... */ } + ``` + Serialize an `i128` value. + +- ```rust + fn serialize_u128(self: Self, v: u128) -> Result<::Ok, ::Error> { /* ... */ } + ``` + Serialize a `u128` value. + +- ```rust + fn collect_seq(self: Self, iter: I) -> Result<::Ok, ::Error> +where + I: IntoIterator, + ::Item: Serialize { /* ... */ } + ``` + Collect an iterator as a sequence. + +- ```rust + fn collect_map(self: Self, iter: I) -> Result<::Ok, ::Error> +where + K: Serialize, + V: Serialize, + I: IntoIterator { /* ... */ } + ``` + Collect an iterator as a map. + +- ```rust + fn collect_str(self: Self, value: &T) -> Result<::Ok, ::Error> +where + T: ?Sized + Display { /* ... */ } + ``` + Serialize a string produced by an implementation of `Display`. + +- ```rust + fn is_human_readable(self: &Self) -> bool { /* ... */ } + ``` + Determine whether `Serialize` implementations should serialize in + +##### Implementations + +This trait is implemented for the following types: + +- `&mut fmt::Formatter<''a>` with <''a> + +#### Trait `SerializeSeq` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeSeq` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeSeq` is not satisfied\",)]")` + +Returned from `Serializer::serialize_seq`. + +# Example use + +```edition2021 +# use std::marker::PhantomData; +# +# struct Vec(PhantomData); +# +# impl Vec { +# fn len(&self) -> usize { +# unimplemented!() +# } +# } +# +# impl<'a, T> IntoIterator for &'a Vec { +# type Item = &'a T; +# type IntoIter = Box>; +# fn into_iter(self) -> Self::IntoIter { +# unimplemented!() +# } +# } +# +use serde::ser::{Serialize, SerializeSeq, Serializer}; + +impl Serialize for Vec +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some(self.len()))?; + for element in self { + seq.serialize_element(element)?; + } + seq.end() + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeSeq` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeSeq { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_element`: Serialize a sequence element. +- `end`: Finish serializing a sequence. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeTuple` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTuple` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTuple` is not satisfied\",)]")` + +Returned from `Serializer::serialize_tuple`. + +# Example use + +```edition2021 +use serde::ser::{Serialize, SerializeTuple, Serializer}; + +# mod fool { +# trait Serialize {} +impl Serialize for (A, B, C) +# {} +# } +# +# struct Tuple3(A, B, C); +# +# impl Serialize for Tuple3 +where + A: Serialize, + B: Serialize, + C: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut tup = serializer.serialize_tuple(3)?; + tup.serialize_element(&self.0)?; + tup.serialize_element(&self.1)?; + tup.serialize_element(&self.2)?; + tup.end() + } +} +``` + +```edition2021 +# use std::marker::PhantomData; +# +# struct Array(PhantomData); +# +# impl Array { +# fn len(&self) -> usize { +# unimplemented!() +# } +# } +# +# impl<'a, T> IntoIterator for &'a Array { +# type Item = &'a T; +# type IntoIter = Box>; +# fn into_iter(self) -> Self::IntoIter { +# unimplemented!() +# } +# } +# +use serde::ser::{Serialize, SerializeTuple, Serializer}; + +# mod fool { +# trait Serialize {} +impl Serialize for [T; 16] +# {} +# } +# +# impl Serialize for Array +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_tuple(16)?; + for element in self { + seq.serialize_element(element)?; + } + seq.end() + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeTuple` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeTuple { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_element`: Serialize a tuple element. +- `end`: Finish serializing a tuple. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeTupleStruct` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTupleStruct` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTupleStruct` is not satisfied\",)]")` + +Returned from `Serializer::serialize_tuple_struct`. + +# Example use + +```edition2021 +use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; + +struct Rgb(u8, u8, u8); + +impl Serialize for Rgb { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; + ts.serialize_field(&self.0)?; + ts.serialize_field(&self.1)?; + ts.serialize_field(&self.2)?; + ts.end() + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeTupleStruct` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeTupleStruct { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_field`: Serialize a tuple struct field. +- `end`: Finish serializing a tuple struct. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeTupleVariant` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTupleVariant` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeTupleVariant` is not satisfied\",)]")` + +Returned from `Serializer::serialize_tuple_variant`. + +# Example use + +```edition2021 +use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; + +enum E { + T(u8, u8), + U(String, u32, u32), +} + +impl Serialize for E { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + E::T(ref a, ref b) => { + let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; + tv.serialize_field(a)?; + tv.serialize_field(b)?; + tv.end() + } + E::U(ref a, ref b, ref c) => { + let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; + tv.serialize_field(a)?; + tv.serialize_field(b)?; + tv.serialize_field(c)?; + tv.end() + } + } + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeTupleVariant` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeTupleVariant { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_field`: Serialize a tuple variant field. +- `end`: Finish serializing a tuple variant. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeMap` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeMap` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeMap` is not satisfied\",)]")` + +Returned from `Serializer::serialize_map`. + +# Example use + +```edition2021 +# use std::marker::PhantomData; +# +# struct HashMap(PhantomData, PhantomData); +# +# impl HashMap { +# fn len(&self) -> usize { +# unimplemented!() +# } +# } +# +# impl<'a, K, V> IntoIterator for &'a HashMap { +# type Item = (&'a K, &'a V); +# type IntoIter = Box>; +# +# fn into_iter(self) -> Self::IntoIter { +# unimplemented!() +# } +# } +# +use serde::ser::{Serialize, SerializeMap, Serializer}; + +impl Serialize for HashMap +where + K: Serialize, + V: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut map = serializer.serialize_map(Some(self.len()))?; + for (k, v) in self { + map.serialize_entry(k, v)?; + } + map.end() + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeMap` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeMap { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_key`: Serialize a map key. +- `serialize_value`: Serialize a map value. +- `end`: Finish serializing a map. + +##### Provided Methods + +- ```rust + fn serialize_entry(self: &mut Self, key: &K, value: &V) -> Result<(), ::Error> +where + K: ?Sized + Serialize, + V: ?Sized + Serialize { /* ... */ } + ``` + Serialize a map entry consisting of a key and a value. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeStruct` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeStruct` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeStruct` is not satisfied\",)]")` + +Returned from `Serializer::serialize_struct`. + +# Example use + +```edition2021 +use serde::ser::{Serialize, SerializeStruct, Serializer}; + +struct Rgb { + r: u8, + g: u8, + b: u8, +} + +impl Serialize for Rgb { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut rgb = serializer.serialize_struct("Rgb", 3)?; + rgb.serialize_field("r", &self.r)?; + rgb.serialize_field("g", &self.g)?; + rgb.serialize_field("b", &self.b)?; + rgb.end() + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeStruct` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeStruct { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_field`: Serialize a struct field. +- `end`: Finish serializing a struct. + +##### Provided Methods + +- ```rust + fn skip_field(self: &mut Self, key: &''static str) -> Result<(), ::Error> { /* ... */ } + ``` + Indicate that a struct field has been skipped. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +#### Trait `SerializeStructVariant` + +**Attributes:** + +- `Other("#[(not(no_diagnostic_namespace),\ndiagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeStructVariant` is not satisfied\",))]")` +- `Other("#[diagnostic::on_unimplemented(message =\n\"the trait bound `{Self}: serde::ser::SerializeStructVariant` is not satisfied\",)]")` + +Returned from `Serializer::serialize_struct_variant`. + +# Example use + +```edition2021 +use serde::ser::{Serialize, SerializeStructVariant, Serializer}; + +enum E { + S { r: u8, g: u8, b: u8 }, +} + +impl Serialize for E { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + E::S { + ref r, + ref g, + ref b, + } => { + let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; + sv.serialize_field("r", r)?; + sv.serialize_field("g", g)?; + sv.serialize_field("b", b)?; + sv.end() + } + } + } +} +``` + +# Example implementation + +The [example data format] presented on the website demonstrates an +implementation of `SerializeStructVariant` for a basic JSON data format. + +[example data format]: https://serde.rs/data-format.html + +```rust +pub trait SerializeStructVariant { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Associated Types + +- `Ok`: Must match the `Ok` type of our `Serializer`. +- `Error`: Must match the `Error` type of our `Serializer`. + +###### Required Methods + +- `serialize_field`: Serialize a struct variant field. +- `end`: Finish serializing a struct variant. + +##### Provided Methods + +- ```rust + fn skip_field(self: &mut Self, key: &''static str) -> Result<(), ::Error> { /* ... */ } + ``` + Indicate that a struct variant field has been skipped. + +##### Implementations + +This trait is implemented for the following types: + +- `Impossible` with + +### Re-exports + +#### Re-export `Impossible` + +```rust +pub use self::impossible::Impossible; +``` + +#### Re-export `Error` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::error::Error as StdError; +``` + +## Macros + +### Macro `forward_to_deserialize_any` + +**Attributes:** + +- `MacroExport` + +Helper macro when implementing the `Deserializer` part of a new data format +for Serde. + +Some [`Deserializer`] implementations for self-describing formats do not +care what hint the [`Visitor`] gives them, they just want to blindly call +the [`Visitor`] method corresponding to the data they can tell is in the +input. This requires repetitive implementations of all the [`Deserializer`] +trait methods. + +```edition2021 +# use serde::forward_to_deserialize_any; +# use serde::de::{value, Deserializer, Visitor}; +# +# struct MyDeserializer; +# +# impl<'de> Deserializer<'de> for MyDeserializer { +# type Error = value::Error; +# +# fn deserialize_any(self, _: V) -> Result +# where +# V: Visitor<'de>, +# { +# unimplemented!() +# } +# +#[inline] +fn deserialize_bool(self, visitor: V) -> Result +where + V: Visitor<'de>, +{ + self.deserialize_any(visitor) +} +# +# forward_to_deserialize_any! { +# i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string +# bytes byte_buf option unit unit_struct newtype_struct seq tuple +# tuple_struct map struct enum identifier ignored_any +# } +# } +``` + +The `forward_to_deserialize_any!` macro implements these simple forwarding +methods so that they forward directly to [`Deserializer::deserialize_any`]. +You can choose which methods to forward. + +```edition2021 +# use serde::forward_to_deserialize_any; +# use serde::de::{value, Deserializer, Visitor}; +# +# struct MyDeserializer; +# +impl<'de> Deserializer<'de> for MyDeserializer { +# type Error = value::Error; +# + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + /* ... */ +# let _ = visitor; +# unimplemented!() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} +``` + +The macro assumes the convention that your `Deserializer` lifetime parameter +is called `'de` and that the `Visitor` type parameters on each method are +called `V`. A different type parameter and a different lifetime can be +specified explicitly if necessary. + +```edition2021 +# use serde::forward_to_deserialize_any; +# use serde::de::{value, Deserializer, Visitor}; +# use std::marker::PhantomData; +# +# struct MyDeserializer(PhantomData); +# +# impl<'q, V> Deserializer<'q> for MyDeserializer { +# type Error = value::Error; +# +# fn deserialize_any(self, visitor: W) -> Result +# where +# W: Visitor<'q>, +# { +# unimplemented!() +# } +# +forward_to_deserialize_any! { + > + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any +} +# } +``` + +[`Deserializer`]: crate::Deserializer +[`Visitor`]: crate::de::Visitor +[`Deserializer::deserialize_any`]: crate::Deserializer::deserialize_any + +```rust +pub macro_rules! forward_to_deserialize_any { + /* macro_rules! forward_to_deserialize_any { + (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { ... }; + ($($func:ident)*) => { ... }; +} */ +} +``` + +## Re-exports + +### Re-export `Deserialize` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::Deserialize; +``` + +### Re-export `Deserializer` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::Deserializer; +``` + +### Re-export `Serialize` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::Serialize; +``` + +### Re-export `Serializer` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::Serializer; +``` + +### Re-export `Deserialize` + +**Attributes:** + +- `Other("#[(feature = \"serde_derive\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"derive\")))]")` +- `Other("#[doc(cfg(feature = \"derive\"))]")` + +Derive macro available if serde is built with `features = ["derive"]`. + +```rust +pub use serde_derive::Deserialize; +``` + +### Re-export `Serialize` + +**Attributes:** + +- `Other("#[(feature = \"serde_derive\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"derive\")))]")` +- `Other("#[doc(cfg(feature = \"derive\"))]")` + +Derive macro available if serde is built with `features = ["derive"]`. + +```rust +pub use serde_derive::Serialize; +``` + diff --git a/doc/serde_json.md b/doc/serde_json.md new file mode 100644 index 0000000..0f37b3e --- /dev/null +++ b/doc/serde_json.md @@ -0,0 +1,5643 @@ +# Crate Documentation + +**Version:** 1.0.145 + +**Format Version:** 56 + +# Module `serde_json` + +# Serde JSON + +JSON is a ubiquitous open-standard format that uses human-readable text to +transmit data objects consisting of key-value pairs. + +```json +{ + "name": "John Doe", + "age": 43, + "address": { + "street": "10 Downing Street", + "city": "London" + }, + "phones": [ + "+44 1234567", + "+44 2345678" + ] +} +``` + +There are three common ways that you might find yourself needing to work +with JSON data in Rust. + + - **As text data.** An unprocessed string of JSON data that you receive on + an HTTP endpoint, read from a file, or prepare to send to a remote + server. + - **As an untyped or loosely typed representation.** Maybe you want to + check that some JSON data is valid before passing it on, but without + knowing the structure of what it contains. Or you want to do very basic + manipulations like insert a key in a particular spot. + - **As a strongly typed Rust data structure.** When you expect all or most + of your data to conform to a particular structure and want to get real + work done without JSON's loosey-goosey nature tripping you up. + +Serde JSON provides efficient, flexible, safe ways of converting data +between each of these representations. + +# Operating on untyped JSON values + +Any valid JSON data can be manipulated in the following recursive enum +representation. This data structure is [`serde_json::Value`][value]. + +``` +# use serde_json::{Number, Map}; +# +# #[allow(dead_code)] +enum Value { + Null, + Bool(bool), + Number(Number), + String(String), + Array(Vec), + Object(Map), +} +``` + +A string of JSON data can be parsed into a `serde_json::Value` by the +[`serde_json::from_str`][from_str] function. There is also [`from_slice`] +for parsing from a byte slice `&[u8]` and [`from_reader`] for parsing from +any `io::Read` like a File or a TCP stream. + +``` +use serde_json::{Result, Value}; + +fn untyped_example() -> Result<()> { + // Some JSON input data as a &str. Maybe this comes from the user. + let data = r#" + { + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + + // Parse the string of data into serde_json::Value. + let v: Value = serde_json::from_str(data)?; + + // Access parts of the data by indexing with square brackets. + println!("Please call {} at the number {}", v["name"], v["phones"][0]); + + Ok(()) +} +# +# fn main() { +# untyped_example().unwrap(); +# } +``` + +The result of square bracket indexing like `v["name"]` is a borrow of the +data at that index, so the type is `&Value`. A JSON map can be indexed with +string keys, while a JSON array can be indexed with integer keys. If the +type of the data is not right for the type with which it is being indexed, +or if a map does not contain the key being indexed, or if the index into a +vector is out of bounds, the returned element is `Value::Null`. + +When a `Value` is printed, it is printed as a JSON string. So in the code +above, the output looks like `Please call "John Doe" at the number "+44 +1234567"`. The quotation marks appear because `v["name"]` is a `&Value` +containing a JSON string and its JSON representation is `"John Doe"`. +Printing as a plain string without quotation marks involves converting from +a JSON string to a Rust string with [`as_str()`] or avoiding the use of +`Value` as described in the following section. + +[`as_str()`]: crate::Value::as_str + +The `Value` representation is sufficient for very basic tasks but can be +tedious to work with for anything more significant. Error handling is +verbose to implement correctly, for example imagine trying to detect the +presence of unrecognized fields in the input data. The compiler is powerless +to help you when you make a mistake, for example imagine typoing `v["name"]` +as `v["nmae"]` in one of the dozens of places it is used in your code. + +# Parsing JSON as strongly typed data structures + +Serde provides a powerful way of mapping JSON data into Rust data structures +largely automatically. + +``` +use serde::{Deserialize, Serialize}; +use serde_json::Result; + +#[derive(Serialize, Deserialize)] +struct Person { + name: String, + age: u8, + phones: Vec, +} + +fn typed_example() -> Result<()> { + // Some JSON input data as a &str. Maybe this comes from the user. + let data = r#" + { + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + + // Parse the string of data into a Person object. This is exactly the + // same function as the one that produced serde_json::Value above, but + // now we are asking it for a Person as output. + let p: Person = serde_json::from_str(data)?; + + // Do things just like with any other Rust data structure. + println!("Please call {} at the number {}", p.name, p.phones[0]); + + Ok(()) +} +# +# fn main() { +# typed_example().unwrap(); +# } +``` + +This is the same `serde_json::from_str` function as before, but this time we +assign the return value to a variable of type `Person` so Serde will +automatically interpret the input data as a `Person` and produce informative +error messages if the layout does not conform to what a `Person` is expected +to look like. + +Any type that implements Serde's `Deserialize` trait can be deserialized +this way. This includes built-in Rust standard library types like `Vec` +and `HashMap`, as well as any structs or enums annotated with +`#[derive(Deserialize)]`. + +Once we have `p` of type `Person`, our IDE and the Rust compiler can help us +use it correctly like they do for any other Rust code. The IDE can +autocomplete field names to prevent typos, which was impossible in the +`serde_json::Value` representation. And the Rust compiler can check that +when we write `p.phones[0]`, then `p.phones` is guaranteed to be a +`Vec` so indexing into it makes sense and produces a `String`. + +# Constructing JSON values + +Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +objects with very natural JSON syntax. + +``` +use serde_json::json; + +fn main() { + // The type of `john` is `serde_json::Value` + let john = json!({ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }); + + println!("first phone number: {}", john["phones"][0]); + + // Convert to a string of JSON and print it out + println!("{}", john.to_string()); +} +``` + +The `Value::to_string()` function converts a `serde_json::Value` into a +`String` of JSON text. + +One neat thing about the `json!` macro is that variables and expressions can +be interpolated directly into the JSON value as you are building it. Serde +will check at compile time that the value you are interpolating is able to +be represented as JSON. + +``` +# use serde_json::json; +# +# fn random_phone() -> u16 { 0 } +# +let full_name = "John Doe"; +let age_last_year = 42; + +// The type of `john` is `serde_json::Value` +let john = json!({ + "name": full_name, + "age": age_last_year + 1, + "phones": [ + format!("+44 {}", random_phone()) + ] +}); +``` + +This is amazingly convenient, but we have the problem we had before with +`Value`: the IDE and Rust compiler cannot help us if we get it wrong. Serde +JSON provides a better way of serializing strongly-typed data structures +into JSON text. + +# Creating JSON by serializing data structures + +A data structure can be converted to a JSON string by +[`serde_json::to_string`][to_string]. There is also +[`serde_json::to_vec`][to_vec] which serializes to a `Vec` and +[`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +such as a File or a TCP stream. + +``` +use serde::{Deserialize, Serialize}; +use serde_json::Result; + +#[derive(Serialize, Deserialize)] +struct Address { + street: String, + city: String, +} + +fn print_an_address() -> Result<()> { + // Some data structure. + let address = Address { + street: "10 Downing Street".to_owned(), + city: "London".to_owned(), + }; + + // Serialize it to a JSON string. + let j = serde_json::to_string(&address)?; + + // Print, write to a file, or send to an HTTP server. + println!("{}", j); + + Ok(()) +} +# +# fn main() { +# print_an_address().unwrap(); +# } +``` + +Any type that implements Serde's `Serialize` trait can be serialized this +way. This includes built-in Rust standard library types like `Vec` and +`HashMap`, as well as any structs or enums annotated with +`#[derive(Serialize)]`. + +# No-std support + +As long as there is a memory allocator, it is possible to use serde_json +without the rest of the Rust standard library. Disable the default "std" +feature and enable the "alloc" feature: + +```toml +[dependencies] +serde_json = { version = "1.0", default-features = false, features = ["alloc"] } +``` + +For JSON support in Serde without a memory allocator, please see the +[`serde-json-core`] crate. + +[value]: crate::value::Value +[from_str]: crate::de::from_str +[from_slice]: crate::de::from_slice +[from_reader]: crate::de::from_reader +[to_string]: crate::ser::to_string +[to_vec]: crate::ser::to_vec +[to_writer]: crate::ser::to_writer +[macro]: crate::json +[`serde-json-core`]: https://github.com/rust-embedded-community/serde-json-core + +## Modules + +## Module `de` + +Deserialize JSON data to a Rust data structure. + +```rust +pub mod de { /* ... */ } +``` + +### Types + +#### Struct `Deserializer` + +A structure that deserializes JSON into Rust values. + +```rust +pub struct Deserializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(read: R) -> Self { /* ... */ } + ``` + Create a JSON deserializer from one of the possible serde_json input + +- ```rust + pub fn from_reader(reader: R) -> Self { /* ... */ } + ``` + Creates a JSON deserializer from an `io::Read`. + +- ```rust + pub fn from_slice(bytes: &''a [u8]) -> Self { /* ... */ } + ``` + Creates a JSON deserializer from a `&[u8]`. + +- ```rust + pub fn from_str(s: &''a str) -> Self { /* ... */ } + ``` + Creates a JSON deserializer from a `&str`. + +- ```rust + pub fn end(self: &mut Self) -> Result<()> { /* ... */ } + ``` + The `Deserializer::end` method should be called after a value has been fully deserialized. + +- ```rust + pub fn into_iter(self: Self) -> StreamDeserializer<''de, R, T> +where + T: de::Deserialize<''de> { /* ... */ } + ``` + Turn a JSON deserializer into an iterator over values of type T. + +- ```rust + pub fn disable_recursion_limit(self: &mut Self) { /* ... */ } + ``` + Parse arbitrarily deep JSON structures without any consideration for + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + Parses a JSON string as bytes. Note that this function does not check + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + Parses a `null` as a None, and any other values as a `Some(...)`. + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, _name: &''static str, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &str, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + Parses a newtype struct as the underlying value. + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, _len: usize, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, _name: &''static str, _len: usize, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, _name: &''static str, _fields: &''static [&''static str], visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, _name: &str, _variants: &''static [&''static str], visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> Result<::Value> +where + V: de::Visitor<''de> { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `StreamDeserializer` + +Iterator that deserializes a stream into multiple JSON values. + +A stream deserializer can be created from any JSON deserializer using the +`Deserializer::into_iter` method. + +The data can consist of any JSON value. Values need to be a self-delineating value e.g. +arrays, objects, or strings, or be followed by whitespace or a self-delineating value. + +``` +use serde_json::{Deserializer, Value}; + +fn main() { + let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; + + let stream = Deserializer::from_str(data).into_iter::(); + + for value in stream { + println!("{}", value.unwrap()); + } +} +``` + +```rust +pub struct StreamDeserializer<''de, R, T> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(read: R) -> Self { /* ... */ } + ``` + Create a JSON stream deserializer from one of the possible serde_json + +- ```rust + pub fn byte_offset(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of bytes so far deserialized into a successful `T`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option> { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Functions + +#### Function `from_reader` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` + +Deserialize an instance of type `T` from an I/O stream of JSON. + +The content of the I/O stream is deserialized directly from the stream +without being buffered in memory by serde_json. + +When reading from a source against which short reads are not efficient, such +as a [`File`], you will want to apply your own buffering because serde_json +will not buffer the input. See [`std::io::BufReader`]. + +It is expected that the input stream ends after the deserialized object. +If the stream does not end, such as in the case of a persistent socket connection, +this function will not return. It is possible instead to deserialize from a prefix of an input +stream without looking for EOF by managing your own [`Deserializer`]. + +Note that counter to intuition, this function is usually slower than +reading a file completely into memory and then applying [`from_str`] +or [`from_slice`] on it. See [issue #160]. + +[`File`]: std::fs::File +[issue #160]: https://github.com/serde-rs/json/issues/160 + +# Example + +Reading the contents of a file. + +``` +use serde::Deserialize; + +use std::error::Error; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; + +#[derive(Deserialize, Debug)] +struct User { + fingerprint: String, + location: String, +} + +fn read_user_from_file>(path: P) -> Result> { + // Open the file in read-only mode with buffer. + let file = File::open(path)?; + let reader = BufReader::new(file); + + // Read the JSON contents of the file as an instance of `User`. + let u = serde_json::from_reader(reader)?; + + // Return the `User`. + Ok(u) +} + +fn main() { +# } +# fn fake_main() { + let u = read_user_from_file("test.json").unwrap(); + println!("{:#?}", u); +} +``` + +Reading from a persistent socket connection. + +``` +use serde::Deserialize; + +use std::error::Error; +use std::io::BufReader; +use std::net::{TcpListener, TcpStream}; + +#[derive(Deserialize, Debug)] +struct User { + fingerprint: String, + location: String, +} + +fn read_user_from_stream(stream: &mut BufReader) -> Result> { + let mut de = serde_json::Deserializer::from_reader(stream); + let u = User::deserialize(&mut de)?; + + Ok(u) +} + +fn main() { +# } +# fn fake_main() { + let listener = TcpListener::bind("127.0.0.1:4000").unwrap(); + + for tcp_stream in listener.incoming() { + let mut buffered = BufReader::new(tcp_stream.unwrap()); + println!("{:#?}", read_user_from_stream(&mut buffered)); + } +} +``` + +# Errors + +This conversion can fail if the structure of the input does not match the +structure expected by `T`, for example if `T` is a struct type but the input +contains something other than a JSON map. It can also fail if the structure +is correct but `T`'s implementation of `Deserialize` decides that something +is wrong with the data, for example required struct fields are missing from +the JSON map or some number is too big to fit in the expected primitive +type. + +```rust +pub fn from_reader(rdr: R) -> crate::error::Result +where + R: crate::io::Read, + T: de::DeserializeOwned { /* ... */ } +``` + +#### Function `from_slice` + +Deserialize an instance of type `T` from bytes of JSON text. + +# Example + +``` +use serde::Deserialize; + +#[derive(Deserialize, Debug)] +struct User { + fingerprint: String, + location: String, +} + +fn main() { + // The type of `j` is `&[u8]` + let j = b" + { + \"fingerprint\": \"0xF9BA143B95FF6D82\", + \"location\": \"Menlo Park, CA\" + }"; + + let u: User = serde_json::from_slice(j).unwrap(); + println!("{:#?}", u); +} +``` + +# Errors + +This conversion can fail if the structure of the input does not match the +structure expected by `T`, for example if `T` is a struct type but the input +contains something other than a JSON map. It can also fail if the structure +is correct but `T`'s implementation of `Deserialize` decides that something +is wrong with the data, for example required struct fields are missing from +the JSON map or some number is too big to fit in the expected primitive +type. + +```rust +pub fn from_slice<''a, T>(v: &''a [u8]) -> crate::error::Result +where + T: de::Deserialize<''a> { /* ... */ } +``` + +#### Function `from_str` + +Deserialize an instance of type `T` from a string of JSON text. + +# Example + +``` +use serde::Deserialize; + +#[derive(Deserialize, Debug)] +struct User { + fingerprint: String, + location: String, +} + +fn main() { + // The type of `j` is `&str` + let j = " + { + \"fingerprint\": \"0xF9BA143B95FF6D82\", + \"location\": \"Menlo Park, CA\" + }"; + + let u: User = serde_json::from_str(j).unwrap(); + println!("{:#?}", u); +} +``` + +# Errors + +This conversion can fail if the structure of the input does not match the +structure expected by `T`, for example if `T` is a struct type but the input +contains something other than a JSON map. It can also fail if the structure +is correct but `T`'s implementation of `Deserialize` decides that something +is wrong with the data, for example required struct fields are missing from +the JSON map or some number is too big to fit in the expected primitive +type. + +```rust +pub fn from_str<''a, T>(s: &''a str) -> crate::error::Result +where + T: de::Deserialize<''a> { /* ... */ } +``` + +### Re-exports + +#### Re-export `Read` + +```rust +pub use crate::read::Read; +``` + +#### Re-export `SliceRead` + +```rust +pub use crate::read::SliceRead; +``` + +#### Re-export `StrRead` + +```rust +pub use crate::read::StrRead; +``` + +#### Re-export `IoRead` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` + +```rust +pub use crate::read::IoRead; +``` + +## Module `error` + +When serializing or deserializing JSON goes wrong. + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `Error` + +This type represents all possible errors that can occur when serializing or +deserializing JSON data. + +```rust +pub struct Error { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn line(self: &Self) -> usize { /* ... */ } + ``` + One-based line number at which the error was detected. + +- ```rust + pub fn column(self: &Self) -> usize { /* ... */ } + ``` + One-based column number at which the error was detected. + +- ```rust + pub fn classify(self: &Self) -> Category { /* ... */ } + ``` + Categorizes the cause of this error. + +- ```rust + pub fn is_io(self: &Self) -> bool { /* ... */ } + ``` + Returns true if this error was caused by a failure to read or write + +- ```rust + pub fn is_syntax(self: &Self) -> bool { /* ... */ } + ``` + Returns true if this error was caused by input that was not + +- ```rust + pub fn is_data(self: &Self) -> bool { /* ... */ } + ``` + Returns true if this error was caused by input data that was + +- ```rust + pub fn is_eof(self: &Self) -> bool { /* ... */ } + ``` + Returns true if this error was caused by prematurely reaching the end of + +- ```rust + pub fn io_error_kind(self: &Self) -> Option { /* ... */ } + ``` + The kind reported by the underlying standard library I/O error, if this + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Error** + - ```rust + fn source(self: &Self) -> Option<&dyn error::Error + ''static> { /* ... */ } + ``` + + - ```rust + fn custom(msg: T) -> Error { /* ... */ } + ``` + + - ```rust + fn invalid_type(unexp: de::Unexpected<''_>, exp: &dyn de::Expected) -> Self { /* ... */ } + ``` + + - ```rust + fn invalid_value(unexp: de::Unexpected<''_>, exp: &dyn de::Expected) -> Self { /* ... */ } + ``` + + - ```rust + fn custom(msg: T) -> Error { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(j: Error) -> Self { /* ... */ } + ``` + Convert a `serde_json::Error` into an `io::Error`. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Type Alias `Result` + +Alias for a `Result` with the error type `serde_json::Error`. + +```rust +pub type Result = result::Result; +``` + +#### Enum `Category` + +Categorizes the cause of a `serde_json::Error`. + +```rust +pub enum Category { + Io, + Syntax, + Data, + Eof, +} +``` + +##### Variants + +###### `Io` + +The error was caused by a failure to read or write bytes on an I/O +stream. + +###### `Syntax` + +The error was caused by input that was not syntactically valid JSON. + +###### `Data` + +The error was caused by input data that was semantically incorrect. + +For example, JSON containing a number is semantically incorrect when the +type being deserialized into holds a String. + +###### `Eof` + +The error was caused by prematurely reaching the end of the input data. + +Callers that process streaming input may be interested in retrying the +deserialization once more data is available. + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Category { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Category) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +## Module `map` + +A map of String to serde_json::Value. + +By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order` +feature of serde_json to use [`IndexMap`] instead. + +[`BTreeMap`]: std::collections::BTreeMap +[`IndexMap`]: indexmap::IndexMap + +```rust +pub mod map { /* ... */ } +``` + +### Types + +#### Struct `Map` + +Represents a JSON key/value type. + +```rust +pub struct Map { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Makes a new empty Map. + +- ```rust + pub fn with_capacity(capacity: usize) -> Self { /* ... */ } + ``` + Makes a new empty Map with the given initial capacity. + +- ```rust + pub fn clear(self: &mut Self) { /* ... */ } + ``` + Clears the map, removing all values. + +- ```rust + pub fn get(self: &Self, key: &Q) -> Option<&Value> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Returns a reference to the value corresponding to the key. + +- ```rust + pub fn contains_key(self: &Self, key: &Q) -> bool +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Returns true if the map contains a value for the specified key. + +- ```rust + pub fn get_mut(self: &mut Self, key: &Q) -> Option<&mut Value> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Returns a mutable reference to the value corresponding to the key. + +- ```rust + pub fn get_key_value(self: &Self, key: &Q) -> Option<(&String, &Value)> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Returns the key-value pair matching the given key. + +- ```rust + pub fn insert(self: &mut Self, k: String, v: Value) -> Option { /* ... */ } + ``` + Inserts a key-value pair into the map. + +- ```rust + pub fn shift_insert(self: &mut Self, index: usize, k: String, v: Value) -> Option { /* ... */ } + ``` + Insert a key-value pair in the map at the given index. + +- ```rust + pub fn remove(self: &mut Self, key: &Q) -> Option +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Removes a key from the map, returning the value at the key if the key + +- ```rust + pub fn remove_entry(self: &mut Self, key: &Q) -> Option<(String, Value)> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Removes a key from the map, returning the stored key and value if the + +- ```rust + pub fn swap_remove(self: &mut Self, key: &Q) -> Option +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Removes and returns the value corresponding to the key from the map. + +- ```rust + pub fn swap_remove_entry(self: &mut Self, key: &Q) -> Option<(String, Value)> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Remove and return the key-value pair. + +- ```rust + pub fn shift_remove(self: &mut Self, key: &Q) -> Option +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Removes and returns the value corresponding to the key from the map. + +- ```rust + pub fn shift_remove_entry(self: &mut Self, key: &Q) -> Option<(String, Value)> +where + String: Borrow, + Q: ?Sized + Ord + Eq + Hash { /* ... */ } + ``` + Remove and return the key-value pair. + +- ```rust + pub fn append(self: &mut Self, other: &mut Self) { /* ... */ } + ``` + Moves all elements from other into self, leaving other empty. + +- ```rust + pub fn entry(self: &mut Self, key: S) -> Entry<''_> +where + S: Into { /* ... */ } + ``` + Gets the given key's corresponding entry in the map for in-place + +- ```rust + pub fn len(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of elements in the map. + +- ```rust + pub fn is_empty(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the map contains no elements. + +- ```rust + pub fn iter(self: &Self) -> Iter<''_> { /* ... */ } + ``` + Gets an iterator over the entries of the map. + +- ```rust + pub fn iter_mut(self: &mut Self) -> IterMut<''_> { /* ... */ } + ``` + Gets a mutable iterator over the entries of the map. + +- ```rust + pub fn keys(self: &Self) -> Keys<''_> { /* ... */ } + ``` + Gets an iterator over the keys of the map. + +- ```rust + pub fn values(self: &Self) -> Values<''_> { /* ... */ } + ``` + Gets an iterator over the values of the map. + +- ```rust + pub fn values_mut(self: &mut Self) -> ValuesMut<''_> { /* ... */ } + ``` + Gets an iterator over mutable values of the map. + +- ```rust + pub fn into_values(self: Self) -> IntoValues { /* ... */ } + ``` + Gets an iterator over the values of the map. + +- ```rust + pub fn retain(self: &mut Self, f: F) +where + F: FnMut(&String, &mut Value) -> bool { /* ... */ } + ``` + Retains only the elements specified by the predicate. + +- ```rust + pub fn sort_keys(self: &mut Self) { /* ... */ } + ``` + Sorts this map's entries in-place using `str`'s usual ordering. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + + - ```rust + fn clone_from(self: &mut Self, source: &Self) { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> Result<(), fmt::Error> { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Deserialize** + - ```rust + fn deserialize(deserializer: D) -> Result::Error> +where + D: de::Deserializer<''de> { /* ... */ } + ``` + +- **DeserializeOwned** +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, _name: &''static str, _variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, _name: &''static str, _variants: &''static [&''static str], visitor: V) -> Result<::Value, ::Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, name: &''static str, len: usize, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, name: &''static str, fields: &''static [&''static str], visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> $crate::__private::Result<::Value, >::Error> +where + V: $crate::de::Visitor<''de> { /* ... */ } + ``` + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Extend** + - ```rust + fn extend(self: &mut Self, iter: T) +where + T: IntoIterator { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(f: Map) -> Self { /* ... */ } + ``` + Convert map (with string keys) to `Value::Object`. + +- **FromIterator** + - ```rust + fn from_iter(iter: T) -> Self +where + T: IntoIterator { /* ... */ } + ``` + +- **FromStr** + - ```rust + fn from_str(s: &str) -> Result { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash(self: &Self, state: &mut H) { /* ... */ } + ``` + +- **Index** + - ```rust + fn index(self: &Self, index: &Q) -> &Value { /* ... */ } + ``` + +- **IndexMut** + - ```rust + fn index_mut(self: &mut Self, index: &Q) -> &mut Value { /* ... */ } + ``` + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> ::IntoIter { /* ... */ } + ``` + + - ```rust + fn into_iter(self: Self) -> ::IntoIter { /* ... */ } + ``` + + - ```rust + fn into_iter(self: Self) -> ::IntoIter { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Self) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize(self: &Self, serializer: S) -> Result<::Ok, ::Error> +where + S: serde::ser::Serializer { /* ... */ } + ``` + +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `Entry` + +A view into a single entry in a map, which may either be vacant or occupied. +This enum is constructed from the [`entry`] method on [`Map`]. + +[`entry`]: Map::entry + +```rust +pub enum Entry<''a> { + Vacant(VacantEntry<''a>), + Occupied(OccupiedEntry<''a>), +} +``` + +##### Variants + +###### `Vacant` + +A vacant Entry. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `VacantEntry<''a>` | | + +###### `Occupied` + +An occupied Entry. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `OccupiedEntry<''a>` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn key(self: &Self) -> &String { /* ... */ } + ``` + Returns a reference to this entry's key. + +- ```rust + pub fn or_insert(self: Self, default: Value) -> &''a mut Value { /* ... */ } + ``` + Ensures a value is in the entry by inserting the default if empty, and + +- ```rust + pub fn or_insert_with(self: Self, default: F) -> &''a mut Value +where + F: FnOnce() -> Value { /* ... */ } + ``` + Ensures a value is in the entry by inserting the result of the default + +- ```rust + pub fn and_modify(self: Self, f: F) -> Self +where + F: FnOnce(&mut Value) { /* ... */ } + ``` + Provides in-place mutable access to an occupied entry before any + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `VacantEntry` + +A vacant Entry. It is part of the [`Entry`] enum. + +```rust +pub struct VacantEntry<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn key(self: &Self) -> &String { /* ... */ } + ``` + Gets a reference to the key that would be used when inserting a value + +- ```rust + pub fn insert(self: Self, value: Value) -> &''a mut Value { /* ... */ } + ``` + Sets the value of the entry with the VacantEntry's key, and returns a + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `OccupiedEntry` + +An occupied Entry. It is part of the [`Entry`] enum. + +```rust +pub struct OccupiedEntry<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn key(self: &Self) -> &String { /* ... */ } + ``` + Gets a reference to the key in the entry. + +- ```rust + pub fn get(self: &Self) -> &Value { /* ... */ } + ``` + Gets a reference to the value in the entry. + +- ```rust + pub fn get_mut(self: &mut Self) -> &mut Value { /* ... */ } + ``` + Gets a mutable reference to the value in the entry. + +- ```rust + pub fn into_mut(self: Self) -> &''a mut Value { /* ... */ } + ``` + Converts the entry into a mutable reference to its value. + +- ```rust + pub fn insert(self: &mut Self, value: Value) -> Value { /* ... */ } + ``` + Sets the value of the entry with the `OccupiedEntry`'s key, and returns + +- ```rust + pub fn remove(self: Self) -> Value { /* ... */ } + ``` + Takes the value of the entry out of the map, and returns it. + +- ```rust + pub fn swap_remove(self: Self) -> Value { /* ... */ } + ``` + Takes the value of the entry out of the map, and returns it. + +- ```rust + pub fn shift_remove(self: Self) -> Value { /* ... */ } + ``` + Takes the value of the entry out of the map, and returns it. + +- ```rust + pub fn remove_entry(self: Self) -> (String, Value) { /* ... */ } + ``` + Removes the entry from the map, returning the stored key and value. + +- ```rust + pub fn swap_remove_entry(self: Self) -> (String, Value) { /* ... */ } + ``` + Removes the entry from the map, returning the stored key and value. + +- ```rust + pub fn shift_remove_entry(self: Self) -> (String, Value) { /* ... */ } + ``` + Removes the entry from the map, returning the stored key and value. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `Iter` + +An iterator over a serde_json::Map's entries. + +```rust +pub struct Iter<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Iter<''a> { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `IterMut` + +A mutable iterator over a serde_json::Map's entries. + +```rust +pub struct IterMut<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `IntoIter` + +An owning iterator over a serde_json::Map's entries. + +```rust +pub struct IntoIter { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `Keys` + +An iterator over a serde_json::Map's keys. + +```rust +pub struct Keys<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Keys<''a> { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `Values` + +An iterator over a serde_json::Map's values. + +```rust +pub struct Values<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Values<''a> { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `ValuesMut` + +A mutable iterator over a serde_json::Map's values. + +```rust +pub struct ValuesMut<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `IntoValues` + +An owning iterator over a serde_json::Map's values. + +```rust +pub struct IntoValues { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **DoubleEndedIterator** + - ```rust + fn next_back(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + +- **ExactSizeIterator** + - ```rust + fn len(self: &Self) -> usize { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FusedIterator** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoIterator** + - ```rust + fn into_iter(self: Self) -> I { /* ... */ } + ``` + +- **Iterator** + - ```rust + fn next(self: &mut Self) -> Option<::Item> { /* ... */ } + ``` + + - ```rust + fn size_hint(self: &Self) -> (usize, Option) { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +## Module `ser` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` + +Serialize a Rust data structure into JSON data. + +```rust +pub mod ser { /* ... */ } +``` + +### Types + +#### Struct `Serializer` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` + +A structure for serializing Rust values into JSON. + +```rust +pub struct Serializer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(writer: W) -> Self { /* ... */ } + ``` + Creates a new JSON serializer. + +- ```rust + pub fn pretty(writer: W) -> Self { /* ... */ } + ``` + Creates a new JSON pretty print serializer. + +- ```rust + pub fn with_formatter(writer: W, formatter: F) -> Self { /* ... */ } + ``` + Creates a new JSON visitor whose output will be written to the writer + +- ```rust + pub fn into_inner(self: Self) -> W { /* ... */ } + ``` + Unwrap the `Writer` from the `Serializer`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Serializer** + - ```rust + fn serialize_bool(self: Self, value: bool) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_i8(self: Self, value: i8) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_i16(self: Self, value: i16) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_i32(self: Self, value: i32) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_i64(self: Self, value: i64) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_i128(self: Self, value: i128) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_u8(self: Self, value: u8) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_u16(self: Self, value: u16) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_u32(self: Self, value: u32) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_u64(self: Self, value: u64) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_u128(self: Self, value: u128) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_f32(self: Self, value: f32) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_f64(self: Self, value: f64) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_char(self: Self, value: char) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_str(self: Self, value: &str) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_bytes(self: Self, value: &[u8]) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_unit(self: Self) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_unit_struct(self: Self, _name: &''static str) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_unit_variant(self: Self, _name: &''static str, _variant_index: u32, variant: &''static str) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_newtype_struct(self: Self, _name: &''static str, value: &T) -> Result<()> +where + T: ?Sized + Serialize { /* ... */ } + ``` + Serialize newtypes without an object wrapper. + + - ```rust + fn serialize_newtype_variant(self: Self, _name: &''static str, _variant_index: u32, variant: &''static str, value: &T) -> Result<()> +where + T: ?Sized + Serialize { /* ... */ } + ``` + + - ```rust + fn serialize_none(self: Self) -> Result<()> { /* ... */ } + ``` + + - ```rust + fn serialize_some(self: Self, value: &T) -> Result<()> +where + T: ?Sized + Serialize { /* ... */ } + ``` + + - ```rust + fn serialize_seq(self: Self, len: Option) -> Result<::SerializeSeq> { /* ... */ } + ``` + + - ```rust + fn serialize_tuple(self: Self, len: usize) -> Result<::SerializeTuple> { /* ... */ } + ``` + + - ```rust + fn serialize_tuple_struct(self: Self, _name: &''static str, len: usize) -> Result<::SerializeTupleStruct> { /* ... */ } + ``` + + - ```rust + fn serialize_tuple_variant(self: Self, _name: &''static str, _variant_index: u32, variant: &''static str, len: usize) -> Result<::SerializeTupleVariant> { /* ... */ } + ``` + + - ```rust + fn serialize_map(self: Self, len: Option) -> Result<::SerializeMap> { /* ... */ } + ``` + + - ```rust + fn serialize_struct(self: Self, name: &''static str, len: usize) -> Result<::SerializeStruct> { /* ... */ } + ``` + + - ```rust + fn serialize_struct_variant(self: Self, _name: &''static str, _variant_index: u32, variant: &''static str, len: usize) -> Result<::SerializeStructVariant> { /* ... */ } + ``` + + - ```rust + fn collect_str(self: Self, value: &T) -> Result<()> +where + T: ?Sized + Display { /* ... */ } + ``` + +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Enum `CharEscape` + +Represents a character escape code in a type-safe manner. + +```rust +pub enum CharEscape { + Quote, + ReverseSolidus, + Solidus, + Backspace, + FormFeed, + LineFeed, + CarriageReturn, + Tab, + AsciiControl(u8), +} +``` + +##### Variants + +###### `Quote` + +An escaped quote `"` + +###### `ReverseSolidus` + +An escaped reverse solidus `\` + +###### `Solidus` + +An escaped solidus `/` + +###### `Backspace` + +An escaped backspace character (usually escaped as `\b`) + +###### `FormFeed` + +An escaped form feed character (usually escaped as `\f`) + +###### `LineFeed` + +An escaped line feed character (usually escaped as `\n`) + +###### `CarriageReturn` + +An escaped carriage return character (usually escaped as `\r`) + +###### `Tab` + +An escaped tab character (usually escaped as `\t`) + +###### `AsciiControl` + +An escaped ASCII plane control character (usually escaped as +`\u00XX` where `XX` are two hex characters) + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `u8` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `CompactFormatter` + +This structure compacts a JSON value with no extra whitespace. + +```rust +pub struct CompactFormatter; +``` + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> CompactFormatter { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> CompactFormatter { /* ... */ } + ``` + +- **Formatter** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +#### Struct `PrettyFormatter` + +This structure pretty prints a JSON value to make it human readable. + +```rust +pub struct PrettyFormatter<''a> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Construct a pretty printer formatter that defaults to using two spaces for indentation. + +- ```rust + pub fn with_indent(indent: &''a [u8]) -> Self { /* ... */ } + ``` + Construct a pretty printer formatter that uses the `indent` string for indentation. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> PrettyFormatter<''a> { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Formatter** + - ```rust + fn begin_array(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn end_array(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn begin_array_value(self: &mut Self, writer: &mut W, first: bool) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn end_array_value(self: &mut Self, _writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn begin_object(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn end_object(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn begin_object_key(self: &mut Self, writer: &mut W, first: bool) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn begin_object_value(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + + - ```rust + fn end_object_value(self: &mut Self, _writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Traits + +#### Trait `Formatter` + +This trait abstracts away serializing the JSON control characters, which allows the user to +optionally pretty print the JSON output. + +```rust +pub trait Formatter { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Provided Methods + +- ```rust + fn write_null(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a `null` value to the specified writer. + +- ```rust + fn write_bool(self: &mut Self, writer: &mut W, value: bool) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a `true` or `false` value to the specified writer. + +- ```rust + fn write_i8(self: &mut Self, writer: &mut W, value: i8) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `-123` to the specified writer. + +- ```rust + fn write_i16(self: &mut Self, writer: &mut W, value: i16) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `-123` to the specified writer. + +- ```rust + fn write_i32(self: &mut Self, writer: &mut W, value: i32) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `-123` to the specified writer. + +- ```rust + fn write_i64(self: &mut Self, writer: &mut W, value: i64) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `-123` to the specified writer. + +- ```rust + fn write_i128(self: &mut Self, writer: &mut W, value: i128) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `-123` to the specified writer. + +- ```rust + fn write_u8(self: &mut Self, writer: &mut W, value: u8) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `123` to the specified writer. + +- ```rust + fn write_u16(self: &mut Self, writer: &mut W, value: u16) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `123` to the specified writer. + +- ```rust + fn write_u32(self: &mut Self, writer: &mut W, value: u32) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `123` to the specified writer. + +- ```rust + fn write_u64(self: &mut Self, writer: &mut W, value: u64) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `123` to the specified writer. + +- ```rust + fn write_u128(self: &mut Self, writer: &mut W, value: u128) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes an integer value like `123` to the specified writer. + +- ```rust + fn write_f32(self: &mut Self, writer: &mut W, value: f32) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a floating point value like `-31.26e+12` to the specified writer. + +- ```rust + fn write_f64(self: &mut Self, writer: &mut W, value: f64) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a floating point value like `-31.26e+12` to the specified writer. + +- ```rust + fn write_number_str(self: &mut Self, writer: &mut W, value: &str) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a number that has already been rendered to a string. + +- ```rust + fn begin_string(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before each series of `write_string_fragment` and + +- ```rust + fn end_string(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after each series of `write_string_fragment` and + +- ```rust + fn write_string_fragment(self: &mut Self, writer: &mut W, fragment: &str) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a string fragment that doesn't need any escaping to the + +- ```rust + fn write_char_escape(self: &mut Self, writer: &mut W, char_escape: CharEscape) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a character escape code to the specified writer. + +- ```rust + fn write_byte_array(self: &mut Self, writer: &mut W, value: &[u8]) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes the representation of a byte array. Formatters can choose whether + +- ```rust + fn begin_array(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before every array. Writes a `[` to the specified + +- ```rust + fn end_array(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after every array. Writes a `]` to the specified + +- ```rust + fn begin_array_value(self: &mut Self, writer: &mut W, first: bool) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before every array value. Writes a `,` if needed to + +- ```rust + fn end_array_value(self: &mut Self, _writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after every array value. + +- ```rust + fn begin_object(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before every object. Writes a `{` to the specified + +- ```rust + fn end_object(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after every object. Writes a `}` to the specified + +- ```rust + fn begin_object_key(self: &mut Self, writer: &mut W, first: bool) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before every object key. + +- ```rust + fn end_object_key(self: &mut Self, _writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after every object key. A `:` should be written to the + +- ```rust + fn begin_object_value(self: &mut Self, writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called before every object value. A `:` should be written to + +- ```rust + fn end_object_value(self: &mut Self, _writer: &mut W) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Called after every object value. + +- ```rust + fn write_raw_fragment(self: &mut Self, writer: &mut W, fragment: &str) -> io::Result<()> +where + W: ?Sized + io::Write { /* ... */ } + ``` + Writes a raw JSON fragment that doesn't need any escaping to the + +##### Implementations + +This trait is implemented for the following types: + +- `CompactFormatter` +- `PrettyFormatter<''a>` with <''a> + +### Functions + +#### Function `to_writer` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as JSON into the I/O stream. + +Serialization guarantees it only feeds valid UTF-8 sequences to the writer. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_writer(writer: W, value: &T) -> crate::error::Result<()> +where + W: io::Write, + T: ?Sized + Serialize { /* ... */ } +``` + +#### Function `to_writer_pretty` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as pretty-printed JSON into the I/O +stream. + +Serialization guarantees it only feeds valid UTF-8 sequences to the writer. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_writer_pretty(writer: W, value: &T) -> crate::error::Result<()> +where + W: io::Write, + T: ?Sized + Serialize { /* ... */ } +``` + +#### Function `to_vec` + +**Attributes:** + +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as a JSON byte vector. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_vec(value: &T) -> crate::error::Result> +where + T: ?Sized + Serialize { /* ... */ } +``` + +#### Function `to_vec_pretty` + +**Attributes:** + +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as a pretty-printed JSON byte vector. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_vec_pretty(value: &T) -> crate::error::Result> +where + T: ?Sized + Serialize { /* ... */ } +``` + +#### Function `to_string` + +**Attributes:** + +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as a String of JSON. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_string(value: &T) -> crate::error::Result +where + T: ?Sized + Serialize { /* ... */ } +``` + +#### Function `to_string_pretty` + +**Attributes:** + +- `Other("#[attr = Inline(Hint)]")` + +Serialize the given data structure as a pretty-printed String of JSON. + +# Errors + +Serialization can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +```rust +pub fn to_string_pretty(value: &T) -> crate::error::Result +where + T: ?Sized + Serialize { /* ... */ } +``` + +## Module `value` + +The Value enum, a loosely typed way of representing any valid JSON value. + +# Constructing JSON + +Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +objects with very natural JSON syntax. + +``` +use serde_json::json; + +fn main() { + // The type of `john` is `serde_json::Value` + let john = json!({ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }); + + println!("first phone number: {}", john["phones"][0]); + + // Convert to a string of JSON and print it out + println!("{}", john.to_string()); +} +``` + +The `Value::to_string()` function converts a `serde_json::Value` into a +`String` of JSON text. + +One neat thing about the `json!` macro is that variables and expressions can +be interpolated directly into the JSON value as you are building it. Serde +will check at compile time that the value you are interpolating is able to +be represented as JSON. + +``` +# use serde_json::json; +# +# fn random_phone() -> u16 { 0 } +# +let full_name = "John Doe"; +let age_last_year = 42; + +// The type of `john` is `serde_json::Value` +let john = json!({ + "name": full_name, + "age": age_last_year + 1, + "phones": [ + format!("+44 {}", random_phone()) + ] +}); +``` + +A string of JSON data can be parsed into a `serde_json::Value` by the +[`serde_json::from_str`][from_str] function. There is also +[`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and +[`from_reader`][from_reader] for parsing from any `io::Read` like a File or +a TCP stream. + +``` +use serde_json::{json, Value, Error}; + +fn untyped_example() -> Result<(), Error> { + // Some JSON input data as a &str. Maybe this comes from the user. + let data = r#" + { + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + + // Parse the string of data into serde_json::Value. + let v: Value = serde_json::from_str(data)?; + + // Access parts of the data by indexing with square brackets. + println!("Please call {} at the number {}", v["name"], v["phones"][0]); + + Ok(()) +} +# +# untyped_example().unwrap(); +``` + +[macro]: crate::json +[from_str]: crate::de::from_str +[from_slice]: crate::de::from_slice +[from_reader]: crate::de::from_reader + +```rust +pub mod value { /* ... */ } +``` + +### Types + +#### Enum `Value` + +Represents any valid JSON value. + +See the [`serde_json::value` module documentation](self) for usage examples. + +```rust +pub enum Value { + Null, + Bool(bool), + Number(Number), + String(alloc::string::String), + Array(alloc::vec::Vec), + Object(Map), +} +``` + +##### Variants + +###### `Null` + +Represents a JSON null value. + +``` +# use serde_json::json; +# +let v = json!(null); +``` + +###### `Bool` + +Represents a JSON boolean. + +``` +# use serde_json::json; +# +let v = json!(true); +``` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `bool` | | + +###### `Number` + +Represents a JSON number, whether integer or floating point. + +``` +# use serde_json::json; +# +let v = json!(12.5); +``` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `Number` | | + +###### `String` + +Represents a JSON string. + +``` +# use serde_json::json; +# +let v = json!("a string"); +``` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `alloc::string::String` | | + +###### `Array` + +Represents a JSON array. + +``` +# use serde_json::json; +# +let v = json!(["an", "array"]); +``` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `alloc::vec::Vec` | | + +###### `Object` + +Represents a JSON object. + +By default the map is backed by a BTreeMap. Enable the `preserve_order` +feature of serde_json to use IndexMap instead, which preserves +entries in the order they are inserted into the map. In particular, this +allows JSON data to be deserialized into a Value and serialized to a +string while retaining the order of map keys in the input. + +``` +# use serde_json::json; +# +let v = json!({ "an": "object" }); +``` + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `Map` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn get(self: &Self, index: I) -> Option<&Value> { /* ... */ } + ``` + Index into a JSON array or map. A string index can be used to access a + +- ```rust + pub fn get_mut(self: &mut Self, index: I) -> Option<&mut Value> { /* ... */ } + ``` + Mutably index into a JSON array or map. A string index can be used to + +- ```rust + pub fn is_object(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is an Object. Returns false otherwise. + +- ```rust + pub fn as_object(self: &Self) -> Option<&Map> { /* ... */ } + ``` + If the `Value` is an Object, returns the associated Map. Returns None + +- ```rust + pub fn as_object_mut(self: &mut Self) -> Option<&mut Map> { /* ... */ } + ``` + If the `Value` is an Object, returns the associated mutable Map. + +- ```rust + pub fn is_array(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is an Array. Returns false otherwise. + +- ```rust + pub fn as_array(self: &Self) -> Option<&Vec> { /* ... */ } + ``` + If the `Value` is an Array, returns the associated vector. Returns None + +- ```rust + pub fn as_array_mut(self: &mut Self) -> Option<&mut Vec> { /* ... */ } + ``` + If the `Value` is an Array, returns the associated mutable vector. + +- ```rust + pub fn is_string(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is a String. Returns false otherwise. + +- ```rust + pub fn as_str(self: &Self) -> Option<&str> { /* ... */ } + ``` + If the `Value` is a String, returns the associated str. Returns None + +- ```rust + pub fn is_number(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is a Number. Returns false otherwise. + +- ```rust + pub fn as_number(self: &Self) -> Option<&Number> { /* ... */ } + ``` + If the `Value` is a Number, returns the associated [`Number`]. Returns + +- ```rust + pub fn is_i64(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is an integer between `i64::MIN` and + +- ```rust + pub fn is_u64(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is an integer between zero and `u64::MAX`. + +- ```rust + pub fn is_f64(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is a number that can be represented by f64. + +- ```rust + pub fn as_i64(self: &Self) -> Option { /* ... */ } + ``` + If the `Value` is an integer, represent it as i64 if possible. Returns + +- ```rust + pub fn as_u64(self: &Self) -> Option { /* ... */ } + ``` + If the `Value` is an integer, represent it as u64 if possible. Returns + +- ```rust + pub fn as_f64(self: &Self) -> Option { /* ... */ } + ``` + If the `Value` is a number, represent it as f64 if possible. Returns + +- ```rust + pub fn is_boolean(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is a Boolean. Returns false otherwise. + +- ```rust + pub fn as_bool(self: &Self) -> Option { /* ... */ } + ``` + If the `Value` is a Boolean, returns the associated bool. Returns None + +- ```rust + pub fn is_null(self: &Self) -> bool { /* ... */ } + ``` + Returns true if the `Value` is a Null. Returns false otherwise. + +- ```rust + pub fn as_null(self: &Self) -> Option<()> { /* ... */ } + ``` + If the `Value` is a Null, returns (). Returns None otherwise. + +- ```rust + pub fn pointer(self: &Self, pointer: &str) -> Option<&Value> { /* ... */ } + ``` + Looks up a value by a JSON Pointer. + +- ```rust + pub fn pointer_mut(self: &mut Self, pointer: &str) -> Option<&mut Value> { /* ... */ } + ``` + Looks up a value by a JSON Pointer and returns a mutable reference to + +- ```rust + pub fn take(self: &mut Self) -> Value { /* ... */ } + ``` + Takes the value out of the `Value`, leaving a `Null` in its place. + +- ```rust + pub fn sort_all_objects(self: &mut Self) { /* ... */ } + ``` + Reorders the entries of all `Value::Object` nested within this JSON + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Value { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, formatter: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Value { /* ... */ } + ``` + + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Deserialize** + - ```rust + fn deserialize(deserializer: D) -> Result::Error> +where + D: serde::Deserializer<''de> { /* ... */ } + ``` + +- **DeserializeOwned** +- **Deserializer** + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, _name: &''static str, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, _len: usize, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, _name: &''static str, _len: usize, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, _name: &''static str, _fields: &''static [&''static str], visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_any(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i8(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i16(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_i128(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u8(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u16(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_u128(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f32(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_f64(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_option(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_enum(self: Self, name: &''static str, variants: &''static [&''static str], visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_newtype_struct(self: Self, name: &''static str, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bool(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_char(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_str(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_string(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_bytes(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_byte_buf(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_unit_struct(self: Self, _name: &''static str, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_seq(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple(self: Self, _len: usize, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_tuple_struct(self: Self, _name: &''static str, _len: usize, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_map(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_struct(self: Self, _name: &''static str, _fields: &''static [&''static str], visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_identifier(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + + - ```rust + fn deserialize_ignored_any(self: Self, visitor: V) -> Result<::Value, Error> +where + V: Visitor<''de> { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + Display a JSON value as a string. + +- **Eq** +- **Equivalent** + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + + - ```rust + fn equivalent(self: &Self, key: &K) -> bool { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(n: i8) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: i16) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: i32) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: i64) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: isize) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: u8) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: u16) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: u32) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: u64) -> Self { /* ... */ } + ``` + + - ```rust + fn from(n: usize) -> Self { /* ... */ } + ``` + + - ```rust + fn from(f: f32) -> Self { /* ... */ } + ``` + Convert 32-bit floating point number to `Value::Number`, or + + - ```rust + fn from(f: f64) -> Self { /* ... */ } + ``` + Convert 64-bit floating point number to `Value::Number`, or + + - ```rust + fn from(f: bool) -> Self { /* ... */ } + ``` + Convert boolean to `Value::Bool`. + + - ```rust + fn from(f: String) -> Self { /* ... */ } + ``` + Convert `String` to `Value::String`. + + - ```rust + fn from(f: &str) -> Self { /* ... */ } + ``` + Convert string slice to `Value::String`. + + - ```rust + fn from(f: Cow<''a, str>) -> Self { /* ... */ } + ``` + Convert copy-on-write string to `Value::String`. + + - ```rust + fn from(f: Number) -> Self { /* ... */ } + ``` + Convert `Number` to `Value::Number`. + + - ```rust + fn from(f: Map) -> Self { /* ... */ } + ``` + Convert map (with string keys) to `Value::Object`. + + - ```rust + fn from(f: Vec) -> Self { /* ... */ } + ``` + Convert a `Vec` to `Value::Array`. + + - ```rust + fn from(array: [T; N]) -> Self { /* ... */ } + ``` + + - ```rust + fn from(f: &[T]) -> Self { /* ... */ } + ``` + Convert a slice to `Value::Array`. + + - ```rust + fn from((): ()) -> Self { /* ... */ } + ``` + Convert `()` to `Value::Null`. + + - ```rust + fn from(opt: Option) -> Self { /* ... */ } + ``` + +- **FromIterator** + - ```rust + fn from_iter>(iter: I) -> Self { /* ... */ } + ``` + Create a `Value::Array` by collecting an iterator of array elements. + + - ```rust + fn from_iter>(iter: I) -> Self { /* ... */ } + ``` + Create a `Value::Object` by collecting an iterator of key-value pairs. + +- **FromStr** + - ```rust + fn from_str(s: &str) -> Result { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Index** + - ```rust + fn index(self: &Self, index: I) -> &Value { /* ... */ } + ``` + Index into a `serde_json::Value` using the syntax `value[0]` or + +- **IndexMut** + - ```rust + fn index_mut(self: &mut Self, index: I) -> &mut Value { /* ... */ } + ``` + Write into a `serde_json::Value` using the syntax `value[0] = ...` or + +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoDeserializer** + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + + - ```rust + fn into_deserializer(self: Self) -> ::Deserializer { /* ... */ } + ``` + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &str) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &&str) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &String) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &i64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &isize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &isize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &isize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u8) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u16) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &u64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &usize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &usize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &usize) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f32) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &f64) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &bool) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &Value) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &bool) -> bool { /* ... */ } + ``` + + - ```rust + fn eq(self: &Self, other: &bool) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Serialize** + - ```rust + fn serialize(self: &Self, serializer: S) -> result::Result<::Ok, ::Error> +where + S: ::serde::Serializer { /* ... */ } + ``` + +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +### Functions + +#### Function `to_value` + +Convert a `T` into `serde_json::Value` which is an enum that can represent +any valid JSON data. + +# Example + +``` +use serde::Serialize; +use serde_json::json; +use std::error::Error; + +#[derive(Serialize)] +struct User { + fingerprint: String, + location: String, +} + +fn compare_json_values() -> Result<(), Box> { + let u = User { + fingerprint: "0xF9BA143B95FF6D82".to_owned(), + location: "Menlo Park, CA".to_owned(), + }; + + // The type of `expected` is `serde_json::Value` + let expected = json!({ + "fingerprint": "0xF9BA143B95FF6D82", + "location": "Menlo Park, CA", + }); + + let v = serde_json::to_value(u).unwrap(); + assert_eq!(v, expected); + + Ok(()) +} +# +# compare_json_values().unwrap(); +``` + +# Errors + +This conversion can fail if `T`'s implementation of `Serialize` decides to +fail, or if `T` contains a map with non-string keys. + +``` +use std::collections::BTreeMap; + +fn main() { + // The keys in this map are vectors, not strings. + let mut map = BTreeMap::new(); + map.insert(vec![32, 64], "x86"); + + println!("{}", serde_json::to_value(map).unwrap_err()); +} +``` + +```rust +pub fn to_value(value: T) -> Result +where + T: Serialize { /* ... */ } +``` + +#### Function `from_value` + +Interpret a `serde_json::Value` as an instance of type `T`. + +# Example + +``` +use serde::Deserialize; +use serde_json::json; + +#[derive(Deserialize, Debug)] +struct User { + fingerprint: String, + location: String, +} + +fn main() { + // The type of `j` is `serde_json::Value` + let j = json!({ + "fingerprint": "0xF9BA143B95FF6D82", + "location": "Menlo Park, CA" + }); + + let u: User = serde_json::from_value(j).unwrap(); + println!("{:#?}", u); +} +``` + +# Errors + +This conversion can fail if the structure of the Value does not match the +structure expected by `T`, for example if `T` is a struct type but the Value +contains something other than a JSON map. It can also fail if the structure +is correct but `T`'s implementation of `Deserialize` decides that something +is wrong with the data, for example required struct fields are missing from +the JSON map or some number is too big to fit in the expected primitive +type. + +```rust +pub fn from_value(value: Value) -> Result +where + T: DeserializeOwned { /* ... */ } +``` + +### Re-exports + +#### Re-export `Index` + +```rust +pub use self::index::Index; +``` + +#### Re-export `Serializer` + +```rust +pub use self::ser::Serializer; +``` + +#### Re-export `Map` + +```rust +pub use crate::map::Map; +``` + +#### Re-export `Number` + +```rust +pub use crate::number::Number; +``` + +#### Re-export `to_raw_value` + +**Attributes:** + +- `Other("#[(feature = \"raw_value\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"raw_value\")))]")` +- `Other("#[doc(cfg(feature = \"raw_value\"))]")` + +```rust +pub use crate::raw::to_raw_value; +``` + +#### Re-export `RawValue` + +**Attributes:** + +- `Other("#[(feature = \"raw_value\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"raw_value\")))]")` +- `Other("#[doc(cfg(feature = \"raw_value\"))]")` + +```rust +pub use crate::raw::RawValue; +``` + +## Macros + +### Macro `json` + +**Attributes:** + +- `MacroExport` + +Construct a `serde_json::Value` from a JSON literal. + +``` +# use serde_json::json; +# +let value = json!({ + "code": 200, + "success": true, + "payload": { + "features": [ + "serde", + "json" + ], + "homepage": null + } +}); +``` + +Variables or expressions can be interpolated into the JSON literal. Any type +interpolated into an array element or object value must implement Serde's +`Serialize` trait, while any type interpolated into a object key must +implement `Into`. If the `Serialize` implementation of the +interpolated type decides to fail, or if the interpolated type contains a +map with non-string keys, the `json!` macro will panic. + +``` +# use serde_json::json; +# +let code = 200; +let features = vec!["serde", "json"]; + +let value = json!({ + "code": code, + "success": code == 200, + "payload": { + features[0]: features[1] + } +}); +``` + +Trailing commas are allowed inside both arrays and objects. + +``` +# use serde_json::json; +# +let value = json!([ + "notice", + "the", + "trailing", + "comma -->", +]); +``` + +```rust +pub macro_rules! json { + /* macro_rules! json { + ($($json:tt)+) => { ... }; +} */ +} +``` + +## Re-exports + +### Re-export `from_reader` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::from_reader; +``` + +### Re-export `from_slice` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::from_slice; +``` + +### Re-export `from_str` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::from_str; +``` + +### Re-export `Deserializer` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::Deserializer; +``` + +### Re-export `StreamDeserializer` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::de::StreamDeserializer; +``` + +### Re-export `Error` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::error::Error; +``` + +### Re-export `Result` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::error::Result; +``` + +### Re-export `to_string` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_string; +``` + +### Re-export `to_string_pretty` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_string_pretty; +``` + +### Re-export `to_vec` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_vec; +``` + +### Re-export `to_vec_pretty` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_vec_pretty; +``` + +### Re-export `to_writer` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_writer; +``` + +### Re-export `to_writer_pretty` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::to_writer_pretty; +``` + +### Re-export `Serializer` + +**Attributes:** + +- `Other("#[(feature = \"std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"std\")))]")` +- `Other("#[doc(cfg(feature = \"std\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use crate::ser::Serializer; +``` + +### Re-export `from_value` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::value::from_value; +``` + +### Re-export `to_value` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::value::to_value; +``` + +### Re-export `Map` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::value::Map; +``` + +### Re-export `Number` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::value::Number; +``` + +### Re-export `Value` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use crate::value::Value; +``` + diff --git a/doc/tokio.md b/doc/tokio.md new file mode 100644 index 0000000..ad35a7e --- /dev/null +++ b/doc/tokio.md @@ -0,0 +1,14681 @@ +# Crate Documentation + +**Version:** 1.48.0 + +**Format Version:** 56 + +# Module `tokio` + +A runtime for writing reliable network applications without compromising speed. + +Tokio is an event-driven, non-blocking I/O platform for writing asynchronous +applications with the Rust programming language. At a high level, it +provides a few major components: + +* Tools for [working with asynchronous tasks][tasks], including + [synchronization primitives and channels][sync] and [timeouts, sleeps, and + intervals][time]. +* APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets, + [filesystem][fs] operations, and [process] and [signal] management. +* A [runtime] for executing asynchronous code, including a task scheduler, + an I/O driver backed by the operating system's event queue (`epoll`, `kqueue`, + `IOCP`, etc...), and a high performance timer. + +Guide level documentation is found on the [website]. + +[tasks]: #working-with-tasks +[sync]: crate::sync +[time]: crate::time +[io]: #asynchronous-io +[net]: crate::net +[fs]: crate::fs +[process]: crate::process +[signal]: crate::signal +[fs]: crate::fs +[runtime]: crate::runtime +[website]: https://tokio.rs/tokio/tutorial + +# A Tour of Tokio + +Tokio consists of a number of modules that provide a range of functionality +essential for implementing asynchronous applications in Rust. In this +section, we will take a brief tour of Tokio, summarizing the major APIs and +their uses. + +The easiest way to get started is to enable all features. Do this by +enabling the `full` feature flag: + +```toml +tokio = { version = "1", features = ["full"] } +``` + +### Authoring applications + +Tokio is great for writing applications and most users in this case shouldn't +worry too much about what features they should pick. If you're unsure, we suggest +going with `full` to ensure that you don't run into any road blocks while you're +building your application. + +#### Example + +This example shows the quickest way to get started with Tokio. + +```toml +tokio = { version = "1", features = ["full"] } +``` + +### Authoring libraries + +As a library author your goal should be to provide the lightest weight crate +that is based on Tokio. To achieve this you should ensure that you only enable +the features you need. This allows users to pick up your crate without having +to enable unnecessary features. + +#### Example + +This example shows how you may want to import features for a library that just +needs to `tokio::spawn` and use a `TcpStream`. + +```toml +tokio = { version = "1", features = ["rt", "net"] } +``` + +## Working With Tasks + +Asynchronous programs in Rust are based around lightweight, non-blocking +units of execution called [_tasks_][tasks]. The [`tokio::task`] module provides +important tools for working with tasks: + +* The [`spawn`] function and [`JoinHandle`] type, for scheduling a new task + on the Tokio runtime and awaiting the output of a spawned task, respectively, +* Functions for [running blocking operations][blocking] in an asynchronous + task context. + +The [`tokio::task`] module is present only when the "rt" feature flag +is enabled. + +[tasks]: task/index.html#what-are-tasks +[`tokio::task`]: crate::task +[`spawn`]: crate::task::spawn() +[`JoinHandle`]: crate::task::JoinHandle +[blocking]: task/index.html#blocking-and-yielding + +The [`tokio::sync`] module contains synchronization primitives to use when +needing to communicate or share data. These include: + +* channels ([`oneshot`], [`mpsc`], [`watch`], and [`broadcast`]), for sending values + between tasks, +* a non-blocking [`Mutex`], for controlling access to a shared, mutable + value, +* an asynchronous [`Barrier`] type, for multiple tasks to synchronize before + beginning a computation. + +The `tokio::sync` module is present only when the "sync" feature flag is +enabled. + +[`tokio::sync`]: crate::sync +[`Mutex`]: crate::sync::Mutex +[`Barrier`]: crate::sync::Barrier +[`oneshot`]: crate::sync::oneshot +[`mpsc`]: crate::sync::mpsc +[`watch`]: crate::sync::watch +[`broadcast`]: crate::sync::broadcast + +The [`tokio::time`] module provides utilities for tracking time and +scheduling work. This includes functions for setting [timeouts][timeout] for +tasks, [sleeping][sleep] work to run in the future, or [repeating an operation at an +interval][interval]. + +In order to use `tokio::time`, the "time" feature flag must be enabled. + +[`tokio::time`]: crate::time +[sleep]: crate::time::sleep() +[interval]: crate::time::interval() +[timeout]: crate::time::timeout() + +Finally, Tokio provides a _runtime_ for executing asynchronous tasks. Most +applications can use the [`#[tokio::main]`][main] macro to run their code on the +Tokio runtime. However, this macro provides only basic configuration options. As +an alternative, the [`tokio::runtime`] module provides more powerful APIs for configuring +and managing runtimes. You should use that module if the `#[tokio::main]` macro doesn't +provide the functionality you need. + +Using the runtime requires the "rt" or "rt-multi-thread" feature flags, to +enable the current-thread [single-threaded scheduler][rt] and the [multi-thread +scheduler][rt-multi-thread], respectively. See the [`runtime` module +documentation][rt-features] for details. In addition, the "macros" feature +flag enables the `#[tokio::main]` and `#[tokio::test]` attributes. + +[main]: attr.main.html +[`tokio::runtime`]: crate::runtime +[`Builder`]: crate::runtime::Builder +[`Runtime`]: crate::runtime::Runtime +[rt]: runtime/index.html#current-thread-scheduler +[rt-multi-thread]: runtime/index.html#multi-thread-scheduler +[rt-features]: runtime/index.html#runtime-scheduler + +## CPU-bound tasks and blocking code + +Tokio is able to concurrently run many tasks on a few threads by repeatedly +swapping the currently running task on each thread. However, this kind of +swapping can only happen at `.await` points, so code that spends a long time +without reaching an `.await` will prevent other tasks from running. To +combat this, Tokio provides two kinds of threads: Core threads and blocking threads. + +The core threads are where all asynchronous code runs, and Tokio will by default +spawn one for each CPU core. You can use the environment variable `TOKIO_WORKER_THREADS` +to override the default value. + +The blocking threads are spawned on demand, can be used to run blocking code +that would otherwise block other tasks from running and are kept alive when +not used for a certain amount of time which can be configured with [`thread_keep_alive`]. +Since it is not possible for Tokio to swap out blocking tasks, like it +can do with asynchronous code, the upper limit on the number of blocking +threads is very large. These limits can be configured on the [`Builder`]. + +To spawn a blocking task, you should use the [`spawn_blocking`] function. + +[`Builder`]: crate::runtime::Builder +[`spawn_blocking`]: crate::task::spawn_blocking() +[`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive() + +``` +# #[cfg(not(target_family = "wasm"))] +# { +#[tokio::main] +async fn main() { + // This is running on a core thread. + + let blocking_task = tokio::task::spawn_blocking(|| { + // This is running on a blocking thread. + // Blocking here is ok. + }); + + // We can wait for the blocking task like this: + // If the blocking task panics, the unwrap below will propagate the + // panic. + blocking_task.await.unwrap(); +} +# } +``` + +If your code is CPU-bound and you wish to limit the number of threads used +to run it, you should use a separate thread pool dedicated to CPU bound tasks. +For example, you could consider using the [rayon] library for CPU-bound +tasks. It is also possible to create an extra Tokio runtime dedicated to +CPU-bound tasks, but if you do this, you should be careful that the extra +runtime runs _only_ CPU-bound tasks, as IO-bound tasks on that runtime +will behave poorly. + +Hint: If using rayon, you can use a [`oneshot`] channel to send the result back +to Tokio when the rayon task finishes. + +[rayon]: https://docs.rs/rayon +[`oneshot`]: crate::sync::oneshot + +## Asynchronous IO + +As well as scheduling and running tasks, Tokio provides everything you need +to perform input and output asynchronously. + +The [`tokio::io`] module provides Tokio's asynchronous core I/O primitives, +the [`AsyncRead`], [`AsyncWrite`], and [`AsyncBufRead`] traits. In addition, +when the "io-util" feature flag is enabled, it also provides combinators and +functions for working with these traits, forming as an asynchronous +counterpart to [`std::io`]. + +Tokio also includes APIs for performing various kinds of I/O and interacting +with the operating system asynchronously. These include: + +* [`tokio::net`], which contains non-blocking versions of [TCP], [UDP], and + [Unix Domain Sockets][UDS] (enabled by the "net" feature flag), +* [`tokio::fs`], similar to [`std::fs`] but for performing filesystem I/O + asynchronously (enabled by the "fs" feature flag), +* [`tokio::signal`], for asynchronously handling Unix and Windows OS signals + (enabled by the "signal" feature flag), +* [`tokio::process`], for spawning and managing child processes (enabled by + the "process" feature flag). + +[`tokio::io`]: crate::io +[`AsyncRead`]: crate::io::AsyncRead +[`AsyncWrite`]: crate::io::AsyncWrite +[`AsyncBufRead`]: crate::io::AsyncBufRead +[`std::io`]: std::io +[`tokio::net`]: crate::net +[TCP]: crate::net::tcp +[UDP]: crate::net::UdpSocket +[UDS]: crate::net::unix +[`tokio::fs`]: crate::fs +[`std::fs`]: std::fs +[`tokio::signal`]: crate::signal +[`tokio::process`]: crate::process + +# Examples + +A simple TCP echo server: + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::net::TcpListener; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let listener = TcpListener::bind("127.0.0.1:8080").await?; + + loop { + let (mut socket, _) = listener.accept().await?; + + tokio::spawn(async move { + let mut buf = [0; 1024]; + + // In a loop, read data from the socket and write the data back. + loop { + let n = match socket.read(&mut buf).await { + // socket closed + Ok(0) => return, + Ok(n) => n, + Err(e) => { + eprintln!("failed to read from socket; err = {:?}", e); + return; + } + }; + + // Write the data back + if let Err(e) = socket.write_all(&buf[0..n]).await { + eprintln!("failed to write to socket; err = {:?}", e); + return; + } + } + }); + } +} +# } +``` + +# Feature flags + +Tokio uses a set of [feature flags] to reduce the amount of compiled code. It +is possible to just enable certain features over others. By default, Tokio +does not enable any features but allows one to enable a subset for their use +case. Below is a list of the available feature flags. You may also notice +above each function, struct and trait there is listed one or more feature flags +that are required for that item to be used. If you are new to Tokio it is +recommended that you use the `full` feature flag which will enable all public APIs. +Beware though that this will pull in many extra dependencies that you may not +need. + +- `full`: Enables all features listed below except `test-util` and `tracing`. +- `rt`: Enables `tokio::spawn`, the current-thread scheduler, + and non-scheduler utilities. +- `rt-multi-thread`: Enables the heavier, multi-threaded, work-stealing scheduler. +- `io-util`: Enables the IO based `Ext` traits. +- `io-std`: Enable `Stdout`, `Stdin` and `Stderr` types. +- `net`: Enables `tokio::net` types such as `TcpStream`, `UnixStream` and + `UdpSocket`, as well as (on Unix-like systems) `AsyncFd` and (on + FreeBSD) `PollAio`. +- `time`: Enables `tokio::time` types and allows the schedulers to enable + the built in timer. +- `process`: Enables `tokio::process` types. +- `macros`: Enables `#[tokio::main]` and `#[tokio::test]` macros. +- `sync`: Enables all `tokio::sync` types. +- `signal`: Enables all `tokio::signal` types. +- `fs`: Enables `tokio::fs` types. +- `test-util`: Enables testing based infrastructure for the Tokio runtime. +- `parking_lot`: As a potential optimization, use the [`parking_lot`] crate's + synchronization primitives internally. Also, this + dependency is necessary to construct some of our primitives + in a `const` context. `MSRV` may increase according to the + [`parking_lot`] release in use. + +_Note: `AsyncRead` and `AsyncWrite` traits do not require any features and are +always available._ + +## Unstable features + +Some feature flags are only available when specifying the `tokio_unstable` flag: + +- `tracing`: Enables tracing events. + +Likewise, some parts of the API are only available with the same flag: + +- [`task::Builder`] +- Some methods on [`task::JoinSet`] +- [`runtime::RuntimeMetrics`] +- [`runtime::Builder::on_task_spawn`] +- [`runtime::Builder::on_task_terminate`] +- [`runtime::Builder::unhandled_panic`] +- [`runtime::TaskMeta`] + +This flag enables **unstable** features. The public API of these features +may break in 1.x releases. To enable these features, the `--cfg +tokio_unstable` argument must be passed to `rustc` when compiling. This +serves to explicitly opt-in to features which may break semver conventions, +since Cargo [does not yet directly support such opt-ins][unstable features]. + +You can specify it in your project's `.cargo/config.toml` file: + +```toml +[build] +rustflags = ["--cfg", "tokio_unstable"] +``` + +
+The [build] section does not go in a +Cargo.toml file. Instead it must be placed in the Cargo config +file .cargo/config.toml. +
+ +Alternatively, you can specify it with an environment variable: + +```sh +## Many *nix shells: +export RUSTFLAGS="--cfg tokio_unstable" +cargo build +``` + +```powershell +## Windows PowerShell: +$Env:RUSTFLAGS="--cfg tokio_unstable" +cargo build +``` + +[unstable features]: https://internals.rust-lang.org/t/feature-request-unstable-opt-in-non-transitive-crate-features/16193#why-not-a-crate-feature-2 +[feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section + +# Supported platforms + +Tokio currently guarantees support for the following platforms: + + * Linux + * Windows + * Android (API level 21) + * macOS + * iOS + * FreeBSD + +Tokio will continue to support these platforms in the future. However, +future releases may change requirements such as the minimum required libc +version on Linux, the API level on Android, or the supported FreeBSD +release. + +Beyond the above platforms, Tokio is intended to work on all platforms +supported by the mio crate. You can find a longer list [in mio's +documentation][mio-supported]. However, these additional platforms may +become unsupported in the future. + +Note that Wine is considered to be a different platform from Windows. See +mio's documentation for more information on Wine support. + +[mio-supported]: https://crates.io/crates/mio#platforms + +## `WASM` support + +Tokio has some limited support for the `WASM` platform. Without the +`tokio_unstable` flag, the following features are supported: + + * `sync` + * `macros` + * `io-util` + * `rt` + * `time` + +Enabling any other feature (including `full`) will cause a compilation +failure. + +The `time` module will only work on `WASM` platforms that have support for +timers (e.g. wasm32-wasi). The timing functions will panic if used on a `WASM` +platform that does not support timers. + +Note also that if the runtime becomes indefinitely idle, it will panic +immediately instead of blocking forever. On platforms that don't support +time, this means that the runtime can never be idle in any way. + +## Unstable `WASM` support + +Tokio also has unstable support for some additional `WASM` features. This +requires the use of the `tokio_unstable` flag. + +Using this flag enables the use of `tokio::net` on the wasm32-wasi target. +However, not all methods are available on the networking types as `WASI` +currently does not support the creation of new sockets from within `WASM`. +Because of this, sockets must currently be created via the `FromRawFd` +trait. + +## Modules + +## Module `fs` + +**Attributes:** + +- `Other("#[(feature = \"fs\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"fs\")))]")` +- `Other("#[doc(cfg(feature = \"fs\"))]")` +- `Other("#[(not(loom))]")` + +Asynchronous file utilities. + +This module contains utility methods for working with the file system +asynchronously. This includes reading/writing to files, and working with +directories. + +Be aware that most operating systems do not provide asynchronous file system +APIs. Because of that, Tokio will use ordinary blocking file operations +behind the scenes. This is done using the [`spawn_blocking`] threadpool to +run them in the background. + +The `tokio::fs` module should only be used for ordinary files. Trying to use +it with e.g., a named pipe on Linux can result in surprising behavior, +such as hangs during runtime shutdown. For special files, you should use a +dedicated type such as [`tokio::net::unix::pipe`] or [`AsyncFd`] instead. + +Currently, Tokio will always use [`spawn_blocking`] on all platforms, but it +may be changed to use asynchronous file system APIs such as io_uring in the +future. + +# Usage + +The easiest way to use this module is to use the utility functions that +operate on entire files: + + * [`tokio::fs::read`](fn@crate::fs::read) + * [`tokio::fs::read_to_string`](fn@crate::fs::read_to_string) + * [`tokio::fs::write`](fn@crate::fs::write) + +The two `read` functions reads the entire file and returns its contents. +The `write` function takes the contents of the file and writes those +contents to the file. It overwrites the existing file, if any. + +For example, to read the file: + +``` +# async fn dox() -> std::io::Result<()> { +let contents = tokio::fs::read_to_string("my_file.txt").await?; + +println!("File has {} lines.", contents.lines().count()); +# Ok(()) +# } +``` + +To overwrite the file: + +``` +# async fn dox() -> std::io::Result<()> { +let contents = "First line.\nSecond line.\nThird line.\n"; + +tokio::fs::write("my_file.txt", contents.as_bytes()).await?; +# Ok(()) +# } +``` + +## Using `File` + +The main type for interacting with files is [`File`]. It can be used to read +from and write to a given file. This is done using the [`AsyncRead`] and +[`AsyncWrite`] traits. This type is generally used when you want to do +something more complex than just reading or writing the entire contents in +one go. + +**Note:** It is important to use [`flush`] when writing to a Tokio +[`File`]. This is because calls to `write` will return before the write has +finished, and [`flush`] will wait for the write to finish. (The write will +happen even if you don't flush; it will just happen later.) This is +different from [`std::fs::File`], and is due to the fact that `File` uses +`spawn_blocking` behind the scenes. + +For example, to count the number of lines in a file without loading the +entire file into memory: + +```no_run +use tokio::fs::File; +use tokio::io::AsyncReadExt; + +# async fn dox() -> std::io::Result<()> { +let mut file = File::open("my_file.txt").await?; + +let mut chunk = vec![0; 4096]; +let mut number_of_lines = 0; +loop { + let len = file.read(&mut chunk).await?; + if len == 0 { + // Length of zero means end of file. + break; + } + for &b in &chunk[..len] { + if b == b'\n' { + number_of_lines += 1; + } + } +} + +println!("File has {} lines.", number_of_lines); +# Ok(()) +# } +``` + +For example, to write a file line-by-line: + +```no_run +use tokio::fs::File; +use tokio::io::AsyncWriteExt; + +# async fn dox() -> std::io::Result<()> { +let mut file = File::create("my_file.txt").await?; + +file.write_all(b"First line.\n").await?; +file.write_all(b"Second line.\n").await?; +file.write_all(b"Third line.\n").await?; + +// Remember to call `flush` after writing! +file.flush().await?; +# Ok(()) +# } +``` + +## Tuning your file IO + +Tokio's file uses [`spawn_blocking`] behind the scenes, and this has serious +performance consequences. To get good performance with file IO on Tokio, it +is recommended to batch your operations into as few `spawn_blocking` calls +as possible. + +One example of this difference can be seen by comparing the two reading +examples above. The first example uses [`tokio::fs::read`], which reads the +entire file in a single `spawn_blocking` call, and then returns it. The +second example will read the file in chunks using many `spawn_blocking` +calls. This means that the second example will most likely be more expensive +for large files. (Of course, using chunks may be necessary for very large +files that don't fit in memory.) + +The following examples will show some strategies for this: + +When creating a file, write the data to a `String` or `Vec` and then +write the entire file in a single `spawn_blocking` call with +`tokio::fs::write`. + +```no_run +# async fn dox() -> std::io::Result<()> { +let mut contents = String::new(); + +contents.push_str("First line.\n"); +contents.push_str("Second line.\n"); +contents.push_str("Third line.\n"); + +tokio::fs::write("my_file.txt", contents.as_bytes()).await?; +# Ok(()) +# } +``` + +Use [`BufReader`] and [`BufWriter`] to buffer many small reads or writes +into a few large ones. This example will most likely only perform one +`spawn_blocking` call. + +```no_run +use tokio::fs::File; +use tokio::io::{AsyncWriteExt, BufWriter}; + +# async fn dox() -> std::io::Result<()> { +let mut file = BufWriter::new(File::create("my_file.txt").await?); + +file.write_all(b"First line.\n").await?; +file.write_all(b"Second line.\n").await?; +file.write_all(b"Third line.\n").await?; + +// Due to the BufWriter, the actual write and spawn_blocking +// call happens when you flush. +file.flush().await?; +# Ok(()) +# } +``` + +Manually use [`std::fs`] inside [`spawn_blocking`]. + +```no_run +use std::fs::File; +use std::io::{self, Write}; +use tokio::task::spawn_blocking; + +# async fn dox() -> std::io::Result<()> { +spawn_blocking(move || { + let mut file = File::create("my_file.txt")?; + + file.write_all(b"First line.\n")?; + file.write_all(b"Second line.\n")?; + file.write_all(b"Third line.\n")?; + + // Unlike Tokio's file, the std::fs file does + // not need flush. + + io::Result::Ok(()) +}).await.unwrap()?; +# Ok(()) +# } +``` + +It's also good to be aware of [`File::set_max_buf_size`], which controls the +maximum amount of bytes that Tokio's [`File`] will read or write in a single +[`spawn_blocking`] call. The default is two megabytes, but this is subject +to change. + +[`spawn_blocking`]: fn@crate::task::spawn_blocking +[`AsyncRead`]: trait@crate::io::AsyncRead +[`AsyncWrite`]: trait@crate::io::AsyncWrite +[`BufReader`]: struct@crate::io::BufReader +[`BufWriter`]: struct@crate::io::BufWriter +[`tokio::net::unix::pipe`]: crate::net::unix::pipe +[`AsyncFd`]: crate::io::unix::AsyncFd +[`flush`]: crate::io::AsyncWriteExt::flush +[`tokio::fs::read`]: fn@crate::fs::read + +```rust +pub mod fs { /* ... */ } +``` + +### Re-exports + +#### Re-export `canonicalize` + +```rust +pub use self::canonicalize::canonicalize; +``` + +#### Re-export `create_dir` + +```rust +pub use self::create_dir::create_dir; +``` + +#### Re-export `create_dir_all` + +```rust +pub use self::create_dir_all::create_dir_all; +``` + +#### Re-export `DirBuilder` + +```rust +pub use self::dir_builder::DirBuilder; +``` + +#### Re-export `File` + +```rust +pub use self::file::File; +``` + +#### Re-export `hard_link` + +```rust +pub use self::hard_link::hard_link; +``` + +#### Re-export `metadata` + +```rust +pub use self::metadata::metadata; +``` + +#### Re-export `OpenOptions` + +```rust +pub use self::open_options::OpenOptions; +``` + +#### Re-export `read` + +```rust +pub use self::read::read; +``` + +#### Re-export `read_dir` + +```rust +pub use self::read_dir::read_dir; +``` + +#### Re-export `DirEntry` + +```rust +pub use self::read_dir::DirEntry; +``` + +#### Re-export `ReadDir` + +```rust +pub use self::read_dir::ReadDir; +``` + +#### Re-export `read_link` + +```rust +pub use self::read_link::read_link; +``` + +#### Re-export `read_to_string` + +```rust +pub use self::read_to_string::read_to_string; +``` + +#### Re-export `remove_dir` + +```rust +pub use self::remove_dir::remove_dir; +``` + +#### Re-export `remove_dir_all` + +```rust +pub use self::remove_dir_all::remove_dir_all; +``` + +#### Re-export `remove_file` + +```rust +pub use self::remove_file::remove_file; +``` + +#### Re-export `rename` + +```rust +pub use self::rename::rename; +``` + +#### Re-export `set_permissions` + +```rust +pub use self::set_permissions::set_permissions; +``` + +#### Re-export `symlink_metadata` + +```rust +pub use self::symlink_metadata::symlink_metadata; +``` + +#### Re-export `write` + +```rust +pub use self::write::write; +``` + +#### Re-export `copy` + +```rust +pub use self::copy::copy; +``` + +#### Re-export `try_exists` + +```rust +pub use self::try_exists::try_exists; +``` + +#### Re-export `symlink` + +**Attributes:** + +- `Other("#[(unix)]")` +- `Other("#[(docsrs, doc(cfg(unix)))]")` +- `Other("#[doc(cfg(unix))]")` + +```rust +pub use self::symlink::symlink; +``` + +#### Re-export `symlink_dir` + +**Attributes:** + +- `Other("#[(any(all(doc, docsrs), windows))]")` +- `Other("#[(docsrs, doc(cfg(windows)))]")` +- `Other("#[doc(cfg(windows))]")` + +```rust +pub use self::symlink_dir::symlink_dir; +``` + +#### Re-export `symlink_file` + +**Attributes:** + +- `Other("#[(any(all(doc, docsrs), windows))]")` +- `Other("#[(docsrs, doc(cfg(windows)))]")` +- `Other("#[doc(cfg(windows))]")` + +```rust +pub use self::symlink_file::symlink_file; +``` + +## Module `io` + +**Attributes:** + +- `Other("#[(not(all(feature = \"rt\", feature = \"net\")),\nallow(dead_code, unused_imports))]")` + +Traits, helpers, and type definitions for asynchronous I/O functionality. + +This module is the asynchronous version of `std::io`. Primarily, it +defines two traits, [`AsyncRead`] and [`AsyncWrite`], which are asynchronous +versions of the [`Read`] and [`Write`] traits in the standard library. + +# `AsyncRead` and `AsyncWrite` + +Like the standard library's [`Read`] and [`Write`] traits, [`AsyncRead`] and +[`AsyncWrite`] provide the most general interface for reading and writing +input and output. Unlike the standard library's traits, however, they are +_asynchronous_ — meaning that reading from or writing to a `tokio::io` +type will _yield_ to the Tokio scheduler when IO is not ready, rather than +blocking. This allows other tasks to run while waiting on IO. + +Another difference is that `AsyncRead` and `AsyncWrite` only contain +core methods needed to provide asynchronous reading and writing +functionality. Instead, utility methods are defined in the [`AsyncReadExt`] +and [`AsyncWriteExt`] extension traits. These traits are automatically +implemented for all values that implement `AsyncRead` and `AsyncWrite` +respectively. + +End users will rarely interact directly with `AsyncRead` and +`AsyncWrite`. Instead, they will use the async functions defined in the +extension traits. Library authors are expected to implement `AsyncRead` +and `AsyncWrite` in order to provide types that behave like byte streams. + +Even with these differences, Tokio's `AsyncRead` and `AsyncWrite` traits +can be used in almost exactly the same manner as the standard library's +`Read` and `Write`. Most types in the standard library that implement `Read` +and `Write` have asynchronous equivalents in `tokio` that implement +`AsyncRead` and `AsyncWrite`, such as [`File`] and [`TcpStream`]. + +For example, the standard library documentation introduces `Read` by +[demonstrating][std_example] reading some bytes from a [`std::fs::File`]. We +can do the same with [`tokio::fs::File`][`File`]: + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::io::{self, AsyncReadExt}; +use tokio::fs::File; + +#[tokio::main] +async fn main() -> io::Result<()> { + let mut f = File::open("foo.txt").await?; + let mut buffer = [0; 10]; + + // read up to 10 bytes + let n = f.read(&mut buffer).await?; + + println!("The bytes: {:?}", &buffer[..n]); + Ok(()) +} +# } +``` + +[`File`]: crate::fs::File +[`TcpStream`]: crate::net::TcpStream +[`std::fs::File`]: std::fs::File +[std_example]: std::io#read-and-write + +## Buffered Readers and Writers + +Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be +making near-constant calls to the operating system. To help with this, +`std::io` comes with [support for _buffered_ readers and writers][stdbuf], +and therefore, `tokio::io` does as well. + +Tokio provides an async version of the [`std::io::BufRead`] trait, +[`AsyncBufRead`]; and async [`BufReader`] and [`BufWriter`] structs, which +wrap readers and writers. These wrappers use a buffer, reducing the number +of calls and providing nicer methods for accessing exactly what you want. + +For example, [`BufReader`] works with the [`AsyncBufRead`] trait to add +extra methods to any async reader: + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::io::{self, BufReader, AsyncBufReadExt}; +use tokio::fs::File; + +#[tokio::main] +async fn main() -> io::Result<()> { + let f = File::open("foo.txt").await?; + let mut reader = BufReader::new(f); + let mut buffer = String::new(); + + // read a line into buffer + reader.read_line(&mut buffer).await?; + + println!("{}", buffer); + Ok(()) +} +# } +``` + +[`BufWriter`] doesn't add any new ways of writing; it just buffers every call +to [`write`](crate::io::AsyncWriteExt::write). However, you **must** flush +[`BufWriter`] to ensure that any buffered data is written. + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::io::{self, BufWriter, AsyncWriteExt}; +use tokio::fs::File; + +#[tokio::main] +async fn main() -> io::Result<()> { + let f = File::create("foo.txt").await?; + { + let mut writer = BufWriter::new(f); + + // Write a byte to the buffer. + writer.write(&[42u8]).await?; + + // Flush the buffer before it goes out of scope. + writer.flush().await?; + + } // Unless flushed or shut down, the contents of the buffer is discarded on drop. + + Ok(()) +} +# } +``` + +[stdbuf]: std::io#bufreader-and-bufwriter +[`std::io::BufRead`]: std::io::BufRead +[`AsyncBufRead`]: crate::io::AsyncBufRead +[`BufReader`]: crate::io::BufReader +[`BufWriter`]: crate::io::BufWriter + +## Implementing `AsyncRead` and `AsyncWrite` + +Because they are traits, we can implement [`AsyncRead`] and [`AsyncWrite`] for +our own types, as well. Note that these traits must only be implemented for +non-blocking I/O types that integrate with the futures type system. In +other words, these types must never block the thread, and instead the +current task is notified when the I/O resource is ready. + +## Conversion to and from Stream/Sink + +It is often convenient to encapsulate the reading and writing of bytes in a +[`Stream`] or [`Sink`] of data. + +Tokio provides simple wrappers for converting [`AsyncRead`] to [`Stream`] +and vice-versa in the [tokio-util] crate, see [`ReaderStream`] and +[`StreamReader`]. + +There are also utility traits that abstract the asynchronous buffering +necessary to write your own adaptors for encoding and decoding bytes to/from +your structured data, allowing to transform something that implements +[`AsyncRead`]/[`AsyncWrite`] into a [`Stream`]/[`Sink`], see [`Decoder`] and +[`Encoder`] in the [tokio-util::codec] module. + +[tokio-util]: https://docs.rs/tokio-util +[tokio-util::codec]: https://docs.rs/tokio-util/latest/tokio_util/codec/index.html + +# Standard input and output + +Tokio provides asynchronous APIs to standard [input], [output], and [error]. +These APIs are very similar to the ones provided by `std`, but they also +implement [`AsyncRead`] and [`AsyncWrite`]. + +Note that the standard input / output APIs **must** be used from the +context of the Tokio runtime, as they require Tokio-specific features to +function. Calling these functions outside of a Tokio runtime will panic. + +[input]: fn@stdin +[output]: fn@stdout +[error]: fn@stderr + +# `std` re-exports + +Additionally, [`Error`], [`ErrorKind`], [`Result`], and [`SeekFrom`] are +re-exported from `std::io` for ease of use. + +[`AsyncRead`]: trait@AsyncRead +[`AsyncWrite`]: trait@AsyncWrite +[`AsyncReadExt`]: trait@AsyncReadExt +[`AsyncWriteExt`]: trait@AsyncWriteExt +["codec"]: https://docs.rs/tokio-util/latest/tokio_util/codec/index.html +[`Encoder`]: https://docs.rs/tokio-util/latest/tokio_util/codec/trait.Encoder.html +[`Decoder`]: https://docs.rs/tokio-util/latest/tokio_util/codec/trait.Decoder.html +[`ReaderStream`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.ReaderStream.html +[`StreamReader`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.StreamReader.html +[`Error`]: struct@Error +[`ErrorKind`]: enum@ErrorKind +[`Result`]: type@Result +[`Read`]: std::io::Read +[`SeekFrom`]: enum@SeekFrom +[`Sink`]: https://docs.rs/futures/0.3/futures/sink/trait.Sink.html +[`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html +[`Write`]: std::io::Write + +```rust +pub mod io { /* ... */ } +``` + +### Modules + +## Module `bsd` + +**Attributes:** + +- `Other("#[(all(any(docsrs, target_os = \"freebsd\"), feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(target_os = \"freebsd\", feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(target_os = \"freebsd\", feature = \"net\")))]")` + +BSD-specific I/O types. + +```rust +pub mod bsd { /* ... */ } +``` + +### Re-exports + +#### Re-export `Aio` + +```rust +pub use poll_aio::Aio; +``` + +#### Re-export `AioEvent` + +```rust +pub use poll_aio::AioEvent; +``` + +#### Re-export `AioSource` + +```rust +pub use poll_aio::AioSource; +``` + +## Module `unix` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +Asynchronous IO structures specific to Unix-like operating systems. + +```rust +pub mod unix { /* ... */ } +``` + +### Re-exports + +#### Re-export `AsyncFd` + +```rust +pub use super::async_fd::AsyncFd; +``` + +#### Re-export `AsyncFdTryNewError` + +```rust +pub use super::async_fd::AsyncFdTryNewError; +``` + +#### Re-export `AsyncFdReadyGuard` + +```rust +pub use super::async_fd::AsyncFdReadyGuard; +``` + +#### Re-export `AsyncFdReadyMutGuard` + +```rust +pub use super::async_fd::AsyncFdReadyMutGuard; +``` + +#### Re-export `TryIoError` + +```rust +pub use super::async_fd::TryIoError; +``` + +### Re-exports + +#### Re-export `AsyncBufRead` + +```rust +pub use self::async_buf_read::AsyncBufRead; +``` + +#### Re-export `AsyncRead` + +```rust +pub use self::async_read::AsyncRead; +``` + +#### Re-export `AsyncSeek` + +```rust +pub use self::async_seek::AsyncSeek; +``` + +#### Re-export `AsyncWrite` + +```rust +pub use self::async_write::AsyncWrite; +``` + +#### Re-export `ReadBuf` + +```rust +pub use self::read_buf::ReadBuf; +``` + +#### Re-export `Error` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::io::Error; +``` + +#### Re-export `ErrorKind` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::io::ErrorKind; +``` + +#### Re-export `Result` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::io::Result; +``` + +#### Re-export `SeekFrom` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::io::SeekFrom; +``` + +#### Re-export `Interest` + +**Attributes:** + +- `Other("#[(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",)))]")` +- `Other("#[(docsrs,\ndoc(cfg(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",)))))]")` +- `Other("#[doc(cfg(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",))))]")` + +```rust +pub use interest::Interest; +``` + +#### Re-export `Ready` + +**Attributes:** + +- `Other("#[(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",)))]")` +- `Other("#[(docsrs,\ndoc(cfg(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",)))))]")` +- `Other("#[doc(cfg(any(feature = \"net\",\nall(tokio_unstable, feature = \"io-uring\", feature = \"rt\", feature = \"fs\",\ntarget_os = \"linux\",))))]")` + +```rust +pub use ready::Ready; +``` + +#### Re-export `stderr` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stderr::stderr; +``` + +#### Re-export `Stderr` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stderr::Stderr; +``` + +#### Re-export `stdin` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stdin::stdin; +``` + +#### Re-export `Stdin` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stdin::Stdin; +``` + +#### Re-export `stdout` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stdout::stdout; +``` + +#### Re-export `Stdout` + +**Attributes:** + +- `Other("#[(feature = \"io-std\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-std\")))]")` +- `Other("#[doc(cfg(feature = \"io-std\"))]")` + +```rust +pub use stdout::Stdout; +``` + +#### Re-export `split` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use split::split; +``` + +#### Re-export `ReadHalf` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use split::ReadHalf; +``` + +#### Re-export `WriteHalf` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use split::WriteHalf; +``` + +#### Re-export `join` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use join::join; +``` + +#### Re-export `Join` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use join::Join; +``` + +#### Re-export `copy` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::copy; +``` + +#### Re-export `copy_bidirectional` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::copy_bidirectional; +``` + +#### Re-export `copy_bidirectional_with_sizes` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::copy_bidirectional_with_sizes; +``` + +#### Re-export `copy_buf` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::copy_buf; +``` + +#### Re-export `duplex` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::duplex; +``` + +#### Re-export `empty` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::empty; +``` + +#### Re-export `repeat` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::repeat; +``` + +#### Re-export `sink` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::sink; +``` + +#### Re-export `simplex` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::simplex; +``` + +#### Re-export `AsyncBufReadExt` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::AsyncBufReadExt; +``` + +#### Re-export `AsyncReadExt` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::AsyncReadExt; +``` + +#### Re-export `AsyncSeekExt` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::AsyncSeekExt; +``` + +#### Re-export `AsyncWriteExt` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::AsyncWriteExt; +``` + +#### Re-export `BufReader` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::BufReader; +``` + +#### Re-export `BufStream` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::BufStream; +``` + +#### Re-export `BufWriter` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::BufWriter; +``` + +#### Re-export `Chain` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Chain; +``` + +#### Re-export `DuplexStream` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::DuplexStream; +``` + +#### Re-export `Empty` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Empty; +``` + +#### Re-export `Lines` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Lines; +``` + +#### Re-export `Repeat` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Repeat; +``` + +#### Re-export `Sink` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Sink; +``` + +#### Re-export `Split` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Split; +``` + +#### Re-export `Take` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::Take; +``` + +#### Re-export `SimplexStream` + +**Attributes:** + +- `Other("#[(feature = \"io-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"io-util\")))]")` +- `Other("#[doc(cfg(feature = \"io-util\"))]")` + +```rust +pub use util::SimplexStream; +``` + +## Module `net` + +**Attributes:** + +- `Other("#[(not(loom))]")` + +TCP/UDP/Unix bindings for `tokio`. + +This module contains the TCP/UDP/Unix networking types, similar to the standard +library, which can be used to implement networking protocols. + +# Organization + +* [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP +* [`UdpSocket`] provides functionality for communication over UDP +* [`UnixListener`] and [`UnixStream`] provide functionality for communication over a + Unix Domain Stream Socket **(available on Unix only)** +* [`UnixDatagram`] provides functionality for communication + over Unix Domain Datagram Socket **(available on Unix only)** +* [`tokio::net::unix::pipe`] for FIFO pipes **(available on Unix only)** +* [`tokio::net::windows::named_pipe`] for Named Pipes **(available on Windows only)** + +For IO resources not available in `tokio::net`, you can use [`AsyncFd`]. + +[`TcpListener`]: TcpListener +[`TcpStream`]: TcpStream +[`UdpSocket`]: UdpSocket +[`UnixListener`]: UnixListener +[`UnixStream`]: UnixStream +[`UnixDatagram`]: UnixDatagram +[`tokio::net::unix::pipe`]: unix::pipe +[`tokio::net::windows::named_pipe`]: windows::named_pipe +[`AsyncFd`]: crate::io::unix::AsyncFd + +```rust +pub mod net { /* ... */ } +``` + +### Modules + +## Module `tcp` + +**Attributes:** + +- `Other("#[(feature = \"net\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"net\")))]")` +- `Other("#[doc(cfg(feature = \"net\"))]")` + +TCP utility types. + +```rust +pub mod tcp { /* ... */ } +``` + +### Re-exports + +#### Re-export `ReadHalf` + +```rust +pub use split::ReadHalf; +``` + +#### Re-export `WriteHalf` + +```rust +pub use split::WriteHalf; +``` + +#### Re-export `OwnedReadHalf` + +```rust +pub use split_owned::OwnedReadHalf; +``` + +#### Re-export `OwnedWriteHalf` + +```rust +pub use split_owned::OwnedWriteHalf; +``` + +#### Re-export `ReuniteError` + +```rust +pub use split_owned::ReuniteError; +``` + +## Module `unix` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +Unix specific network types. + +```rust +pub mod unix { /* ... */ } +``` + +### Modules + +## Module `pipe` + +Unix pipe types. + +```rust +pub mod pipe { /* ... */ } +``` + +### Types + +#### Struct `OpenOptions` + +Options and flags which can be used to configure how a FIFO file is opened. + +This builder allows configuring how to create a pipe end from a FIFO file. +Generally speaking, when using `OpenOptions`, you'll first call [`new`], +then chain calls to methods to set each option, then call either +[`open_receiver`] or [`open_sender`], passing the path of the FIFO file you +are trying to open. This will give you a [`io::Result`] with a pipe end +inside that you can further operate on. + +[`new`]: OpenOptions::new +[`open_receiver`]: OpenOptions::open_receiver +[`open_sender`]: OpenOptions::open_sender + +# Examples + +Opening a pair of pipe ends from a FIFO file: + +```no_run +use tokio::net::unix::pipe; +# use std::error::Error; + +const FIFO_NAME: &str = "path/to/a/fifo"; + +# async fn dox() -> Result<(), Box> { +let rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?; +let tx = pipe::OpenOptions::new().open_sender(FIFO_NAME)?; +# Ok(()) +# } +``` + +Opening a [`Sender`] on Linux when you are sure the file is a FIFO: + +```ignore +use tokio::net::unix::pipe; +use nix::{unistd::mkfifo, sys::stat::Mode}; +# use std::error::Error; + +// Our program has exclusive access to this path. +const FIFO_NAME: &str = "path/to/a/new/fifo"; + +# async fn dox() -> Result<(), Box> { +mkfifo(FIFO_NAME, Mode::S_IRWXU)?; +let tx = pipe::OpenOptions::new() + .read_write(true) + .unchecked(true) + .open_sender(FIFO_NAME)?; +# Ok(()) +# } +``` + +```rust +pub struct OpenOptions { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> OpenOptions { /* ... */ } + ``` + Creates a blank new set of options ready for configuration. + +- ```rust + pub fn read_write(self: &mut Self, value: bool) -> &mut Self { /* ... */ } + ``` + Sets the option for read-write access. + +- ```rust + pub fn unchecked(self: &mut Self, value: bool) -> &mut Self { /* ... */ } + ``` + Sets the option to skip the check for FIFO file type. + +- ```rust + pub fn open_receiver>(self: &Self, path: P) -> io::Result { /* ... */ } + ``` + Creates a [`Receiver`] from a FIFO file with the options specified by `self`. + +- ```rust + pub fn open_sender>(self: &Self, path: P) -> io::Result { /* ... */ } + ``` + Creates a [`Sender`] from a FIFO file with the options specified by `self`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> OpenOptions { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> OpenOptions { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Sender` + +Writing end of a Unix pipe. + +It can be constructed from a FIFO file with [`OpenOptions::open_sender`]. + +Opening a named pipe for writing involves a few steps. +Call to [`OpenOptions::open_sender`] might fail with an error indicating +different things: + +* [`io::ErrorKind::NotFound`] - There is no file at the specified path. +* [`io::ErrorKind::InvalidInput`] - The file exists, but it is not a FIFO. +* [`ENXIO`] - The file is a FIFO, but no process has it open for reading. + Sleep for a while and try again. +* Other OS errors not specific to opening FIFO files. + +Opening a `Sender` from a FIFO file should look like this: + +```no_run +use tokio::net::unix::pipe; +use tokio::time::{self, Duration}; + +const FIFO_NAME: &str = "path/to/a/fifo"; + +# async fn dox() -> Result<(), Box> { +// Wait for a reader to open the file. +let tx = loop { + match pipe::OpenOptions::new().open_sender(FIFO_NAME) { + Ok(tx) => break tx, + Err(e) if e.raw_os_error() == Some(libc::ENXIO) => {}, + Err(e) => return Err(e.into()), + } + + time::sleep(Duration::from_millis(50)).await; +}; +# Ok(()) +# } +``` + +On Linux, it is possible to create a `Sender` without waiting in a sleeping +loop. This is done by opening a named pipe in read-write access mode with +`OpenOptions::read_write`. This way, a `Sender` can at the same time hold +both a writing end and a reading end, and the latter allows to open a FIFO +without [`ENXIO`] error since the pipe is open for reading as well. + +`Sender` cannot be used to read from a pipe, so in practice the read access +is only used when a FIFO is opened. However, using a `Sender` in read-write +mode **may lead to lost data**, because written data will be dropped by the +system as soon as all pipe ends are closed. To avoid lost data you have to +make sure that a reading end has been opened before dropping a `Sender`. + +Note that using read-write access mode with FIFO files is not defined by +the POSIX standard and it is only guaranteed to work on Linux. + +```ignore +use tokio::io::AsyncWriteExt; +use tokio::net::unix::pipe; + +const FIFO_NAME: &str = "path/to/a/fifo"; + +# async fn dox() -> Result<(), Box> { +let mut tx = pipe::OpenOptions::new() + .read_write(true) + .open_sender(FIFO_NAME)?; + +// Asynchronously write to the pipe before a reader. +tx.write_all(b"hello world").await?; +# Ok(()) +# } +``` + +[`ENXIO`]: https://docs.rs/libc/latest/libc/constant.ENXIO.html + +```rust +pub struct Sender { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn from_file(file: File) -> io::Result { /* ... */ } + ``` + Creates a new `Sender` from a [`File`]. + +- ```rust + pub fn from_owned_fd(owned_fd: OwnedFd) -> io::Result { /* ... */ } + ``` + Creates a new `Sender` from an [`OwnedFd`]. + +- ```rust + pub fn from_file_unchecked(file: File) -> io::Result { /* ... */ } + ``` + Creates a new `Sender` from a [`File`] without checking pipe properties. + +- ```rust + pub fn from_owned_fd_unchecked(owned_fd: OwnedFd) -> io::Result { /* ... */ } + ``` + Creates a new `Sender` from an [`OwnedFd`] without checking pipe properties. + +- ```rust + pub async fn ready(self: &Self, interest: Interest) -> io::Result { /* ... */ } + ``` + Waits for any of the requested ready states. + +- ```rust + pub async fn writable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become writable. + +- ```rust + pub fn poll_write_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for write readiness. + +- ```rust + pub fn try_write(self: &Self, buf: &[u8]) -> io::Result { /* ... */ } + ``` + Tries to write a buffer to the pipe, returning how many bytes were + +- ```rust + pub fn try_write_vectored(self: &Self, buf: &[io::IoSlice<''_>]) -> io::Result { /* ... */ } + ``` + Tries to write several buffers to the pipe, returning how many bytes + +- ```rust + pub fn into_blocking_fd(self: Self) -> io::Result { /* ... */ } + ``` + Converts the pipe into an [`OwnedFd`] in blocking mode. + +- ```rust + pub fn into_nonblocking_fd(self: Self) -> io::Result { /* ... */ } + ``` + Converts the pipe into an [`OwnedFd`] in nonblocking mode. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsFd** + - ```rust + fn as_fd(self: &Self) -> BorrowedFd<''_> { /* ... */ } + ``` + +- **AsRawFd** + - ```rust + fn as_raw_fd(self: &Self) -> RawFd { /* ... */ } + ``` + +- **AsyncWrite** + - ```rust + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &[u8]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<''_>, bufs: &[io::IoSlice<''_>]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn is_write_vectored(self: &Self) -> bool { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncWriteExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Receiver` + +Reading end of a Unix pipe. + +It can be constructed from a FIFO file with [`OpenOptions::open_receiver`]. + +# Examples + +Receiving messages from a named pipe in a loop: + +```no_run +use tokio::net::unix::pipe; +use tokio::io::{self, AsyncReadExt}; + +const FIFO_NAME: &str = "path/to/a/fifo"; + +# async fn dox() -> Result<(), Box> { +let mut rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?; +loop { + let mut msg = vec![0; 256]; + match rx.read_exact(&mut msg).await { + Ok(_) => { + /* handle the message */ + } + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { + // Writing end has been closed, we should reopen the pipe. + rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?; + } + Err(e) => return Err(e.into()), + } +} +# } +``` + +On Linux, you can use a `Receiver` in read-write access mode to implement +resilient reading from a named pipe. Unlike `Receiver` opened in read-only +mode, read from a pipe in read-write mode will not fail with `UnexpectedEof` +when the writing end is closed. This way, a `Receiver` can asynchronously +wait for the next writer to open the pipe. + +You should not use functions waiting for EOF such as [`read_to_end`] with +a `Receiver` in read-write access mode, since it **may wait forever**. +`Receiver` in this mode also holds an open writing end, which prevents +receiving EOF. + +To set the read-write access mode you can use `OpenOptions::read_write`. +Note that using read-write access mode with FIFO files is not defined by +the POSIX standard and it is only guaranteed to work on Linux. + +```ignore +use tokio::net::unix::pipe; +use tokio::io::AsyncReadExt; +# use std::error::Error; + +const FIFO_NAME: &str = "path/to/a/fifo"; + +# async fn dox() -> Result<(), Box> { +let mut rx = pipe::OpenOptions::new() + .read_write(true) + .open_receiver(FIFO_NAME)?; +loop { + let mut msg = vec![0; 256]; + rx.read_exact(&mut msg).await?; + /* handle the message */ +} +# } +``` + +[`read_to_end`]: crate::io::AsyncReadExt::read_to_end + +```rust +pub struct Receiver { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn from_file(file: File) -> io::Result { /* ... */ } + ``` + Creates a new `Receiver` from a [`File`]. + +- ```rust + pub fn from_owned_fd(owned_fd: OwnedFd) -> io::Result { /* ... */ } + ``` + Creates a new `Receiver` from an [`OwnedFd`]. + +- ```rust + pub fn from_file_unchecked(file: File) -> io::Result { /* ... */ } + ``` + Creates a new `Receiver` from a [`File`] without checking pipe properties. + +- ```rust + pub fn from_owned_fd_unchecked(owned_fd: OwnedFd) -> io::Result { /* ... */ } + ``` + Creates a new `Receiver` from an [`OwnedFd`] without checking pipe properties. + +- ```rust + pub async fn ready(self: &Self, interest: Interest) -> io::Result { /* ... */ } + ``` + Waits for any of the requested ready states. + +- ```rust + pub async fn readable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become readable. + +- ```rust + pub fn poll_read_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for read readiness. + +- ```rust + pub fn try_read(self: &Self, buf: &mut [u8]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffer, returning how + +- ```rust + pub fn try_read_vectored(self: &Self, bufs: &mut [io::IoSliceMut<''_>]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffers, returning + +- ```rust + pub fn try_read_buf(self: &Self, buf: &mut B) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffer, advancing the + +- ```rust + pub fn into_blocking_fd(self: Self) -> io::Result { /* ... */ } + ``` + Converts the pipe into an [`OwnedFd`] in blocking mode. + +- ```rust + pub fn into_nonblocking_fd(self: Self) -> io::Result { /* ... */ } + ``` + Converts the pipe into an [`OwnedFd`] in nonblocking mode. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsFd** + - ```rust + fn as_fd(self: &Self) -> BorrowedFd<''_> { /* ... */ } + ``` + +- **AsRawFd** + - ```rust + fn as_raw_fd(self: &Self) -> RawFd { /* ... */ } + ``` + +- **AsyncRead** + - ```rust + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &mut ReadBuf<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncReadExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `pipe` + +Creates a new anonymous Unix pipe. + +This function will open a new pipe and associate both pipe ends with the default +event loop. + +If you need to create a pipe for communication with a spawned process, you can +use [`Stdio::piped()`] instead. + +[`Stdio::piped()`]: std::process::Stdio::piped + +# Errors + +If creating a pipe fails, this function will return with the related OS error. + +# Examples + +Create a pipe and pass the writing end to a spawned process. + +```no_run +use tokio::net::unix::pipe; +use tokio::process::Command; +# use tokio::io::AsyncReadExt; +# use std::error::Error; + +# async fn dox() -> Result<(), Box> { +let (tx, mut rx) = pipe::pipe()?; +let mut buffer = String::new(); + +let status = Command::new("echo") + .arg("Hello, world!") + .stdout(tx.into_blocking_fd()?) + .status(); +rx.read_to_string(&mut buffer).await?; + +assert!(status.await?.success()); +assert_eq!(buffer, "Hello, world!\n"); +# Ok(()) +# } +``` + +# Panics + +This function panics if it is not called from within a runtime with +IO enabled. + +The runtime is usually set implicitly when this function is called +from a future driven by a tokio runtime, otherwise runtime can be set +explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function. + +```rust +pub fn pipe() -> io::Result<(Sender, Receiver)> { /* ... */ } +``` + +### Types + +#### Type Alias `uid_t` + +**Attributes:** + +- `Other("#[allow(non_camel_case_types)]")` + +A type representing user ID. + +```rust +pub type uid_t = u32; +``` + +#### Type Alias `gid_t` + +**Attributes:** + +- `Other("#[allow(non_camel_case_types)]")` + +A type representing group ID. + +```rust +pub type gid_t = u32; +``` + +#### Type Alias `pid_t` + +**Attributes:** + +- `Other("#[allow(non_camel_case_types)]")` + +A type representing process and process group IDs. + +```rust +pub type pid_t = i32; +``` + +### Re-exports + +#### Re-export `ReadHalf` + +```rust +pub use split::ReadHalf; +``` + +#### Re-export `WriteHalf` + +```rust +pub use split::WriteHalf; +``` + +#### Re-export `OwnedReadHalf` + +```rust +pub use split_owned::OwnedReadHalf; +``` + +#### Re-export `OwnedWriteHalf` + +```rust +pub use split_owned::OwnedWriteHalf; +``` + +#### Re-export `ReuniteError` + +```rust +pub use split_owned::ReuniteError; +``` + +#### Re-export `SocketAddr` + +```rust +pub use socketaddr::SocketAddr; +``` + +#### Re-export `UCred` + +```rust +pub use ucred::UCred; +``` + +## Module `windows` + +**Attributes:** + +- `Other("#[(all(any(all(doc, docsrs), windows), feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(windows, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(windows, feature = \"net\")))]")` + +Windows specific network types. + +```rust +pub mod windows { /* ... */ } +``` + +### Modules + +## Module `named_pipe` + +Tokio support for [Windows named pipes]. + +[Windows named pipes]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes + +```rust +pub mod named_pipe { /* ... */ } +``` + +### Types + +#### Struct `NamedPipeServer` + +A [Windows named pipe] server. + +Accepting client connections involves creating a server with +[`ServerOptions::create`] and waiting for clients to connect using +[`NamedPipeServer::connect`]. + +To avoid having clients sporadically fail with +[`std::io::ErrorKind::NotFound`] when they connect to a server, we must +ensure that at least one server instance is available at all times. This +means that the typical listen loop for a server is a bit involved, because +we have to ensure that we never drop a server accidentally while a client +might connect. + +So a correctly implemented server looks like this: + +```no_run +use std::io; +use tokio::net::windows::named_pipe::ServerOptions; + +const PIPE_NAME: &str = r"\\.\pipe\named-pipe-idiomatic-server"; + +# #[tokio::main] async fn main() -> std::io::Result<()> { +// The first server needs to be constructed early so that clients can +// be correctly connected. Otherwise calling .wait will cause the client to +// error. +// +// Here we also make use of `first_pipe_instance`, which will ensure that +// there are no other servers up and running already. +let mut server = ServerOptions::new() + .first_pipe_instance(true) + .create(PIPE_NAME)?; + +// Spawn the server loop. +let server = tokio::spawn(async move { + loop { + // Wait for a client to connect. + server.connect().await?; + let connected_client = server; + + // Construct the next server to be connected before sending the one + // we already have of onto a task. This ensures that the server + // isn't closed (after it's done in the task) before a new one is + // available. Otherwise the client might error with + // `io::ErrorKind::NotFound`. + server = ServerOptions::new().create(PIPE_NAME)?; + + let client = tokio::spawn(async move { + /* use the connected client */ +# Ok::<_, std::io::Error>(()) + }); +# if true { break } // needed for type inference to work + } + + Ok::<_, io::Error>(()) +}); + +/* do something else not server related here */ +# Ok(()) } +``` + +[Windows named pipe]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes + +```rust +pub struct NamedPipeServer { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub unsafe fn from_raw_handle(handle: RawHandle) -> io::Result { /* ... */ } + ``` + Constructs a new named pipe server from the specified raw handle. + +- ```rust + pub fn info(self: &Self) -> io::Result { /* ... */ } + ``` + Retrieves information about the named pipe the server is associated + +- ```rust + pub async fn connect(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Enables a named pipe server process to wait for a client process to + +- ```rust + pub fn disconnect(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Disconnects the server end of a named pipe instance from a client + +- ```rust + pub async fn ready(self: &Self, interest: Interest) -> io::Result { /* ... */ } + ``` + Waits for any of the requested ready states. + +- ```rust + pub async fn readable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become readable. + +- ```rust + pub fn poll_read_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for read readiness. + +- ```rust + pub fn try_read(self: &Self, buf: &mut [u8]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffer, returning how + +- ```rust + pub fn try_read_vectored(self: &Self, bufs: &mut [io::IoSliceMut<''_>]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffers, returning + +- ```rust + pub fn try_read_buf(self: &Self, buf: &mut B) -> io::Result { /* ... */ } + ``` + Tries to read data from the stream into the provided buffer, advancing the + +- ```rust + pub async fn writable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become writable. + +- ```rust + pub fn poll_write_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for write readiness. + +- ```rust + pub fn try_write(self: &Self, buf: &[u8]) -> io::Result { /* ... */ } + ``` + Tries to write a buffer to the pipe, returning how many bytes were + +- ```rust + pub fn try_write_vectored(self: &Self, buf: &[io::IoSlice<''_>]) -> io::Result { /* ... */ } + ``` + Tries to write several buffers to the pipe, returning how many bytes + +- ```rust + pub fn try_io io::Result: FnOnce() -> io::Result>(self: &Self, interest: Interest, f: impl FnOnce() -> io::Result) -> io::Result { /* ... */ } + ``` + Tries to read or write from the pipe using a user-provided IO operation. + +- ```rust + pub async fn async_io io::Result: FnMut() -> io::Result>(self: &Self, interest: Interest, f: impl FnMut() -> io::Result) -> io::Result { /* ... */ } + ``` + Reads or writes from the pipe using a user-provided IO operation. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsHandle** + - ```rust + fn as_handle(self: &Self) -> BorrowedHandle<''_> { /* ... */ } + ``` + +- **AsRawHandle** + - ```rust + fn as_raw_handle(self: &Self) -> RawHandle { /* ... */ } + ``` + +- **AsyncRead** + - ```rust + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &mut ReadBuf<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncReadExt** +- **AsyncWrite** + - ```rust + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &[u8]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<''_>, bufs: &[io::IoSlice<''_>]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncWriteExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `NamedPipeClient` + +A [Windows named pipe] client. + +Constructed using [`ClientOptions::open`]. + +Connecting a client correctly involves a few steps. When connecting through +[`ClientOptions::open`], it might error indicating one of two things: + +* [`std::io::ErrorKind::NotFound`] - There is no server available. +* [`ERROR_PIPE_BUSY`] - There is a server available, but it is busy. Sleep + for a while and try again. + +So a correctly implemented client looks like this: + +```no_run +use std::time::Duration; +use tokio::net::windows::named_pipe::ClientOptions; +use tokio::time; +use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY; + +const PIPE_NAME: &str = r"\\.\pipe\named-pipe-idiomatic-client"; + +# #[tokio::main] async fn main() -> std::io::Result<()> { +let client = loop { + match ClientOptions::new().open(PIPE_NAME) { + Ok(client) => break client, + Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => (), + Err(e) => return Err(e), + } + + time::sleep(Duration::from_millis(50)).await; +}; + +/* use the connected client */ +# Ok(()) } +``` + +[`ERROR_PIPE_BUSY`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Foundation/constant.ERROR_PIPE_BUSY.html +[Windows named pipe]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes + +```rust +pub struct NamedPipeClient { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub unsafe fn from_raw_handle(handle: RawHandle) -> io::Result { /* ... */ } + ``` + Constructs a new named pipe client from the specified raw handle. + +- ```rust + pub fn info(self: &Self) -> io::Result { /* ... */ } + ``` + Retrieves information about the named pipe the client is associated + +- ```rust + pub async fn ready(self: &Self, interest: Interest) -> io::Result { /* ... */ } + ``` + Waits for any of the requested ready states. + +- ```rust + pub async fn readable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become readable. + +- ```rust + pub fn poll_read_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for read readiness. + +- ```rust + pub fn try_read(self: &Self, buf: &mut [u8]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffer, returning how + +- ```rust + pub fn try_read_vectored(self: &Self, bufs: &mut [io::IoSliceMut<''_>]) -> io::Result { /* ... */ } + ``` + Tries to read data from the pipe into the provided buffers, returning + +- ```rust + pub fn try_read_buf(self: &Self, buf: &mut B) -> io::Result { /* ... */ } + ``` + Tries to read data from the stream into the provided buffer, advancing the + +- ```rust + pub async fn writable(self: &Self) -> io::Result<()> { /* ... */ } + ``` + Waits for the pipe to become writable. + +- ```rust + pub fn poll_write_ready(self: &Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls for write readiness. + +- ```rust + pub fn try_write(self: &Self, buf: &[u8]) -> io::Result { /* ... */ } + ``` + Tries to write a buffer to the pipe, returning how many bytes were + +- ```rust + pub fn try_write_vectored(self: &Self, buf: &[io::IoSlice<''_>]) -> io::Result { /* ... */ } + ``` + Tries to write several buffers to the pipe, returning how many bytes + +- ```rust + pub fn try_io io::Result: FnOnce() -> io::Result>(self: &Self, interest: Interest, f: impl FnOnce() -> io::Result) -> io::Result { /* ... */ } + ``` + Tries to read or write from the pipe using a user-provided IO operation. + +- ```rust + pub async fn async_io io::Result: FnMut() -> io::Result>(self: &Self, interest: Interest, f: impl FnMut() -> io::Result) -> io::Result { /* ... */ } + ``` + Reads or writes from the pipe using a user-provided IO operation. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsHandle** + - ```rust + fn as_handle(self: &Self) -> BorrowedHandle<''_> { /* ... */ } + ``` + +- **AsRawHandle** + - ```rust + fn as_raw_handle(self: &Self) -> RawHandle { /* ... */ } + ``` + +- **AsyncRead** + - ```rust + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &mut ReadBuf<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncReadExt** +- **AsyncWrite** + - ```rust + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &[u8]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<''_>, bufs: &[io::IoSlice<''_>]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncWriteExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `ServerOptions` + +A builder structure for construct a named pipe with named pipe-specific +options. This is required to use for named pipe servers who wants to modify +pipe-related options. + +See [`ServerOptions::create`]. + +```rust +pub struct ServerOptions { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> ServerOptions { /* ... */ } + ``` + Creates a new named pipe builder with the default settings. + +- ```rust + pub fn pipe_mode(self: &mut Self, pipe_mode: PipeMode) -> &mut Self { /* ... */ } + ``` + The pipe mode. + +- ```rust + pub fn access_inbound(self: &mut Self, allowed: bool) -> &mut Self { /* ... */ } + ``` + The flow of data in the pipe goes from client to server only. + +- ```rust + pub fn access_outbound(self: &mut Self, allowed: bool) -> &mut Self { /* ... */ } + ``` + The flow of data in the pipe goes from server to client only. + +- ```rust + pub fn first_pipe_instance(self: &mut Self, first: bool) -> &mut Self { /* ... */ } + ``` + If you attempt to create multiple instances of a pipe with this flag + +- ```rust + pub fn write_dac(self: &mut Self, requested: bool) -> &mut Self { /* ... */ } + ``` + Requests permission to modify the pipe's discretionary access control list. + +- ```rust + pub fn write_owner(self: &mut Self, requested: bool) -> &mut Self { /* ... */ } + ``` + Requests permission to modify the pipe's owner. + +- ```rust + pub fn access_system_security(self: &mut Self, requested: bool) -> &mut Self { /* ... */ } + ``` + Requests permission to modify the pipe's system access control list. + +- ```rust + pub fn reject_remote_clients(self: &mut Self, reject: bool) -> &mut Self { /* ... */ } + ``` + Indicates whether this server can accept remote clients or not. Remote + +- ```rust + pub fn max_instances(self: &mut Self, instances: usize) -> &mut Self { /* ... */ } + ``` + The maximum number of instances that can be created for this pipe. The + +- ```rust + pub fn out_buffer_size(self: &mut Self, buffer: u32) -> &mut Self { /* ... */ } + ``` + The number of bytes to reserve for the output buffer. + +- ```rust + pub fn in_buffer_size(self: &mut Self, buffer: u32) -> &mut Self { /* ... */ } + ``` + The number of bytes to reserve for the input buffer. + +- ```rust + pub fn create: AsRef>(self: &Self, addr: impl AsRef) -> io::Result { /* ... */ } + ``` + Creates the named pipe identified by `addr` for use as a server. + +- ```rust + pub unsafe fn create_with_security_attributes_raw: AsRef>(self: &Self, addr: impl AsRef, attrs: *mut c_void) -> io::Result { /* ... */ } + ``` + Creates the named pipe identified by `addr` for use as a server. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> ServerOptions { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `ClientOptions` + +A builder suitable for building and interacting with named pipes from the +client side. + +See [`ClientOptions::open`]. + +```rust +pub struct ClientOptions { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Creates a new named pipe builder with the default settings. + +- ```rust + pub fn read(self: &mut Self, allowed: bool) -> &mut Self { /* ... */ } + ``` + If the client supports reading data. This is enabled by default. + +- ```rust + pub fn write(self: &mut Self, allowed: bool) -> &mut Self { /* ... */ } + ``` + If the created pipe supports writing data. This is enabled by default. + +- ```rust + pub fn security_qos_flags(self: &mut Self, flags: u32) -> &mut Self { /* ... */ } + ``` + Sets qos flags which are combined with other flags and attributes in the + +- ```rust + pub fn pipe_mode(self: &mut Self, pipe_mode: PipeMode) -> &mut Self { /* ... */ } + ``` + The pipe mode. + +- ```rust + pub fn open: AsRef>(self: &Self, addr: impl AsRef) -> io::Result { /* ... */ } + ``` + Opens the named pipe identified by `addr`. + +- ```rust + pub unsafe fn open_with_security_attributes_raw: AsRef>(self: &Self, addr: impl AsRef, attrs: *mut c_void) -> io::Result { /* ... */ } + ``` + Opens the named pipe identified by `addr`. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> ClientOptions { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `PipeMode` + +**Attributes:** + +- `NonExhaustive` + +The pipe mode of a named pipe. + +Set through [`ServerOptions::pipe_mode`]. + +```rust +pub enum PipeMode { + Byte, + Message, +} +``` + +##### Variants + +###### `Byte` + +Data is written to the pipe as a stream of bytes. The pipe does not +distinguish bytes written during different write operations. + +Corresponds to [`PIPE_TYPE_BYTE`]. + +[`PIPE_TYPE_BYTE`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_TYPE_BYTE.html + +###### `Message` + +Data is written to the pipe as a stream of messages. The pipe treats the +bytes written during each write operation as a message unit. Any reading +on a named pipe returns [`ERROR_MORE_DATA`] when a message is not read +completely. + +Corresponds to [`PIPE_TYPE_MESSAGE`]. + +[`ERROR_MORE_DATA`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Foundation/constant.ERROR_MORE_DATA.html +[`PIPE_TYPE_MESSAGE`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_TYPE_MESSAGE.html + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> PipeMode { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &PipeMode) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `PipeEnd` + +**Attributes:** + +- `NonExhaustive` + +Indicates the end of a named pipe. + +```rust +pub enum PipeEnd { + Client, + Server, +} +``` + +##### Variants + +###### `Client` + +The named pipe refers to the client end of a named pipe instance. + +Corresponds to [`PIPE_CLIENT_END`]. + +[`PIPE_CLIENT_END`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_CLIENT_END.html + +###### `Server` + +The named pipe refers to the server end of a named pipe instance. + +Corresponds to [`PIPE_SERVER_END`]. + +[`PIPE_SERVER_END`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_SERVER_END.html + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> PipeEnd { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &PipeEnd) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `PipeInfo` + +**Attributes:** + +- `NonExhaustive` + +Information about a named pipe. + +Constructed through [`NamedPipeServer::info`] or [`NamedPipeClient::info`]. + +```rust +pub struct PipeInfo { + pub mode: PipeMode, + pub end: PipeEnd, + pub max_instances: u32, + pub out_buffer_size: u32, + pub in_buffer_size: u32, +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `mode` | `PipeMode` | Indicates the mode of a named pipe. | +| `end` | `PipeEnd` | Indicates the end of a named pipe. | +| `max_instances` | `u32` | The maximum number of instances that can be created for this pipe. | +| `out_buffer_size` | `u32` | The number of bytes to reserve for the output buffer. | +| `in_buffer_size` | `u32` | The number of bytes to reserve for the input buffer. | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> PipeInfo { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Re-exports + +#### Re-export `ToSocketAddrs` + +```rust +pub use addr::ToSocketAddrs; +``` + +#### Re-export `lookup_host` + +**Attributes:** + +- `Other("#[(feature = \"net\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"net\")))]")` +- `Other("#[doc(cfg(feature = \"net\"))]")` + +```rust +pub use lookup_host::lookup_host; +``` + +#### Re-export `TcpListener` + +**Attributes:** + +- `Other("#[(feature = \"net\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"net\")))]")` +- `Other("#[doc(cfg(feature = \"net\"))]")` + +```rust +pub use tcp::listener::TcpListener; +``` + +#### Re-export `TcpStream` + +**Attributes:** + +- `Other("#[(feature = \"net\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"net\")))]")` +- `Other("#[doc(cfg(feature = \"net\"))]")` + +```rust +pub use tcp::stream::TcpStream; +``` + +#### Re-export `TcpSocket` + +**Attributes:** + +- `Other("#[(not(target_os = \"wasi\"))]")` + +```rust +pub use tcp::socket::TcpSocket; +``` + +#### Re-export `UdpSocket` + +**Attributes:** + +- `Other("#[(not(target_os = \"wasi\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use udp::UdpSocket; +``` + +#### Re-export `UnixDatagram` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +```rust +pub use unix::datagram::socket::UnixDatagram; +``` + +#### Re-export `UnixListener` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +```rust +pub use unix::listener::UnixListener; +``` + +#### Re-export `UnixStream` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +```rust +pub use unix::stream::UnixStream; +``` + +#### Re-export `UnixSocket` + +**Attributes:** + +- `Other("#[(all(unix, feature = \"net\"))]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"net\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"net\")))]")` + +```rust +pub use unix::socket::UnixSocket; +``` + +## Module `process` + +**Attributes:** + +- `Other("#[(feature = \"process\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"process\")))]")` +- `Other("#[doc(cfg(feature = \"process\"))]")` +- `Other("#[(not(loom))]")` +- `Other("#[(not(target_os = \"wasi\"))]")` + +An implementation of asynchronous process management for Tokio. + +This module provides a [`Command`] struct that imitates the interface of the +[`std::process::Command`] type in the standard library, but provides asynchronous versions of +functions that create processes. These functions (`spawn`, `status`, `output` and their +variants) return "future aware" types that interoperate with Tokio. The asynchronous process +support is provided through signal handling on Unix and system APIs on Windows. + +[`std::process::Command`]: std::process::Command + +# Examples + +Here's an example program which will spawn `echo hello world` and then wait +for it complete. + +```no_run +use tokio::process::Command; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // The usage is similar as with the standard library's `Command` type + let mut child = Command::new("echo") + .arg("hello") + .arg("world") + .spawn() + .expect("failed to spawn"); + + // Await until the command completes + let status = child.wait().await?; + println!("the command exited with: {}", status); + Ok(()) +} +``` + +Next, let's take a look at an example where we not only spawn `echo hello +world` but we also capture its output. + +```no_run +use tokio::process::Command; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Like above, but use `output` which returns a future instead of + // immediately returning the `Child`. + let output = Command::new("echo").arg("hello").arg("world") + .output(); + + let output = output.await?; + + assert!(output.status.success()); + assert_eq!(output.stdout, b"hello world\n"); + Ok(()) +} +``` + +We can also read input line by line. + +```no_run +use tokio::io::{BufReader, AsyncBufReadExt}; +use tokio::process::Command; + +use std::process::Stdio; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let mut cmd = Command::new("cat"); + + // Specify that we want the command's standard output piped back to us. + // By default, standard input/output/error will be inherited from the + // current process (for example, this means that standard input will + // come from the keyboard and standard output/error will go directly to + // the terminal if this process is invoked from the command line). + cmd.stdout(Stdio::piped()); + + let mut child = cmd.spawn() + .expect("failed to spawn command"); + + let stdout = child.stdout.take() + .expect("child did not have a handle to stdout"); + + let mut reader = BufReader::new(stdout).lines(); + + // Ensure the child process is spawned in the runtime so it can + // make progress on its own while we await for any output. + tokio::spawn(async move { + let status = child.wait().await + .expect("child process encountered an error"); + + println!("child status was: {}", status); + }); + + while let Some(line) = reader.next_line().await? { + println!("Line: {}", line); + } + + Ok(()) +} +``` + +Here is another example using `sort` writing into the child process +standard input, capturing the output of the sorted text. + +```no_run +use tokio::io::AsyncWriteExt; +use tokio::process::Command; + +use std::process::Stdio; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let mut cmd = Command::new("sort"); + + // Specifying that we want pipe both the output and the input. + // Similarly to capturing the output, by configuring the pipe + // to stdin it can now be used as an asynchronous writer. + cmd.stdout(Stdio::piped()); + cmd.stdin(Stdio::piped()); + + let mut child = cmd.spawn().expect("failed to spawn command"); + + // These are the animals we want to sort + let animals: &[&str] = &["dog", "bird", "frog", "cat", "fish"]; + + let mut stdin = child + .stdin + .take() + .expect("child did not have a handle to stdin"); + + // Write our animals to the child process + // Note that the behavior of `sort` is to buffer _all input_ before writing any output. + // In the general sense, it is recommended to write to the child in a separate task as + // awaiting its exit (or output) to avoid deadlocks (for example, the child tries to write + // some output but gets stuck waiting on the parent to read from it, meanwhile the parent + // is stuck waiting to write its input completely before reading the output). + stdin + .write(animals.join("\n").as_bytes()) + .await + .expect("could not write to stdin"); + + // We drop the handle here which signals EOF to the child process. + // This tells the child process that it there is no more data on the pipe. + drop(stdin); + + let op = child.wait_with_output().await?; + + // Results should come back in sorted order + assert_eq!(op.stdout, "bird\ncat\ndog\nfish\nfrog\n".as_bytes()); + + Ok(()) +} +``` + +With some coordination, we can also pipe the output of one command into +another. + +```no_run +use tokio::join; +use tokio::process::Command; +use std::process::Stdio; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let mut echo = Command::new("echo") + .arg("hello world!") + .stdout(Stdio::piped()) + .spawn() + .expect("failed to spawn echo"); + + let tr_stdin: Stdio = echo + .stdout + .take() + .unwrap() + .try_into() + .expect("failed to convert to Stdio"); + + let tr = Command::new("tr") + .arg("a-z") + .arg("A-Z") + .stdin(tr_stdin) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to spawn tr"); + + let (echo_result, tr_output) = join!(echo.wait(), tr.wait_with_output()); + + assert!(echo_result.unwrap().success()); + + let tr_output = tr_output.expect("failed to await tr"); + assert!(tr_output.status.success()); + + assert_eq!(tr_output.stdout, b"HELLO WORLD!\n"); + + Ok(()) +} +``` + +# Caveats + +## Dropping/Cancellation + +Similar to the behavior to the standard library, and unlike the futures +paradigm of dropping-implies-cancellation, a spawned process will, by +default, continue to execute even after the `Child` handle has been dropped. + +The [`Command::kill_on_drop`] method can be used to modify this behavior +and kill the child process if the `Child` wrapper is dropped before it +has exited. + +## Unix Processes + +On Unix platforms processes must be "reaped" by their parent process after +they have exited in order to release all OS resources. A child process which +has exited, but has not yet been reaped by its parent is considered a "zombie" +process. Such processes continue to count against limits imposed by the system, +and having too many zombie processes present can prevent additional processes +from being spawned. + +The tokio runtime will, on a best-effort basis, attempt to reap and clean up +any process which it has spawned. No additional guarantees are made with regard to +how quickly or how often this procedure will take place. + +It is recommended to avoid dropping a [`Child`] process handle before it has been +fully `await`ed if stricter cleanup guarantees are required. + +[`Command`]: crate::process::Command +[`Command::kill_on_drop`]: crate::process::Command::kill_on_drop +[`Child`]: crate::process::Child + +```rust +pub mod process { /* ... */ } +``` + +### Types + +#### Struct `Command` + +This structure mimics the API of [`std::process::Command`] found in the standard library, but +replaces functions that create a process with an asynchronous variant. The main provided +asynchronous functions are [spawn](Command::spawn), [status](Command::status), and +[output](Command::output). + +`Command` uses asynchronous versions of some `std` types (for example [`Child`]). + +[`std::process::Command`]: std::process::Command +[`Child`]: struct@Child + +```rust +pub struct Command { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new>(program: S) -> Command { /* ... */ } + ``` + Constructs a new `Command` for launching the program at + +- ```rust + pub fn as_std(self: &Self) -> &StdCommand { /* ... */ } + ``` + Cheaply convert to a `&std::process::Command` for places where the type from the standard + +- ```rust + pub fn as_std_mut(self: &mut Self) -> &mut StdCommand { /* ... */ } + ``` + Cheaply convert to a `&mut std::process::Command` for places where the type from the + +- ```rust + pub fn into_std(self: Self) -> StdCommand { /* ... */ } + ``` + Cheaply convert into a `std::process::Command`. + +- ```rust + pub fn arg>(self: &mut Self, arg: S) -> &mut Command { /* ... */ } + ``` + Adds an argument to pass to the program. + +- ```rust + pub fn args(self: &mut Self, args: I) -> &mut Command +where + I: IntoIterator, + S: AsRef { /* ... */ } + ``` + Adds multiple arguments to pass to the program. + +- ```rust + pub fn raw_arg>(self: &mut Self, text_to_append_as_is: S) -> &mut Command { /* ... */ } + ``` + Append literal text to the command line without any quoting or escaping. + +- ```rust + pub fn env(self: &mut Self, key: K, val: V) -> &mut Command +where + K: AsRef, + V: AsRef { /* ... */ } + ``` + Inserts or updates an environment variable mapping. + +- ```rust + pub fn envs(self: &mut Self, vars: I) -> &mut Command +where + I: IntoIterator, + K: AsRef, + V: AsRef { /* ... */ } + ``` + Adds or updates multiple environment variable mappings. + +- ```rust + pub fn env_remove>(self: &mut Self, key: K) -> &mut Command { /* ... */ } + ``` + Removes an environment variable mapping. + +- ```rust + pub fn env_clear(self: &mut Self) -> &mut Command { /* ... */ } + ``` + Clears the entire environment map for the child process. + +- ```rust + pub fn current_dir>(self: &mut Self, dir: P) -> &mut Command { /* ... */ } + ``` + Sets the working directory for the child process. + +- ```rust + pub fn stdin>(self: &mut Self, cfg: T) -> &mut Command { /* ... */ } + ``` + Sets configuration for the child process's standard input (stdin) handle. + +- ```rust + pub fn stdout>(self: &mut Self, cfg: T) -> &mut Command { /* ... */ } + ``` + Sets configuration for the child process's standard output (stdout) handle. + +- ```rust + pub fn stderr>(self: &mut Self, cfg: T) -> &mut Command { /* ... */ } + ``` + Sets configuration for the child process's standard error (stderr) handle. + +- ```rust + pub fn kill_on_drop(self: &mut Self, kill_on_drop: bool) -> &mut Command { /* ... */ } + ``` + Controls whether a `kill` operation should be invoked on a spawned child + +- ```rust + pub fn creation_flags(self: &mut Self, flags: u32) -> &mut Command { /* ... */ } + ``` + Sets the [process creation flags][1] to be passed to `CreateProcess`. + +- ```rust + pub fn uid(self: &mut Self, id: u32) -> &mut Command { /* ... */ } + ``` + Sets the child process's user ID. This translates to a + +- ```rust + pub fn gid(self: &mut Self, id: u32) -> &mut Command { /* ... */ } + ``` + Similar to `uid` but sets the group ID of the child process. This has + +- ```rust + pub fn arg0(self: &mut Self, arg: S) -> &mut Command +where + S: AsRef { /* ... */ } + ``` + Sets executable argument. + +- ```rust + pub unsafe fn pre_exec(self: &mut Self, f: F) -> &mut Command +where + F: FnMut() -> io::Result<()> + Send + Sync + ''static { /* ... */ } + ``` + Schedules a closure to be run just before the `exec` function is + +- ```rust + pub fn process_group(self: &mut Self, pgroup: i32) -> &mut Command { /* ... */ } + ``` + Sets the process group ID (PGID) of the child process. Equivalent to a + +- ```rust + pub fn spawn(self: &mut Self) -> io::Result { /* ... */ } + ``` + Executes the command as a child process, returning a handle to it. + +- ```rust + pub fn spawn_with io::Result: FnOnce(&mut StdCommand) -> io::Result>(self: &mut Self, with: impl FnOnce(&mut StdCommand) -> io::Result) -> io::Result { /* ... */ } + ``` + Executes the command as a child process with a custom spawning function, + +- ```rust + pub fn status(self: &mut Self) -> impl Future> { /* ... */ } + ``` + Executes the command as a child process, waiting for it to finish and + +- ```rust + pub fn output(self: &mut Self) -> impl Future> { /* ... */ } + ``` + Executes the command as a child process, waiting for it to finish and + +- ```rust + pub fn get_kill_on_drop(self: &Self) -> bool { /* ... */ } + ``` + Returns the boolean value that was previously set by [`Command::kill_on_drop`]. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(std: StdCommand) -> Command { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Child` + +Representation of a child process spawned onto an event loop. + +# Caveats +Similar to the behavior to the standard library, and unlike the futures +paradigm of dropping-implies-cancellation, a spawned process will, by +default, continue to execute even after the `Child` handle has been dropped. + +The `Command::kill_on_drop` method can be used to modify this behavior +and kill the child process if the `Child` wrapper is dropped before it +has exited. + +```rust +pub struct Child { + pub stdin: Option, + pub stdout: Option, + pub stderr: Option, + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| `stdin` | `Option` | The handle for writing to the child's standard input (stdin), if it has
been captured. To avoid partially moving the `child` and thus blocking
yourself from calling functions on `child` while using `stdin`, you might
find it helpful to do:

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stdin = child.stdin.take().unwrap();
``` | +| `stdout` | `Option` | The handle for reading from the child's standard output (stdout), if it
has been captured. You might find it helpful to do

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stdout = child.stdout.take().unwrap();
```

to avoid partially moving the `child` and thus blocking yourself from calling
functions on `child` while using `stdout`. | +| `stderr` | `Option` | The handle for reading from the child's standard error (stderr), if it
has been captured. You might find it helpful to do

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stderr = child.stderr.take().unwrap();
```

to avoid partially moving the `child` and thus blocking yourself from calling
functions on `child` while using `stderr`. | +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn id(self: &Self) -> Option { /* ... */ } + ``` + Returns the OS-assigned process identifier associated with this child + +- ```rust + pub fn raw_handle(self: &Self) -> Option { /* ... */ } + ``` + Extracts the raw handle of the process associated with this child while + +- ```rust + pub fn start_kill(self: &mut Self) -> io::Result<()> { /* ... */ } + ``` + Attempts to force the child to exit, but does not wait for the request + +- ```rust + pub async fn kill(self: &mut Self) -> io::Result<()> { /* ... */ } + ``` + Forces the child to exit. + +- ```rust + pub async fn wait(self: &mut Self) -> io::Result { /* ... */ } + ``` + Waits for the child to exit completely, returning the status that it + +- ```rust + pub fn try_wait(self: &mut Self) -> io::Result> { /* ... */ } + ``` + Attempts to collect the exit status of the child if it has already + +- ```rust + pub async fn wait_with_output(self: Self) -> io::Result { /* ... */ } + ``` + Returns a future that will resolve to an `Output`, containing the exit + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `ChildStdin` + +The standard input stream for spawned children. + +This type implements the `AsyncWrite` trait to pass data to the stdin +handle of a child process asynchronously. + +```rust +pub struct ChildStdin { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_owned_fd(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedFd`]. + +- ```rust + pub fn into_owned_handle(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedHandle`]. + +- ```rust + pub fn from_std(inner: std::process::ChildStdin) -> io::Result { /* ... */ } + ``` + Creates an asynchronous `ChildStdin` from a synchronous one. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsFd** + - ```rust + fn as_fd(self: &Self) -> BorrowedFd<''_> { /* ... */ } + ``` + +- **AsHandle** + - ```rust + fn as_handle(self: &Self) -> BorrowedHandle<''_> { /* ... */ } + ``` + +- **AsRawFd** + - ```rust + fn as_raw_fd(self: &Self) -> RawFd { /* ... */ } + ``` + +- **AsRawHandle** + - ```rust + fn as_raw_handle(self: &Self) -> RawHandle { /* ... */ } + ``` + +- **AsyncWrite** + - ```rust + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &[u8]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + + - ```rust + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<''_>, bufs: &[io::IoSlice<''_>]) -> Poll> { /* ... */ } + ``` + + - ```rust + fn is_write_vectored(self: &Self) -> bool { /* ... */ } + ``` + +- **AsyncWriteExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + + - ```rust + fn try_into(self: Self) -> Result::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `ChildStdout` + +The standard output stream for spawned children. + +This type implements the `AsyncRead` trait to read data from the stdout +handle of a child process asynchronously. + +```rust +pub struct ChildStdout { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_owned_fd(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedFd`]. + +- ```rust + pub fn into_owned_handle(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedHandle`]. + +- ```rust + pub fn from_std(inner: std::process::ChildStdout) -> io::Result { /* ... */ } + ``` + Creates an asynchronous `ChildStdout` from a synchronous one. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsFd** + - ```rust + fn as_fd(self: &Self) -> BorrowedFd<''_> { /* ... */ } + ``` + +- **AsHandle** + - ```rust + fn as_handle(self: &Self) -> BorrowedHandle<''_> { /* ... */ } + ``` + +- **AsRawFd** + - ```rust + fn as_raw_fd(self: &Self) -> RawFd { /* ... */ } + ``` + +- **AsRawHandle** + - ```rust + fn as_raw_handle(self: &Self) -> RawHandle { /* ... */ } + ``` + +- **AsyncRead** + - ```rust + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &mut ReadBuf<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncReadExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + + - ```rust + fn try_into(self: Self) -> Result::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `ChildStderr` + +The standard error stream for spawned children. + +This type implements the `AsyncRead` trait to read data from the stderr +handle of a child process asynchronously. + +```rust +pub struct ChildStderr { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_owned_fd(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedFd`]. + +- ```rust + pub fn into_owned_handle(self: Self) -> io::Result { /* ... */ } + ``` + Convert into [`OwnedHandle`]. + +- ```rust + pub fn from_std(inner: std::process::ChildStderr) -> io::Result { /* ... */ } + ``` + Creates an asynchronous `ChildStderr` from a synchronous one. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **AsFd** + - ```rust + fn as_fd(self: &Self) -> BorrowedFd<''_> { /* ... */ } + ``` + +- **AsHandle** + - ```rust + fn as_handle(self: &Self) -> BorrowedHandle<''_> { /* ... */ } + ``` + +- **AsRawFd** + - ```rust + fn as_raw_fd(self: &Self) -> RawFd { /* ... */ } + ``` + +- **AsRawHandle** + - ```rust + fn as_raw_handle(self: &Self) -> RawHandle { /* ... */ } + ``` + +- **AsyncRead** + - ```rust + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<''_>, buf: &mut ReadBuf<''_>) -> Poll> { /* ... */ } + ``` + +- **AsyncReadExt** +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + + - ```rust + fn try_into(self: Self) -> Result::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +## Module `runtime` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +The Tokio runtime. + +Unlike other Rust programs, asynchronous applications require runtime +support. In particular, the following runtime services are necessary: + +* An **I/O event loop**, called the driver, which drives I/O resources and + dispatches I/O events to tasks that depend on them. +* A **scheduler** to execute [tasks] that use these I/O resources. +* A **timer** for scheduling work to run after a set period of time. + +Tokio's [`Runtime`] bundles all of these services as a single type, allowing +them to be started, shut down, and configured together. However, often it is +not required to configure a [`Runtime`] manually, and a user may just use the +[`tokio::main`] attribute macro, which creates a [`Runtime`] under the hood. + +# Choose your runtime + +Here is the rules of thumb to choose the right runtime for your application. + +```plaintext + +------------------------------------------------------+ + | Do you want work-stealing or multi-thread scheduler? | + +------------------------------------------------------+ + | Yes | No + | | + | | + v | + +------------------------+ | + | Multi-threaded Runtime | | + +------------------------+ | + | + V + +--------------------------------+ + | Do you execute `!Send` Future? | + +--------------------------------+ + | Yes | No + | | + V | + +--------------------------+ | + | Local Runtime (unstable) | | + +--------------------------+ | + | + v + +------------------------+ + | Current-thread Runtime | + +------------------------+ +``` + +The above decision tree is not exhaustive. there are other factors that +may influence your decision. + +## Bridging with sync code + +See for details. + +## NUMA awareness + +The tokio runtime is not NUMA (Non-Uniform Memory Access) aware. +You may want to start multiple runtimes instead of a single runtime +for better performance on NUMA systems. + +# Usage + +When no fine tuning is required, the [`tokio::main`] attribute macro can be +used. + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::net::TcpListener; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let listener = TcpListener::bind("127.0.0.1:8080").await?; + + loop { + let (mut socket, _) = listener.accept().await?; + + tokio::spawn(async move { + let mut buf = [0; 1024]; + + // In a loop, read data from the socket and write the data back. + loop { + let n = match socket.read(&mut buf).await { + // socket closed + Ok(0) => return, + Ok(n) => n, + Err(e) => { + println!("failed to read from socket; err = {:?}", e); + return; + } + }; + + // Write the data back + if let Err(e) = socket.write_all(&buf[0..n]).await { + println!("failed to write to socket; err = {:?}", e); + return; + } + } + }); + } +} +# } +``` + +From within the context of the runtime, additional tasks are spawned using +the [`tokio::spawn`] function. Futures spawned using this function will be +executed on the same thread pool used by the [`Runtime`]. + +A [`Runtime`] instance can also be used directly. + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::net::TcpListener; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::runtime::Runtime; + +fn main() -> Result<(), Box> { + // Create the runtime + let rt = Runtime::new()?; + + // Spawn the root task + rt.block_on(async { + let listener = TcpListener::bind("127.0.0.1:8080").await?; + + loop { + let (mut socket, _) = listener.accept().await?; + + tokio::spawn(async move { + let mut buf = [0; 1024]; + + // In a loop, read data from the socket and write the data back. + loop { + let n = match socket.read(&mut buf).await { + // socket closed + Ok(0) => return, + Ok(n) => n, + Err(e) => { + println!("failed to read from socket; err = {:?}", e); + return; + } + }; + + // Write the data back + if let Err(e) = socket.write_all(&buf[0..n]).await { + println!("failed to write to socket; err = {:?}", e); + return; + } + } + }); + } + }) +} +# } +``` + +## Runtime Configurations + +Tokio provides multiple task scheduling strategies, suitable for different +applications. The [runtime builder] or `#[tokio::main]` attribute may be +used to select which scheduler to use. + +#### Multi-Thread Scheduler + +The multi-thread scheduler executes futures on a _thread pool_, using a +work-stealing strategy. By default, it will start a worker thread for each +CPU core available on the system. This tends to be the ideal configuration +for most applications. The multi-thread scheduler requires the `rt-multi-thread` +feature flag, and is selected by default: +``` +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::runtime; + +# fn main() -> Result<(), Box> { +let threaded_rt = runtime::Runtime::new()?; +# Ok(()) } +# } +``` + +Most applications should use the multi-thread scheduler, except in some +niche use-cases, such as when running only a single thread is required. + +#### Current-Thread Scheduler + +The current-thread scheduler provides a _single-threaded_ future executor. +All tasks will be created and executed on the current thread. This requires +the `rt` feature flag. +``` +use tokio::runtime; + +# fn main() -> Result<(), Box> { +let rt = runtime::Builder::new_current_thread() + .build()?; +# Ok(()) } +``` + +#### Resource drivers + +When configuring a runtime by hand, no resource drivers are enabled by +default. In this case, attempting to use networking types or time types will +fail. In order to enable these types, the resource drivers must be enabled. +This is done with [`Builder::enable_io`] and [`Builder::enable_time`]. As a +shorthand, [`Builder::enable_all`] enables both resource drivers. + +## Lifetime of spawned threads + +The runtime may spawn threads depending on its configuration and usage. The +multi-thread scheduler spawns threads to schedule tasks and for `spawn_blocking` +calls. + +While the `Runtime` is active, threads may shut down after periods of being +idle. Once `Runtime` is dropped, all runtime threads have usually been +terminated, but in the presence of unstoppable spawned work are not +guaranteed to have been terminated. See the +[struct level documentation](Runtime#shutdown) for more details. + +[tasks]: crate::task +[`Runtime`]: Runtime +[`tokio::spawn`]: crate::spawn +[`tokio::main`]: ../attr.main.html +[runtime builder]: crate::runtime::Builder +[`Runtime::new`]: crate::runtime::Runtime::new +[`Builder::enable_io`]: crate::runtime::Builder::enable_io +[`Builder::enable_time`]: crate::runtime::Builder::enable_time +[`Builder::enable_all`]: crate::runtime::Builder::enable_all + +# Detailed runtime behavior + +This section gives more details into how the Tokio runtime will schedule +tasks for execution. + +At its most basic level, a runtime has a collection of tasks that need to be +scheduled. It will repeatedly remove a task from that collection and +schedule it (by calling [`poll`]). When the collection is empty, the thread +will go to sleep until a task is added to the collection. + +However, the above is not sufficient to guarantee a well-behaved runtime. +For example, the runtime might have a single task that is always ready to be +scheduled, and schedule that task every time. This is a problem because it +starves other tasks by not scheduling them. To solve this, Tokio provides +the following fairness guarantee: + +> If the total number of tasks does not grow without bound, and no task is +> [blocking the thread], then it is guaranteed that tasks are scheduled +> fairly. + +Or, more formally: + +> Under the following two assumptions: +> +> * There is some number `MAX_TASKS` such that the total number of tasks on +> the runtime at any specific point in time never exceeds `MAX_TASKS`. +> * There is some number `MAX_SCHEDULE` such that calling [`poll`] on any +> task spawned on the runtime returns within `MAX_SCHEDULE` time units. +> +> Then, there is some number `MAX_DELAY` such that when a task is woken, it +> will be scheduled by the runtime within `MAX_DELAY` time units. + +(Here, `MAX_TASKS` and `MAX_SCHEDULE` can be any number and the user of +the runtime may choose them. The `MAX_DELAY` number is controlled by the +runtime, and depends on the value of `MAX_TASKS` and `MAX_SCHEDULE`.) + +Other than the above fairness guarantee, there is no guarantee about the +order in which tasks are scheduled. There is also no guarantee that the +runtime is equally fair to all tasks. For example, if the runtime has two +tasks A and B that are both ready, then the runtime may schedule A five +times before it schedules B. This is the case even if A yields using +[`yield_now`]. All that is guaranteed is that it will schedule B eventually. + +Normally, tasks are scheduled only if they have been woken by calling +[`wake`] on their waker. However, this is not guaranteed, and Tokio may +schedule tasks that have not been woken under some circumstances. This is +called a spurious wakeup. + +## IO and timers + +Beyond just scheduling tasks, the runtime must also manage IO resources and +timers. It does this by periodically checking whether there are any IO +resources or timers that are ready, and waking the relevant task so that +it will be scheduled. + +These checks are performed periodically between scheduling tasks. Under the +same assumptions as the previous fairness guarantee, Tokio guarantees that +it will wake tasks with an IO or timer event within some maximum number of +time units. + +## Current thread runtime (behavior at the time of writing) + +This section describes how the [current thread runtime] behaves today. This +behavior may change in future versions of Tokio. + +The current thread runtime maintains two FIFO queues of tasks that are ready +to be scheduled: the global queue and the local queue. The runtime will prefer +to choose the next task to schedule from the local queue, and will only pick a +task from the global queue if the local queue is empty, or if it has picked +a task from the local queue 31 times in a row. The number 31 can be +changed using the [`global_queue_interval`] setting. + +The runtime will check for new IO or timer events whenever there are no +tasks ready to be scheduled, or when it has scheduled 61 tasks in a row. The +number 61 may be changed using the [`event_interval`] setting. + +When a task is woken from within a task running on the runtime, then the +woken task is added directly to the local queue. Otherwise, the task is +added to the global queue. The current thread runtime does not use [the lifo +slot optimization]. + +## Multi threaded runtime (behavior at the time of writing) + +This section describes how the [multi thread runtime] behaves today. This +behavior may change in future versions of Tokio. + +A multi thread runtime has a fixed number of worker threads, which are all +created on startup. The multi thread runtime maintains one global queue, and +a local queue for each worker thread. The local queue of a worker thread can +fit at most 256 tasks. If more than 256 tasks are added to the local queue, +then half of them are moved to the global queue to make space. + +The runtime will prefer to choose the next task to schedule from the local +queue, and will only pick a task from the global queue if the local queue is +empty, or if it has picked a task from the local queue +[`global_queue_interval`] times in a row. If the value of +[`global_queue_interval`] is not explicitly set using the runtime builder, +then the runtime will dynamically compute it using a heuristic that targets +10ms intervals between each check of the global queue (based on the +[`worker_mean_poll_time`] metric). + +If both the local queue and global queue is empty, then the worker thread +will attempt to steal tasks from the local queue of another worker thread. +Stealing is done by moving half of the tasks in one local queue to another +local queue. + +The runtime will check for new IO or timer events whenever there are no +tasks ready to be scheduled, or when it has scheduled 61 tasks in a row. The +number 61 may be changed using the [`event_interval`] setting. + +The multi thread runtime uses [the lifo slot optimization]: Whenever a task +wakes up another task, the other task is added to the worker thread's lifo +slot instead of being added to a queue. If there was already a task in the +lifo slot when this happened, then the lifo slot is replaced, and the task +that used to be in the lifo slot is placed in the thread's local queue. +When the runtime finishes scheduling a task, it will schedule the task in +the lifo slot immediately, if any. When the lifo slot is used, the [coop +budget] is not reset. Furthermore, if a worker thread uses the lifo slot +three times in a row, it is temporarily disabled until the worker thread has +scheduled a task that didn't come from the lifo slot. The lifo slot can be +disabled using the [`disable_lifo_slot`] setting. The lifo slot is separate +from the local queue, so other worker threads cannot steal the task in the +lifo slot. + +When a task is woken from a thread that is not a worker thread, then the +task is placed in the global queue. + +[`poll`]: std::future::Future::poll +[`wake`]: std::task::Waker::wake +[`yield_now`]: crate::task::yield_now +[blocking the thread]: https://ryhl.io/blog/async-what-is-blocking/ +[current thread runtime]: crate::runtime::Builder::new_current_thread +[multi thread runtime]: crate::runtime::Builder::new_multi_thread +[`global_queue_interval`]: crate::runtime::Builder::global_queue_interval +[`event_interval`]: crate::runtime::Builder::event_interval +[`disable_lifo_slot`]: crate::runtime::Builder::disable_lifo_slot +[the lifo slot optimization]: crate::runtime::Builder::disable_lifo_slot +[coop budget]: crate::task::coop#cooperative-scheduling +[`worker_mean_poll_time`]: crate::runtime::RuntimeMetrics::worker_mean_poll_time + +```rust +pub mod runtime { /* ... */ } +``` + +### Modules + +## Module `dump` + +**Attributes:** + +- `Other("#[(all(tokio_unstable, feature = \"taskdump\", feature = \"rt\", target_os =\n\"linux\",\nany(target_arch = \"aarch64\", target_arch = \"x86\", target_arch = \"x86_64\")))]")` + +Snapshots of runtime state. + +See [`Handle::dump`][crate::runtime::Handle::dump]. + +```rust +pub mod dump { /* ... */ } +``` + +### Types + +#### Struct `Dump` + +A snapshot of a runtime's state. + +See [`Handle::dump`][crate::runtime::Handle::dump]. + +```rust +pub struct Dump { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn tasks(self: &Self) -> &Tasks { /* ... */ } + ``` + Tasks in this snapshot. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Tasks` + +Snapshots of tasks. + +See [`Handle::dump`][crate::runtime::Handle::dump]. + +```rust +pub struct Tasks { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn iter(self: &Self) -> impl Iterator { /* ... */ } + ``` + Iterate over tasks. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Task` + +A snapshot of a task. + +See [`Handle::dump`][crate::runtime::Handle::dump]. + +```rust +pub struct Task { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn id(self: &Self) -> Id { /* ... */ } + ``` + Returns a [task ID] that uniquely identifies this task relative to other + +- ```rust + pub fn trace(self: &Self) -> &Trace { /* ... */ } + ``` + A trace of this task's state. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `BacktraceSymbol` + +A backtrace symbol. + +This struct provides accessors for backtrace symbols, similar to [`backtrace::BacktraceSymbol`]. + +```rust +pub struct BacktraceSymbol { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn name_raw(self: &Self) -> Option<&[u8]> { /* ... */ } + ``` + Return the raw name of the symbol. + +- ```rust + pub fn name_demangled(self: &Self) -> Option<&str> { /* ... */ } + ``` + Return the demangled name of the symbol. + +- ```rust + pub fn addr(self: &Self) -> Option<*mut std::ffi::c_void> { /* ... */ } + ``` + Returns the starting address of this symbol. + +- ```rust + pub fn filename(self: &Self) -> Option<&Path> { /* ... */ } + ``` + Returns the file name where this function was defined. If debuginfo + +- ```rust + pub fn lineno(self: &Self) -> Option { /* ... */ } + ``` + Returns the line number for where this symbol is currently executing. + +- ```rust + pub fn colno(self: &Self) -> Option { /* ... */ } + ``` + Returns the column number for where this symbol is currently executing. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> BacktraceSymbol { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `BacktraceFrame` + +A backtrace frame. + +This struct represents one stack frame in a captured backtrace, similar to [`backtrace::BacktraceFrame`]. + +```rust +pub struct BacktraceFrame { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn ip(self: &Self) -> *mut std::ffi::c_void { /* ... */ } + ``` + Return the instruction pointer of this frame. + +- ```rust + pub fn symbol_address(self: &Self) -> *mut std::ffi::c_void { /* ... */ } + ``` + Returns the starting symbol address of the frame of this function. + +- ```rust + pub fn symbols(self: &Self) -> impl Iterator { /* ... */ } + ``` + Return an iterator over the symbols of this backtrace frame. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> BacktraceFrame { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Backtrace` + +A captured backtrace. + +This struct provides access to each backtrace frame, similar to [`backtrace::Backtrace`]. + +```rust +pub struct Backtrace { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn frames(self: &Self) -> impl Iterator { /* ... */ } + ``` + Return the frames in this backtrace, innermost (in a task dump, + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Backtrace { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Trace` + +An execution trace of a task's last poll. + +
+ +Resolving a backtrace, either via the [`Display`][std::fmt::Display] impl or via +[`resolve_backtraces`][Trace::resolve_backtraces], parses debuginfo, which is +possibly a CPU-expensive operation that can take a platform-specific but +long time to run - often over 100 milliseconds, especially if the current +process's binary is big. In some cases, the platform might internally cache some of the +debuginfo, so successive calls to `resolve_backtraces` might be faster than +the first call, but all guarantees are platform-dependent. + +To avoid blocking the runtime, it is recommended +that you resolve backtraces inside of a [`spawn_blocking()`][crate::task::spawn_blocking] +and to have some concurrency-limiting mechanism to avoid unexpected performance impact. +
+ +See [`Handle::dump`][crate::runtime::Handle::dump]. + +```rust +pub struct Trace { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn resolve_backtraces(self: &Self) -> Vec { /* ... */ } + ``` + Resolve and return a list of backtraces that are involved in polls in this trace. + +- ```rust + pub fn capture(f: F) -> (R, Trace) +where + F: FnOnce() -> R { /* ... */ } + ``` + Runs the function `f` in tracing mode, and returns its result along with the resulting [`Trace`]. + +- ```rust + pub fn root(f: F) -> Root +where + F: Future { /* ... */ } + ``` + Create a root for stack traces captured using [`Trace::capture`]. Stack frames above + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Re-exports + +#### Re-export `Root` + +```rust +pub use crate::runtime::task::trace::Root; +``` + +### Re-exports + +#### Re-export `Builder` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use self::builder::Builder; +``` + +#### Re-export `Id` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` +- `Other("#[(not(tokio_unstable), allow(unreachable_pub))]")` + +```rust +pub use id::Id; +``` + +#### Re-export `UnhandledPanic` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use self::builder::UnhandledPanic; +``` + +#### Re-export `RngSeed` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use crate::util::rand::RngSeed; +``` + +#### Re-export `LocalRuntime` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use local_runtime::LocalRuntime; +``` + +#### Re-export `LocalOptions` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use local_runtime::LocalOptions; +``` + +#### Re-export `Dump` + +**Attributes:** + +- `Other("#[(all(tokio_unstable, feature = \"taskdump\", feature = \"rt\", target_os =\n\"linux\",\nany(target_arch = \"aarch64\", target_arch = \"x86\", target_arch = \"x86_64\")))]")` + +```rust +pub use dump::Dump; +``` + +#### Re-export `TaskMeta` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use task_hooks::TaskMeta; +``` + +#### Re-export `EnterGuard` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use handle::EnterGuard; +``` + +#### Re-export `Handle` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use handle::Handle; +``` + +#### Re-export `TryCurrentError` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use handle::TryCurrentError; +``` + +#### Re-export `Runtime` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use runtime::Runtime; +``` + +#### Re-export `RuntimeFlavor` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use runtime::RuntimeFlavor; +``` + +#### Re-export `RuntimeMetrics` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use metrics::RuntimeMetrics; +``` + +#### Re-export `HistogramScale` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use metrics::HistogramScale; +``` + +#### Re-export `HistogramConfiguration` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use metrics::HistogramConfiguration; +``` + +#### Re-export `LogHistogram` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use metrics::LogHistogram; +``` + +#### Re-export `LogHistogramBuilder` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use metrics::LogHistogramBuilder; +``` + +#### Re-export `InvalidHistogramConfiguration` + +**Attributes:** + +- `Other("#[(tokio_unstable)]")` +- `Other("#[(docsrs, doc(cfg(tokio_unstable)))]")` +- `Other("#[doc(cfg(tokio_unstable))]")` + +```rust +pub use metrics::InvalidHistogramConfiguration; +``` + +## Module `signal` + +**Attributes:** + +- `Other("#[(feature = \"signal\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"signal\")))]")` +- `Other("#[doc(cfg(feature = \"signal\"))]")` +- `Other("#[(not(loom))]")` +- `Other("#[(not(target_os = \"wasi\"))]")` + +Asynchronous signal handling for Tokio. + +Note that signal handling is in general a very tricky topic and should be +used with great care. This crate attempts to implement 'best practice' for +signal handling, but it should be evaluated for your own applications' needs +to see if it's suitable. + +There are some fundamental limitations of this crate documented on the OS +specific structures, as well. + +# Examples + +Print on "ctrl-c" notification. + +```rust,no_run +use tokio::signal; + +#[tokio::main] +async fn main() -> Result<(), Box> { + signal::ctrl_c().await?; + println!("ctrl-c received!"); + Ok(()) +} +``` + +Wait for `SIGHUP` on Unix + +```rust,no_run +# #[cfg(unix)] { +use tokio::signal::unix::{signal, SignalKind}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // An infinite stream of hangup signals. + let mut stream = signal(SignalKind::hangup())?; + + // Print whenever a HUP signal is received + loop { + stream.recv().await; + println!("got signal HUP"); + } +} +# } +``` + +```rust +pub mod signal { /* ... */ } +``` + +### Modules + +## Module `unix` + +**Attributes:** + +- `Other("#[(unix)]")` +- `Other("#[(docsrs, doc(cfg(all(unix, feature = \"signal\"))))]")` +- `Other("#[doc(cfg(all(unix, feature = \"signal\")))]")` + +Unix-specific types for signal handling. + +This module is only defined on Unix platforms and contains the primary +`Signal` type for receiving notifications of signals. + +```rust +pub mod unix { /* ... */ } +``` + +### Types + +#### Struct `SignalKind` + +Represents the specific kind of signal to listen for. + +```rust +pub struct SignalKind(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub const fn from_raw(signum: std::os::raw::c_int) -> Self { /* ... */ } + ``` + Allows for listening to any valid OS signal. + +- ```rust + pub const fn as_raw_value(self: &Self) -> std::os::raw::c_int { /* ... */ } + ``` + Get the signal's numeric value. + +- ```rust + pub const fn alarm() -> Self { /* ... */ } + ``` + Represents the `SIGALRM` signal. + +- ```rust + pub const fn child() -> Self { /* ... */ } + ``` + Represents the `SIGCHLD` signal. + +- ```rust + pub const fn hangup() -> Self { /* ... */ } + ``` + Represents the `SIGHUP` signal. + +- ```rust + pub const fn interrupt() -> Self { /* ... */ } + ``` + Represents the `SIGINT` signal. + +- ```rust + pub const fn io() -> Self { /* ... */ } + ``` + Represents the `SIGIO` signal. + +- ```rust + pub const fn pipe() -> Self { /* ... */ } + ``` + Represents the `SIGPIPE` signal. + +- ```rust + pub const fn quit() -> Self { /* ... */ } + ``` + Represents the `SIGQUIT` signal. + +- ```rust + pub const fn terminate() -> Self { /* ... */ } + ``` + Represents the `SIGTERM` signal. + +- ```rust + pub const fn user_defined1() -> Self { /* ... */ } + ``` + Represents the `SIGUSR1` signal. + +- ```rust + pub const fn user_defined2() -> Self { /* ... */ } + ``` + Represents the `SIGUSR2` signal. + +- ```rust + pub const fn window_change() -> Self { /* ... */ } + ``` + Represents the `SIGWINCH` signal. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SignalKind { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(signum: std::os::raw::c_int) -> Self { /* ... */ } + ``` + + - ```rust + fn from(kind: SignalKind) -> Self { /* ... */ } + ``` + +- **Hash** + - ```rust + fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H) { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &SignalKind) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Signal` + +**Attributes:** + +- `MustUse { reason: Some("streams do nothing unless polled") }` + +An listener for receiving a particular type of OS signal. + +The listener can be turned into a `Stream` using [`SignalStream`]. + +[`SignalStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.SignalStream.html + +In general signal handling on Unix is a pretty tricky topic, and this +structure is no exception! There are some important limitations to keep in +mind when using `Signal` streams: + +* Signals handling in Unix already necessitates coalescing signals + together sometimes. This `Signal` stream is also no exception here in + that it will also coalesce signals. That is, even if the signal handler + for this process runs multiple times, the `Signal` stream may only return + one signal notification. Specifically, before `poll` is called, all + signal notifications are coalesced into one item returned from `poll`. + Once `poll` has been called, however, a further signal is guaranteed to + be yielded as an item. + + Put another way, any element pulled off the returned listener corresponds to + *at least one* signal, but possibly more. + +* Signal handling in general is relatively inefficient. Although some + improvements are possible in this crate, it's recommended to not plan on + having millions of signal channels open. + +If you've got any questions about this feel free to open an issue on the +repo! New approaches to alleviate some of these limitations are always +appreciated! + +# Caveats + +The first time that a `Signal` instance is registered for a particular +signal kind, an OS signal-handler is installed which replaces the default +platform behavior when that signal is received, **for the duration of the +entire process**. + +For example, Unix systems will terminate a process by default when it +receives `SIGINT`. But, when a `Signal` instance is created to listen for +this signal, the next `SIGINT` that arrives will be translated to a stream +event, and the process will continue to execute. **Even if this `Signal` +instance is dropped, subsequent `SIGINT` deliveries will end up captured by +Tokio, and the default platform behavior will NOT be reset**. + +Thus, applications should take care to ensure the expected signal behavior +occurs as expected after listening for specific signals. + +# Examples + +Wait for `SIGHUP` + +```rust,no_run +use tokio::signal::unix::{signal, SignalKind}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // An infinite stream of hangup signals. + let mut sig = signal(SignalKind::hangup())?; + + // Print whenever a HUP signal is received + loop { + sig.recv().await; + println!("got signal HUP"); + } +} +``` + +```rust +pub struct Signal { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `signal` + +**Attributes:** + +- `Other("#[attr = TrackCaller]")` + +Creates a new listener which will receive notifications when the current +process receives the specified signal `kind`. + +This function will create a new stream which binds to the default reactor. +The `Signal` stream is an infinite stream which will receive +notifications whenever a signal is received. More documentation can be +found on `Signal` itself, but to reiterate: + +* Signals may be coalesced beyond what the kernel already does. +* Once a signal handler is registered with the process the underlying + libc signal handler is never unregistered. + +A `Signal` stream can be created for a particular signal number +multiple times. When a signal is received then all the associated +channels will receive the signal notification. + +# Errors + +* If the lower-level C functions fail for some reason. +* If the previous initialization of this specific signal failed. +* If the signal is one of + [`signal_hook::FORBIDDEN`](fn@signal_hook_registry::register#panics) + +# Panics + +This function panics if there is no current reactor set, or if the `rt` +feature flag is not enabled. + +```rust +pub fn signal(kind: SignalKind) -> io::Result { /* ... */ } +``` + +## Module `windows` + +**Attributes:** + +- `Other("#[(any(windows, docsrs))]")` +- `Other("#[(docsrs, doc(cfg(all(windows, feature = \"signal\"))))]")` +- `Other("#[doc(cfg(all(windows, feature = \"signal\")))]")` + +Windows-specific types for signal handling. + +This module is only defined on Windows and allows receiving "ctrl-c", +"ctrl-break", "ctrl-logoff", "ctrl-shutdown", and "ctrl-close" +notifications. These events are listened for via the `SetConsoleCtrlHandler` +function which receives the corresponding `windows_sys` event type. + +```rust +pub mod windows { /* ... */ } +``` + +### Types + +#### Struct `CtrlC` + +**Attributes:** + +- `MustUse { reason: Some("listeners do nothing unless polled") }` + +Represents a listener which receives "ctrl-c" notifications sent to the process +via `SetConsoleCtrlHandler`. + +This event can be turned into a `Stream` using [`CtrlCStream`]. + +[`CtrlCStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.CtrlCStream.html + +A notification to this process notifies *all* receivers for +this event. Moreover, the notifications **are coalesced** if they aren't processed +quickly enough. This means that if two notifications are received back-to-back, +then the listener may only receive one item about the two notifications. + +```rust +pub struct CtrlC { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `CtrlBreak` + +**Attributes:** + +- `MustUse { reason: Some("listeners do nothing unless polled") }` + +Represents a listener which receives "ctrl-break" notifications sent to the process +via `SetConsoleCtrlHandler`. + +This listener can be turned into a `Stream` using [`CtrlBreakStream`]. + +[`CtrlBreakStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.CtrlBreakStream.html + +A notification to this process notifies *all* receivers for +this event. Moreover, the notifications **are coalesced** if they aren't processed +quickly enough. This means that if two notifications are received back-to-back, +then the listener may only receive one item about the two notifications. + +```rust +pub struct CtrlBreak { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `CtrlClose` + +**Attributes:** + +- `MustUse { reason: Some("listeners do nothing unless polled") }` + +Represents a listener which receives "ctrl-close" notifications sent to the process +via `SetConsoleCtrlHandler`. + +A notification to this process notifies *all* listeners listening for +this event. Moreover, the notifications **are coalesced** if they aren't processed +quickly enough. This means that if two notifications are received back-to-back, +then the listener may only receive one item about the two notifications. + +```rust +pub struct CtrlClose { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `CtrlShutdown` + +**Attributes:** + +- `MustUse { reason: Some("listeners do nothing unless polled") }` + +Represents a listener which receives "ctrl-shutdown" notifications sent to the process +via `SetConsoleCtrlHandler`. + +A notification to this process notifies *all* listeners listening for +this event. Moreover, the notifications **are coalesced** if they aren't processed +quickly enough. This means that if two notifications are received back-to-back, +then the listener may only receive one item about the two notifications. + +```rust +pub struct CtrlShutdown { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `CtrlLogoff` + +**Attributes:** + +- `MustUse { reason: Some("listeners do nothing unless polled") }` + +Represents a listener which receives "ctrl-logoff" notifications sent to the process +via `SetConsoleCtrlHandler`. + +A notification to this process notifies *all* listeners listening for +this event. Moreover, the notifications **are coalesced** if they aren't processed +quickly enough. This means that if two notifications are received back-to-back, +then the listener may only receive one item about the two notifications. + +```rust +pub struct CtrlLogoff { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub async fn recv(self: &mut Self) -> Option<()> { /* ... */ } + ``` + Receives the next signal notification event. + +- ```rust + pub fn poll_recv(self: &mut Self, cx: &mut Context<''_>) -> Poll> { /* ... */ } + ``` + Polls to receive the next signal notification event, outside of an + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `ctrl_c` + +Creates a new listener which receives "ctrl-c" notifications sent to the +process. + +# Examples + +```rust,no_run +use tokio::signal::windows::ctrl_c; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // A listener of CTRL-C events. + let mut signal = ctrl_c()?; + + // Print whenever a CTRL-C event is received. + for countdown in (0..3).rev() { + signal.recv().await; + println!("got CTRL-C. {} more to exit", countdown); + } + + Ok(()) +} +``` + +```rust +pub fn ctrl_c() -> io::Result { /* ... */ } +``` + +#### Function `ctrl_break` + +Creates a new listener which receives "ctrl-break" notifications sent to the +process. + +# Examples + +```rust,no_run +use tokio::signal::windows::ctrl_break; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // A listener of CTRL-BREAK events. + let mut signal = ctrl_break()?; + + // Print whenever a CTRL-BREAK event is received. + loop { + signal.recv().await; + println!("got signal CTRL-BREAK"); + } +} +``` + +```rust +pub fn ctrl_break() -> io::Result { /* ... */ } +``` + +#### Function `ctrl_close` + +Creates a new listener which receives "ctrl-close" notifications sent to the +process. + +# Examples + +```rust,no_run +use tokio::signal::windows::ctrl_close; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // A listener of CTRL-CLOSE events. + let mut signal = ctrl_close()?; + + // Print whenever a CTRL-CLOSE event is received. + for countdown in (0..3).rev() { + signal.recv().await; + println!("got CTRL-CLOSE. {} more to exit", countdown); + } + + Ok(()) +} +``` + +```rust +pub fn ctrl_close() -> io::Result { /* ... */ } +``` + +#### Function `ctrl_shutdown` + +Creates a new listener which receives "ctrl-shutdown" notifications sent to the +process. + +# Examples + +```rust,no_run +use tokio::signal::windows::ctrl_shutdown; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // A listener of CTRL-SHUTDOWN events. + let mut signal = ctrl_shutdown()?; + + signal.recv().await; + println!("got CTRL-SHUTDOWN. Cleaning up before exiting"); + + Ok(()) +} +``` + +```rust +pub fn ctrl_shutdown() -> io::Result { /* ... */ } +``` + +#### Function `ctrl_logoff` + +Creates a new listener which receives "ctrl-logoff" notifications sent to the +process. + +# Examples + +```rust,no_run +use tokio::signal::windows::ctrl_logoff; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // A listener of CTRL-LOGOFF events. + let mut signal = ctrl_logoff()?; + + signal.recv().await; + println!("got CTRL-LOGOFF. Cleaning up before exiting"); + + Ok(()) +} +``` + +```rust +pub fn ctrl_logoff() -> io::Result { /* ... */ } +``` + +### Re-exports + +#### Re-export `ctrl_c` + +**Attributes:** + +- `Other("#[(feature = \"signal\")]")` + +```rust +pub use ctrl_c::ctrl_c; +``` + +## Module `sync` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` +- `Other("#[(loom, allow(dead_code, unreachable_pub, unused_imports))]")` + +Synchronization primitives for use in asynchronous contexts. + +Tokio programs tend to be organized as a set of [tasks] where each task +operates independently and may be executed on separate physical threads. The +synchronization primitives provided in this module permit these independent +tasks to communicate together. + +[tasks]: crate::task + +# Message passing + +The most common form of synchronization in a Tokio program is message +passing. Two tasks operate independently and send messages to each other to +synchronize. Doing so has the advantage of avoiding shared state. + +Message passing is implemented using channels. A channel supports sending a +message from one producer task to one or more consumer tasks. There are a +few flavors of channels provided by Tokio. Each channel flavor supports +different message passing patterns. When a channel supports multiple +producers, many separate tasks may **send** messages. When a channel +supports multiple consumers, many different separate tasks may **receive** +messages. + +Tokio provides many different channel flavors as different message passing +patterns are best handled with different implementations. + +## `oneshot` channel + +The [`oneshot` channel][oneshot] supports sending a **single** value from a +single producer to a single consumer. This channel is usually used to send +the result of a computation to a waiter. + +**Example:** using a [`oneshot` channel][oneshot] to receive the result of a +computation. + +``` +use tokio::sync::oneshot; + +async fn some_computation() -> String { + "represents the result of the computation".to_string() +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel(); + +tokio::spawn(async move { + let res = some_computation().await; + tx.send(res).unwrap(); +}); + +// Do other work while the computation is happening in the background + +// Wait for the computation result +let res = rx.await.unwrap(); +# } +``` + +Note, if the task produces a computation result as its final +action before terminating, the [`JoinHandle`] can be used to +receive that value instead of allocating resources for the +`oneshot` channel. Awaiting on [`JoinHandle`] returns `Result`. If +the task panics, the `Joinhandle` yields `Err` with the panic +cause. + +**Example:** + +``` +async fn some_computation() -> String { + "the result of the computation".to_string() +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let join_handle = tokio::spawn(async move { + some_computation().await +}); + +// Do other work while the computation is happening in the background + +// Wait for the computation result +let res = join_handle.await.unwrap(); +# } +``` + +[`JoinHandle`]: crate::task::JoinHandle + +## `mpsc` channel + +The [`mpsc` channel][mpsc] supports sending **many** values from **many** +producers to a single consumer. This channel is often used to send work to a +task or to receive the result of many computations. + +This is also the channel you should use if you want to send many messages +from a single producer to a single consumer. There is no dedicated spsc +channel. + +**Example:** using an mpsc to incrementally stream the results of a series +of computations. + +``` +use tokio::sync::mpsc; + +async fn some_computation(input: u32) -> String { + format!("the result of computation {}", input) +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx) = mpsc::channel(100); + +tokio::spawn(async move { + for i in 0..10 { + let res = some_computation(i).await; + tx.send(res).await.unwrap(); + } +}); + +while let Some(res) = rx.recv().await { + println!("got = {}", res); +} +# } +``` + +The argument to `mpsc::channel` is the channel capacity. This is the maximum +number of values that can be stored in the channel pending receipt at any +given time. Properly setting this value is key in implementing robust +programs as the channel capacity plays a critical part in handling back +pressure. + +A common concurrency pattern for resource management is to spawn a task +dedicated to managing that resource and using message passing between other +tasks to interact with the resource. The resource may be anything that may +not be concurrently used. Some examples include a socket and program state. +For example, if multiple tasks need to send data over a single socket, spawn +a task to manage the socket and use a channel to synchronize. + +**Example:** sending data from many tasks over a single socket using message +passing. + +```no_run +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::io::{self, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::sync::mpsc; + +#[tokio::main] +async fn main() -> io::Result<()> { + let mut socket = TcpStream::connect("www.example.com:1234").await?; + let (tx, mut rx) = mpsc::channel(100); + + for _ in 0..10 { + // Each task needs its own `tx` handle. This is done by cloning the + // original handle. + let tx = tx.clone(); + + tokio::spawn(async move { + tx.send(&b"data to write"[..]).await.unwrap(); + }); + } + + // The `rx` half of the channel returns `None` once **all** `tx` clones + // drop. To ensure `None` is returned, drop the handle owned by the + // current task. If this `tx` handle is not dropped, there will always + // be a single outstanding `tx` handle. + drop(tx); + + while let Some(res) = rx.recv().await { + socket.write_all(res).await?; + } + + Ok(()) +} +# } +``` + +The [`mpsc`] and [`oneshot`] channels can be combined to provide a request / +response type synchronization pattern with a shared resource. A task is +spawned to synchronize a resource and waits on commands received on a +[`mpsc`] channel. Each command includes a [`oneshot`] `Sender` on which the +result of the command is sent. + +**Example:** use a task to synchronize a `u64` counter. Each task sends an +"fetch and increment" command. The counter value **before** the increment is +sent over the provided `oneshot` channel. + +``` +use tokio::sync::{oneshot, mpsc}; +use Command::Increment; + +enum Command { + Increment, + // Other commands can be added here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (cmd_tx, mut cmd_rx) = mpsc::channel::<(Command, oneshot::Sender)>(100); + +// Spawn a task to manage the counter +tokio::spawn(async move { + let mut counter: u64 = 0; + + while let Some((cmd, response)) = cmd_rx.recv().await { + match cmd { + Increment => { + let prev = counter; + counter += 1; + response.send(prev).unwrap(); + } + } + } +}); + +let mut join_handles = vec![]; + +// Spawn tasks that will send the increment command. +for _ in 0..10 { + let cmd_tx = cmd_tx.clone(); + + join_handles.push(tokio::spawn(async move { + let (resp_tx, resp_rx) = oneshot::channel(); + + cmd_tx.send((Increment, resp_tx)).await.ok().unwrap(); + let res = resp_rx.await.unwrap(); + + println!("previous value = {}", res); + })); +} + +// Wait for all tasks to complete +for join_handle in join_handles.drain(..) { + join_handle.await.unwrap(); +} +# } +``` + +## `broadcast` channel + +The [`broadcast` channel] supports sending **many** values from +**many** producers to **many** consumers. Each consumer will receive +**each** value. This channel can be used to implement "fan out" style +patterns common with pub / sub or "chat" systems. + +This channel tends to be used less often than `oneshot` and `mpsc` but still +has its use cases. + +This is also the channel you should use if you want to broadcast values from +a single producer to many consumers. There is no dedicated spmc broadcast +channel. + +Basic usage + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx1) = broadcast::channel(16); +let mut rx2 = tx.subscribe(); + +tokio::spawn(async move { + assert_eq!(rx1.recv().await.unwrap(), 10); + assert_eq!(rx1.recv().await.unwrap(), 20); +}); + +tokio::spawn(async move { + assert_eq!(rx2.recv().await.unwrap(), 10); + assert_eq!(rx2.recv().await.unwrap(), 20); +}); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +# } +``` + +[`broadcast` channel]: crate::sync::broadcast + +## `watch` channel + +The [`watch` channel] supports sending **many** values from **many** +producers to **many** consumers. However, only the **most recent** value is +stored in the channel. Consumers are notified when a new value is sent, but +there is no guarantee that consumers will see **all** values. + +The [`watch` channel] is similar to a [`broadcast` channel] with capacity 1. + +Use cases for the [`watch` channel] include broadcasting configuration +changes or signalling program state changes, such as transitioning to +shutdown. + +**Example:** use a [`watch` channel] to notify tasks of configuration +changes. In this example, a configuration file is checked periodically. When +the file changes, the configuration changes are signalled to consumers. + +``` +use tokio::sync::watch; +use tokio::time::{self, Duration, Instant}; + +use std::io; + +#[derive(Debug, Clone, Eq, PartialEq)] +struct Config { + timeout: Duration, +} + +impl Config { + async fn load_from_file() -> io::Result { + // file loading and deserialization logic here +# Ok(Config { timeout: Duration::from_secs(1) }) + } +} + +async fn my_async_operation() { + // Do something here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +// Load initial configuration value +let mut config = Config::load_from_file().await.unwrap(); + +// Create the watch channel, initialized with the loaded configuration +let (tx, rx) = watch::channel(config.clone()); + +// Spawn a task to monitor the file. +tokio::spawn(async move { + loop { + // Wait 10 seconds between checks + time::sleep(Duration::from_secs(10)).await; + + // Load the configuration file + let new_config = Config::load_from_file().await.unwrap(); + + // If the configuration changed, send the new config value + // on the watch channel. + if new_config != config { + tx.send(new_config.clone()).unwrap(); + config = new_config; + } + } +}); + +let mut handles = vec![]; + +// Spawn tasks that runs the async operation for at most `timeout`. If +// the timeout elapses, restart the operation. +// +// The task simultaneously watches the `Config` for changes. When the +// timeout duration changes, the timeout is updated without restarting +// the in-flight operation. +for _ in 0..5 { + // Clone a config watch handle for use in this task + let mut rx = rx.clone(); + + let handle = tokio::spawn(async move { + // Start the initial operation and pin the future to the stack. + // Pinning to the stack is required to resume the operation + // across multiple calls to `select!` + let op = my_async_operation(); + tokio::pin!(op); + + // Get the initial config value + let mut conf = rx.borrow().clone(); + + let mut op_start = Instant::now(); + let sleep = time::sleep_until(op_start + conf.timeout); + tokio::pin!(sleep); + + loop { + tokio::select! { + _ = &mut sleep => { + // The operation elapsed. Restart it + op.set(my_async_operation()); + + // Track the new start time + op_start = Instant::now(); + + // Restart the timeout + sleep.set(time::sleep_until(op_start + conf.timeout)); + } + _ = rx.changed() => { + conf = rx.borrow_and_update().clone(); + + // The configuration has been updated. Update the + // `sleep` using the new `timeout` value. + sleep.as_mut().reset(op_start + conf.timeout); + } + _ = &mut op => { + // The operation completed! + return + } + } + } + }); + + handles.push(handle); +} + +for handle in handles.drain(..) { + handle.await.unwrap(); +} +# } +``` + +[`watch` channel]: mod@crate::sync::watch +[`broadcast` channel]: mod@crate::sync::broadcast + +# State synchronization + +The remaining synchronization primitives focus on synchronizing state. +These are asynchronous equivalents to versions provided by `std`. They +operate in a similar way as their `std` counterparts but will wait +asynchronously instead of blocking the thread. + +* [`Barrier`] Ensures multiple tasks will wait for each other to reach a + point in the program, before continuing execution all together. + +* [`Mutex`] Mutual Exclusion mechanism, which ensures that at most one + thread at a time is able to access some data. + +* [`Notify`] Basic task notification. `Notify` supports notifying a + receiving task without sending data. In this case, the task wakes up and + resumes processing. + +* [`RwLock`] Provides a mutual exclusion mechanism which allows multiple + readers at the same time, while allowing only one writer at a time. In + some cases, this can be more efficient than a mutex. + +* [`Semaphore`] Limits the amount of concurrency. A semaphore holds a + number of permits, which tasks may request in order to enter a critical + section. Semaphores are useful for implementing limiting or bounding of + any kind. + +# Runtime compatibility + +All synchronization primitives provided in this module are runtime agnostic. +You can freely move them between different instances of the Tokio runtime +or even use them from non-Tokio runtimes. + +When used in a Tokio runtime, the synchronization primitives participate in +[cooperative scheduling](crate::task::coop#cooperative-scheduling) to avoid +starvation. This feature does not apply when used from non-Tokio runtimes. + +As an exception, methods ending in `_timeout` are not runtime agnostic +because they require access to the Tokio timer. See the documentation of +each `*_timeout` method for more information on its use. + +```rust +pub mod sync { /* ... */ } +``` + +### Modules + +## Module `futures` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +Named future types. + +```rust +pub mod futures { /* ... */ } +``` + +### Re-exports + +#### Re-export `Notified` + +```rust +pub use super::notify::Notified; +``` + +#### Re-export `OwnedNotified` + +```rust +pub use super::notify::OwnedNotified; +``` + +## Module `broadcast` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +A multi-producer, multi-consumer broadcast queue. Each sent value is seen by +all consumers. + +A [`Sender`] is used to broadcast values to **all** connected [`Receiver`] +values. [`Sender`] handles are clone-able, allowing concurrent send and +receive actions. [`Sender`] and [`Receiver`] are both `Send` and `Sync` as +long as `T` is `Send`. + +When a value is sent, **all** [`Receiver`] handles are notified and will +receive the value. The value is stored once inside the channel and cloned on +demand for each receiver. Once all receivers have received a clone of the +value, the value is released from the channel. + +A channel is created by calling [`channel`], specifying the maximum number +of messages the channel can retain at any given time. + +New [`Receiver`] handles are created by calling [`Sender::subscribe`]. The +returned [`Receiver`] will receive values sent **after** the call to +`subscribe`. + +This channel is also suitable for the single-producer multi-consumer +use-case, where a single sender broadcasts values to many receivers. + +## Lagging + +As sent messages must be retained until **all** [`Receiver`] handles receive +a clone, broadcast channels are susceptible to the "slow receiver" problem. +In this case, all but one receiver are able to receive values at the rate +they are sent. Because one receiver is stalled, the channel starts to fill +up. + +This broadcast channel implementation handles this case by setting a hard +upper bound on the number of values the channel may retain at any given +time. This upper bound is passed to the [`channel`] function as an argument. + +If a value is sent when the channel is at capacity, the oldest value +currently held by the channel is released. This frees up space for the new +value. Any receiver that has not yet seen the released value will return +[`RecvError::Lagged`] the next time [`recv`] is called. + +Once [`RecvError::Lagged`] is returned, the lagging receiver's position is +updated to the oldest value contained by the channel. The next call to +[`recv`] will return this value. + +This behavior enables a receiver to detect when it has lagged so far behind +that data has been dropped. The caller may decide how to respond to this: +either by aborting its task or by tolerating lost messages and resuming +consumption of the channel. + +## Closing + +When **all** [`Sender`] handles have been dropped, no new values may be +sent. At this point, the channel is "closed". Once a receiver has received +all values retained by the channel, the next call to [`recv`] will return +with [`RecvError::Closed`]. + +When a [`Receiver`] handle is dropped, any messages not read by the receiver +will be marked as read. If this receiver was the only one not to have read +that message, the message will be dropped at this point. + +[`Sender`]: crate::sync::broadcast::Sender +[`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe +[`Receiver`]: crate::sync::broadcast::Receiver +[`channel`]: crate::sync::broadcast::channel +[`RecvError::Lagged`]: crate::sync::broadcast::error::RecvError::Lagged +[`RecvError::Closed`]: crate::sync::broadcast::error::RecvError::Closed +[`recv`]: crate::sync::broadcast::Receiver::recv + +# Examples + +Basic usage + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx1) = broadcast::channel(16); +let mut rx2 = tx.subscribe(); + +tokio::spawn(async move { + assert_eq!(rx1.recv().await.unwrap(), 10); + assert_eq!(rx1.recv().await.unwrap(), 20); +}); + +tokio::spawn(async move { + assert_eq!(rx2.recv().await.unwrap(), 10); + assert_eq!(rx2.recv().await.unwrap(), 20); +}); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +# } +``` + +Handling lag + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx) = broadcast::channel(2); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +tx.send(30).unwrap(); + +// The receiver lagged behind +assert!(rx.recv().await.is_err()); + +// At this point, we can abort or continue with lost messages + +assert_eq!(20, rx.recv().await.unwrap()); +assert_eq!(30, rx.recv().await.unwrap()); +# } +``` + +```rust +pub mod broadcast { /* ... */ } +``` + +### Modules + +## Module `error` + +Broadcast error types + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `SendError` + +Error returned by the [`send`] function on a [`Sender`]. + +A **send** operation can only fail if there are no active receivers, +implying that the message could never be received. The error contains the +message being sent as a payload so it can be recovered. + +[`send`]: crate::sync::broadcast::Sender::send +[`Sender`]: crate::sync::broadcast::Sender + +```rust +pub struct SendError(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `RecvError` + +An error returned from the [`recv`] function on a [`Receiver`]. + +[`recv`]: crate::sync::broadcast::Receiver::recv +[`Receiver`]: crate::sync::broadcast::Receiver + +```rust +pub enum RecvError { + Closed, + Lagged(u64), +} +``` + +##### Variants + +###### `Closed` + +There are no more active senders implying no further messages will ever +be sent. + +###### `Lagged` + +The receiver lagged too far behind. Attempting to receive again will +return the oldest message still retained by the channel. + +Includes the number of skipped messages. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `u64` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> RecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &RecvError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `TryRecvError` + +An error returned from the [`try_recv`] function on a [`Receiver`]. + +[`try_recv`]: crate::sync::broadcast::Receiver::try_recv +[`Receiver`]: crate::sync::broadcast::Receiver + +```rust +pub enum TryRecvError { + Empty, + Closed, + Lagged(u64), +} +``` + +##### Variants + +###### `Empty` + +The channel is currently empty. There are still active +[`Sender`] handles, so data may yet become available. + +[`Sender`]: crate::sync::broadcast::Sender + +###### `Closed` + +There are no more active senders implying no further messages will ever +be sent. + +###### `Lagged` + +The receiver lagged too far behind and has been forcibly disconnected. +Attempting to receive again will return the oldest message still +retained by the channel. + +Includes the number of skipped messages. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `u64` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> TryRecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &TryRecvError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Types + +#### Struct `Sender` + +Sending-half of the [`broadcast`] channel. + +May be used from many threads. Messages can be sent with +[`send`][Sender::send]. + +# Examples + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx1) = broadcast::channel(16); +let mut rx2 = tx.subscribe(); + +tokio::spawn(async move { + assert_eq!(rx1.recv().await.unwrap(), 10); + assert_eq!(rx1.recv().await.unwrap(), 20); +}); + +tokio::spawn(async move { + assert_eq!(rx2.recv().await.unwrap(), 10); + assert_eq!(rx2.recv().await.unwrap(), 20); +}); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +# } +``` + +[`broadcast`]: crate::sync::broadcast + +```rust +pub struct Sender { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(capacity: usize) -> Self { /* ... */ } + ``` + Creates the sending-half of the [`broadcast`] channel. + +- ```rust + pub fn send(self: &Self, value: T) -> Result> { /* ... */ } + ``` + Attempts to send a value to all active [`Receiver`] handles, returning + +- ```rust + pub fn subscribe(self: &Self) -> Receiver { /* ... */ } + ``` + Creates a new [`Receiver`] handle that will receive values sent **after** + +- ```rust + pub fn downgrade(self: &Self) -> WeakSender { /* ... */ } + ``` + Converts the `Sender` to a [`WeakSender`] that does not count + +- ```rust + pub fn len(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of queued values. + +- ```rust + pub fn is_empty(self: &Self) -> bool { /* ... */ } + ``` + Returns true if there are no queued values. + +- ```rust + pub fn receiver_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of active receivers. + +- ```rust + pub fn same_channel(self: &Self, other: &Self) -> bool { /* ... */ } + ``` + Returns `true` if senders belong to the same channel. + +- ```rust + pub async fn closed(self: &Self) { /* ... */ } + ``` + A future which completes when the number of [Receiver]s subscribed to this `Sender` reaches + +- ```rust + pub fn strong_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`Sender`] handles. + +- ```rust + pub fn weak_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`WeakSender`] handles. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Sender { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `WeakSender` + +A sender that does not prevent the channel from being closed. + +If all [`Sender`] instances of a channel were dropped and only `WeakSender` +instances remain, the channel is closed. + +In order to send messages, the `WeakSender` needs to be upgraded using +[`WeakSender::upgrade`], which returns `Option`. It returns `None` +if all `Sender`s have been dropped, and otherwise it returns a `Sender`. + +[`Sender`]: Sender +[`WeakSender::upgrade`]: WeakSender::upgrade + +# Examples + +``` +use tokio::sync::broadcast::channel; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, _rx) = channel::(15); +let tx_weak = tx.downgrade(); + +// Upgrading will succeed because `tx` still exists. +assert!(tx_weak.upgrade().is_some()); + +// If we drop `tx`, then it will fail. +drop(tx); +assert!(tx_weak.clone().upgrade().is_none()); +# } +``` + +```rust +pub struct WeakSender { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn upgrade(self: &Self) -> Option> { /* ... */ } + ``` + Tries to convert a `WeakSender` into a [`Sender`]. + +- ```rust + pub fn strong_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`Sender`] handles. + +- ```rust + pub fn weak_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`WeakSender`] handles. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> WeakSender { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Receiver` + +Receiving-half of the [`broadcast`] channel. + +Must not be used concurrently. Messages may be retrieved using +[`recv`][Receiver::recv]. + +To turn this receiver into a `Stream`, you can use the [`BroadcastStream`] +wrapper. + +[`BroadcastStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.BroadcastStream.html + +# Examples + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx1) = broadcast::channel(16); +let mut rx2 = tx.subscribe(); + +tokio::spawn(async move { + assert_eq!(rx1.recv().await.unwrap(), 10); + assert_eq!(rx1.recv().await.unwrap(), 20); +}); + +tokio::spawn(async move { + assert_eq!(rx2.recv().await.unwrap(), 10); + assert_eq!(rx2.recv().await.unwrap(), 20); +}); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +# } +``` + +[`broadcast`]: crate::sync::broadcast + +```rust +pub struct Receiver { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn len(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of messages that were sent into the channel and that + +- ```rust + pub fn is_empty(self: &Self) -> bool { /* ... */ } + ``` + Returns true if there aren't any messages in the channel that the [`Receiver`] + +- ```rust + pub fn same_channel(self: &Self, other: &Self) -> bool { /* ... */ } + ``` + Returns `true` if receivers belong to the same channel. + +- ```rust + pub fn sender_strong_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`Sender`] handles. + +- ```rust + pub fn sender_weak_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of [`WeakSender`] handles. + +- ```rust + pub fn is_closed(self: &Self) -> bool { /* ... */ } + ``` + Checks if a channel is closed. + +- ```rust + pub fn resubscribe(self: &Self) -> Self { /* ... */ } + ``` + Re-subscribes to the channel starting from the current tail element. + +- ```rust + pub async fn recv(self: &mut Self) -> Result { /* ... */ } + ``` + Receives the next value for this receiver. + +- ```rust + pub fn try_recv(self: &mut Self) -> Result { /* ... */ } + ``` + Attempts to return a pending value on this receiver without awaiting. + +- ```rust + pub fn blocking_recv(self: &mut Self) -> Result { /* ... */ } + ``` + Blocking receive to call outside of asynchronous contexts. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `channel` + +**Attributes:** + +- `Other("#[attr = TrackCaller]")` + +Create a bounded, multi-producer, multi-consumer channel where each sent +value is broadcasted to all active receivers. + +**Note:** The actual capacity may be greater than the provided `capacity`. + +All data sent on [`Sender`] will become available on every active +[`Receiver`] in the same order as it was sent. + +The `Sender` can be cloned to `send` to the same channel from multiple +points in the process or it can be used concurrently from an `Arc`. New +`Receiver` handles are created by calling [`Sender::subscribe`]. + +If all [`Receiver`] handles are dropped, the `send` method will return a +[`SendError`]. Similarly, if all [`Sender`] handles are dropped, the [`recv`] +method will return a [`RecvError`]. + +[`Sender`]: crate::sync::broadcast::Sender +[`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe +[`Receiver`]: crate::sync::broadcast::Receiver +[`recv`]: crate::sync::broadcast::Receiver::recv +[`SendError`]: crate::sync::broadcast::error::SendError +[`RecvError`]: crate::sync::broadcast::error::RecvError + +# Examples + +``` +use tokio::sync::broadcast; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx1) = broadcast::channel(16); +let mut rx2 = tx.subscribe(); + +tokio::spawn(async move { + assert_eq!(rx1.recv().await.unwrap(), 10); + assert_eq!(rx1.recv().await.unwrap(), 20); +}); + +tokio::spawn(async move { + assert_eq!(rx2.recv().await.unwrap(), 10); + assert_eq!(rx2.recv().await.unwrap(), 20); +}); + +tx.send(10).unwrap(); +tx.send(20).unwrap(); +# } +``` + +# Panics + +This will panic if `capacity` is equal to `0`. + +This pre-allocates space for `capacity` messages. Allocation failure may result in a panic or +[an allocation error](std::alloc::handle_alloc_error). + +```rust +pub fn channel(capacity: usize) -> (Sender, Receiver) { /* ... */ } +``` + +## Module `mpsc` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` +- `Other("#[(not(feature = \"sync\"), allow(dead_code, unreachable_pub))]")` + +A multi-producer, single-consumer queue for sending values between +asynchronous tasks. + +This module provides two variants of the channel: bounded and unbounded. The +bounded variant has a limit on the number of messages that the channel can +store, and if this limit is reached, trying to send another message will +wait until a message is received from the channel. An unbounded channel has +an infinite capacity, so the `send` method will always complete immediately. +This makes the [`UnboundedSender`] usable from both synchronous and +asynchronous code. + +Similar to the `mpsc` channels provided by `std`, the channel constructor +functions provide separate send and receive handles, [`Sender`] and +[`Receiver`] for the bounded channel, [`UnboundedSender`] and +[`UnboundedReceiver`] for the unbounded channel. If there is no message to read, +the current task will be notified when a new value is sent. [`Sender`] and +[`UnboundedSender`] allow sending values into the channel. If the bounded +channel is at capacity, the send is rejected and the task will be notified +when additional capacity is available. In other words, the channel provides +backpressure. + +This channel is also suitable for the single-producer single-consumer +use-case. (Unless you only need to send one message, in which case you +should use the [oneshot] channel.) + +# Disconnection + +When all [`Sender`] handles have been dropped, it is no longer +possible to send values into the channel. This is considered the termination +event of the stream. As such, `Receiver::poll` returns `Ok(Ready(None))`. + +If the [`Receiver`] handle is dropped, then messages can no longer +be read out of the channel. In this case, all further attempts to send will +result in an error. Additionally, all unread messages will be drained from the +channel and dropped. + +# Clean Shutdown + +When the [`Receiver`] is dropped, it is possible for unprocessed messages to +remain in the channel. Instead, it is usually desirable to perform a "clean" +shutdown. To do this, the receiver first calls `close`, which will prevent +any further messages to be sent into the channel. Then, the receiver +consumes the channel to completion, at which point the receiver can be +dropped. + +# Communicating between sync and async code + +When you want to communicate between synchronous and asynchronous code, there +are two situations to consider: + +**Bounded channel**: If you need a bounded channel, you should use a bounded +Tokio `mpsc` channel for both directions of communication. Instead of calling +the async [`send`][bounded-send] or [`recv`][bounded-recv] methods, in +synchronous code you will need to use the [`blocking_send`][blocking-send] or +[`blocking_recv`][blocking-recv] methods. + +**Unbounded channel**: You should use the kind of channel that matches where +the receiver is. So for sending a message _from async to sync_, you should +use [the standard library unbounded channel][std-unbounded] or +[crossbeam][crossbeam-unbounded]. Similarly, for sending a message _from sync +to async_, you should use an unbounded Tokio `mpsc` channel. + +Please be aware that the above remarks were written with the `mpsc` channel +in mind, but they can also be generalized to other kinds of channels. In +general, any channel method that isn't marked async can be called anywhere, +including outside of the runtime. For example, sending a message on a +[oneshot] channel from outside the runtime is perfectly fine. + +# Multiple runtimes + +The `mpsc` channel is runtime agnostic. You can freely move it between +different instances of the Tokio runtime or even use it from non-Tokio +runtimes. + +When used in a Tokio runtime, it participates in +[cooperative scheduling](crate::task::coop#cooperative-scheduling) to avoid +starvation. This feature does not apply when used from non-Tokio runtimes. + +As an exception, methods ending in `_timeout` are not runtime agnostic +because they require access to the Tokio timer. See the documentation of +each `*_timeout` method for more information on its use. + +# Allocation behavior + +
The implementation details described in this section may change in future +Tokio releases.
+ +The mpsc channel stores elements in blocks. Blocks are organized in a linked list. Sending +pushes new elements onto the block at the front of the list, and receiving pops them off the +one at the back. A block can hold 32 messages on a 64-bit target and 16 messages on a 32-bit +target. This number is independent of channel and message size. Each block also stores 4 +pointer-sized values for bookkeeping (so on a 64-bit machine, each message has 1 byte of +overhead). + +When all values in a block have been received, it becomes empty. It will then be freed, unless +the channel's first block (where newly-sent elements are being stored) has no next block. In +that case, the empty block is reused as the next block. + +[`Sender`]: crate::sync::mpsc::Sender +[`Receiver`]: crate::sync::mpsc::Receiver +[bounded-send]: crate::sync::mpsc::Sender::send() +[bounded-recv]: crate::sync::mpsc::Receiver::recv() +[blocking-send]: crate::sync::mpsc::Sender::blocking_send() +[blocking-recv]: crate::sync::mpsc::Receiver::blocking_recv() +[`UnboundedSender`]: crate::sync::mpsc::UnboundedSender +[`UnboundedReceiver`]: crate::sync::mpsc::UnboundedReceiver +[oneshot]: crate::sync::oneshot +[`Handle::block_on`]: crate::runtime::Handle::block_on() +[std-unbounded]: std::sync::mpsc::channel +[crossbeam-unbounded]: https://docs.rs/crossbeam/*/crossbeam/channel/fn.unbounded.html +[`send_timeout`]: crate::sync::mpsc::Sender::send_timeout + +```rust +pub mod mpsc { /* ... */ } +``` + +### Modules + +## Module `error` + +Channel error types. + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `SendError` + +Error returned by the `Sender`. + +```rust +pub struct SendError(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SendError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(src: SendError) -> TrySendError { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &SendError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `TrySendError` + +This enumeration is the list of the possible error outcomes for the +[`try_send`](super::Sender::try_send) method. + +```rust +pub enum TrySendError { + Full(T), + Closed(T), +} +``` + +##### Variants + +###### `Full` + +The data could not be sent on the channel because the channel is +currently full and sending would require blocking. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +###### `Closed` + +The receive half of the channel was explicitly closed or has been +dropped. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_inner(self: Self) -> T { /* ... */ } + ``` + Consume the `TrySendError`, returning the unsent value. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> TrySendError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(src: SendError) -> TrySendError { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &TrySendError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `TryRecvError` + +Error returned by `try_recv`. + +```rust +pub enum TryRecvError { + Empty, + Disconnected, +} +``` + +##### Variants + +###### `Empty` + +This **channel** is currently empty, but the **Sender**(s) have not yet +disconnected, so data may yet become available. + +###### `Disconnected` + +The **channel**'s sending half has become disconnected, and there will +never be any more data received on it. + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> TryRecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &TryRecvError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `SendTimeoutError` + +**Attributes:** + +- `Other("#[(feature = \"time\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"time\")))]")` +- `Other("#[doc(cfg(feature = \"time\"))]")` + +Error returned by [`Sender::send_timeout`](super::Sender::send_timeout)]. + +```rust +pub enum SendTimeoutError { + Timeout(T), + Closed(T), +} +``` + +##### Variants + +###### `Timeout` + +The data could not be sent on the channel because the channel is +full, and the timeout to send has elapsed. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +###### `Closed` + +The receive half of the channel was explicitly closed or has been +dropped. + +Fields: + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Methods + +- ```rust + pub fn into_inner(self: Self) -> T { /* ... */ } + ``` + Consume the `SendTimeoutError`, returning the unsent value. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SendTimeoutError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &SendTimeoutError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Re-exports + +#### Re-export `channel` + +```rust +pub use self::bounded::channel; +``` + +#### Re-export `OwnedPermit` + +```rust +pub use self::bounded::OwnedPermit; +``` + +#### Re-export `Permit` + +```rust +pub use self::bounded::Permit; +``` + +#### Re-export `PermitIterator` + +```rust +pub use self::bounded::PermitIterator; +``` + +#### Re-export `Receiver` + +```rust +pub use self::bounded::Receiver; +``` + +#### Re-export `Sender` + +```rust +pub use self::bounded::Sender; +``` + +#### Re-export `WeakSender` + +```rust +pub use self::bounded::WeakSender; +``` + +#### Re-export `unbounded_channel` + +```rust +pub use self::unbounded::unbounded_channel; +``` + +#### Re-export `UnboundedReceiver` + +```rust +pub use self::unbounded::UnboundedReceiver; +``` + +#### Re-export `UnboundedSender` + +```rust +pub use self::unbounded::UnboundedSender; +``` + +#### Re-export `WeakUnboundedSender` + +```rust +pub use self::unbounded::WeakUnboundedSender; +``` + +## Module `oneshot` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` +- `Other("#[(not(feature = \"sync\"), allow(dead_code, unreachable_pub))]")` + +A one-shot channel is used for sending a single message between +asynchronous tasks. The [`channel`] function is used to create a +[`Sender`] and [`Receiver`] handle pair that form the channel. + +The `Sender` handle is used by the producer to send the value. +The `Receiver` handle is used by the consumer to receive the value. + +Each handle can be used on separate tasks. + +Since the `send` method is not async, it can be used anywhere. This includes +sending between two runtimes, and using it from non-async code. + +If the [`Receiver`] is closed before receiving a message which has already +been sent, the message will remain in the channel until the receiver is +dropped, at which point the message will be dropped immediately. + +# Examples + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel(); + +tokio::spawn(async move { + if let Err(_) = tx.send(3) { + println!("the receiver dropped"); + } +}); + +match rx.await { + Ok(v) => println!("got = {:?}", v), + Err(_) => println!("the sender dropped"), +} +# } +``` + +If the sender is dropped without sending, the receiver will fail with +[`error::RecvError`]: + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel::(); + +tokio::spawn(async move { + drop(tx); +}); + +match rx.await { + Ok(_) => panic!("This doesn't happen"), + Err(_) => println!("the sender dropped"), +} +# } +``` + +To use a `oneshot` channel in a `tokio::select!` loop, add `&mut` in front of +the channel. + +``` +use tokio::sync::oneshot; +use tokio::time::{interval, sleep, Duration}; + +# #[tokio::main(flavor = "current_thread")] +# async fn _doc() {} +# #[tokio::main(flavor = "current_thread", start_paused = true)] +# async fn main() { +let (send, mut recv) = oneshot::channel(); +let mut interval = interval(Duration::from_millis(100)); + +# let handle = +tokio::spawn(async move { + sleep(Duration::from_secs(1)).await; + send.send("shut down").unwrap(); +}); + +loop { + tokio::select! { + _ = interval.tick() => println!("Another 100ms"), + msg = &mut recv => { + println!("Got message: {}", msg.unwrap()); + break; + } + } +} +# handle.await.unwrap(); +# } +``` + +To use a `Sender` from a destructor, put it in an [`Option`] and call +[`Option::take`]. + +``` +use tokio::sync::oneshot; + +struct SendOnDrop { + sender: Option>, +} +impl Drop for SendOnDrop { + fn drop(&mut self) { + if let Some(sender) = self.sender.take() { + // Using `let _ =` to ignore send errors. + let _ = sender.send("I got dropped!"); + } + } +} + +# #[tokio::main(flavor = "current_thread")] +# async fn _doc() {} +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (send, recv) = oneshot::channel(); + +let send_on_drop = SendOnDrop { sender: Some(send) }; +drop(send_on_drop); + +assert_eq!(recv.await, Ok("I got dropped!")); +# } +``` + +```rust +pub mod oneshot { /* ... */ } +``` + +### Modules + +## Module `error` + +`Oneshot` error types. + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `RecvError` + +Error returned by the `Future` implementation for `Receiver`. + +This error is returned by the receiver when the sender is dropped without sending. + +```rust +pub struct RecvError(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> RecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &RecvError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Enum `TryRecvError` + +Error returned by the `try_recv` function on `Receiver`. + +```rust +pub enum TryRecvError { + Empty, + Closed, +} +``` + +##### Variants + +###### `Empty` + +The send half of the channel has not yet sent a value. + +###### `Closed` + +The send half of the channel was dropped without sending a value. + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> TryRecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &TryRecvError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Types + +#### Struct `Sender` + +Sends a value to the associated [`Receiver`]. + +A pair of both a [`Sender`] and a [`Receiver`] are created by the +[`channel`](fn@channel) function. + +# Examples + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel(); + +tokio::spawn(async move { + if let Err(_) = tx.send(3) { + println!("the receiver dropped"); + } +}); + +match rx.await { + Ok(v) => println!("got = {:?}", v), + Err(_) => println!("the sender dropped"), +} +# } +``` + +If the sender is dropped without sending, the receiver will fail with +[`error::RecvError`]: + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel::(); + +tokio::spawn(async move { + drop(tx); +}); + +match rx.await { + Ok(_) => panic!("This doesn't happen"), + Err(_) => println!("the sender dropped"), +} +# } +``` + +To use a `Sender` from a destructor, put it in an [`Option`] and call +[`Option::take`]. + +``` +use tokio::sync::oneshot; + +struct SendOnDrop { + sender: Option>, +} +impl Drop for SendOnDrop { + fn drop(&mut self) { + if let Some(sender) = self.sender.take() { + // Using `let _ =` to ignore send errors. + let _ = sender.send("I got dropped!"); + } + } +} + +# #[tokio::main(flavor = "current_thread")] +# async fn _doc() {} +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (send, recv) = oneshot::channel(); + +let send_on_drop = SendOnDrop { sender: Some(send) }; +drop(send_on_drop); + +assert_eq!(recv.await, Ok("I got dropped!")); +# } +``` + +[`Option`]: std::option::Option +[`Option::take`]: std::option::Option::take + +```rust +pub struct Sender { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn send(self: Self, t: T) -> Result<(), T> { /* ... */ } + ``` + Attempts to send a value on this channel, returning it back if it could + +- ```rust + pub async fn closed(self: &mut Self) { /* ... */ } + ``` + Waits for the associated [`Receiver`] handle to close. + +- ```rust + pub fn is_closed(self: &Self) -> bool { /* ... */ } + ``` + Returns `true` if the associated [`Receiver`] handle has been dropped. + +- ```rust + pub fn poll_closed(self: &mut Self, cx: &mut Context<''_>) -> Poll<()> { /* ... */ } + ``` + Checks whether the `oneshot` channel has been closed, and if not, schedules the + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Receiver` + +Receives a value from the associated [`Sender`]. + +A pair of both a [`Sender`] and a [`Receiver`] are created by the +[`channel`](fn@channel) function. + +This channel has no `recv` method because the receiver itself implements the +[`Future`] trait. To receive a `Result`, `.await` the `Receiver` object directly. + +The `poll` method on the `Future` trait is allowed to spuriously return +`Poll::Pending` even if the message has been sent. If such a spurious +failure happens, then the caller will be woken when the spurious failure has +been resolved so that the caller can attempt to receive the message again. +Note that receiving such a wakeup does not guarantee that the next call will +succeed — it could fail with another spurious failure. (A spurious failure +does not mean that the message is lost. It is just delayed.) + +[`Future`]: trait@std::future::Future + +# Examples + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel(); + +tokio::spawn(async move { + if let Err(_) = tx.send(3) { + println!("the receiver dropped"); + } +}); + +match rx.await { + Ok(v) => println!("got = {:?}", v), + Err(_) => println!("the sender dropped"), +} +# } +``` + +If the sender is dropped without sending, the receiver will fail with +[`error::RecvError`]: + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel::(); + +tokio::spawn(async move { + drop(tx); +}); + +match rx.await { + Ok(_) => panic!("This doesn't happen"), + Err(_) => println!("the sender dropped"), +} +# } +``` + +To use a `Receiver` in a `tokio::select!` loop, add `&mut` in front of the +channel. + +``` +use tokio::sync::oneshot; +use tokio::time::{interval, sleep, Duration}; + +# #[tokio::main(flavor = "current_thread")] +# async fn _doc() {} +# #[tokio::main(flavor = "current_thread", start_paused = true)] +# async fn main() { +let (send, mut recv) = oneshot::channel(); +let mut interval = interval(Duration::from_millis(100)); + +# let handle = +tokio::spawn(async move { + sleep(Duration::from_secs(1)).await; + send.send("shut down").unwrap(); +}); + +loop { + tokio::select! { + _ = interval.tick() => println!("Another 100ms"), + msg = &mut recv => { + println!("Got message: {}", msg.unwrap()); + break; + } + } +} +# handle.await.unwrap(); +# } +``` + +```rust +pub struct Receiver { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn close(self: &mut Self) { /* ... */ } + ``` + Prevents the associated [`Sender`] handle from sending a value. + +- ```rust + pub fn is_terminated(self: &Self) -> bool { /* ... */ } + ``` + Checks if this receiver is terminated. + +- ```rust + pub fn is_empty(self: &Self) -> bool { /* ... */ } + ``` + Checks if a channel is empty. + +- ```rust + pub fn try_recv(self: &mut Self) -> Result { /* ... */ } + ``` + Attempts to receive a value. + +- ```rust + pub fn blocking_recv(self: Self) -> Result { /* ... */ } + ``` + Blocking receive to call outside of asynchronous contexts. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `channel` + +**Attributes:** + +- `Other("#[attr = TrackCaller]")` + +Creates a new one-shot channel for sending single values across asynchronous +tasks. + +The function returns separate "send" and "receive" handles. The `Sender` +handle is used by the producer to send the value. The `Receiver` handle is +used by the consumer to receive the value. + +Each handle can be used on separate tasks. + +# Examples + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, rx) = oneshot::channel(); + +tokio::spawn(async move { + if let Err(_) = tx.send(3) { + println!("the receiver dropped"); + } +}); + +match rx.await { + Ok(v) => println!("got = {:?}", v), + Err(_) => println!("the sender dropped"), +} +# } +``` + +```rust +pub fn channel() -> (Sender, Receiver) { /* ... */ } +``` + +## Module `watch` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` +- `Other("#[(not(feature = \"sync\"), allow(dead_code, unreachable_pub))]")` + +A multi-producer, multi-consumer channel that only retains the *last* sent +value. + +This channel is useful for watching for changes to a value from multiple +points in the code base, for example, changes to configuration values. + +# Usage + +[`channel`] returns a [`Sender`] / [`Receiver`] pair. These are the producer +and consumer halves of the channel. The channel is created with an initial +value. + +Each [`Receiver`] independently tracks the last value *seen* by its caller. + +To access the **current** value stored in the channel and mark it as *seen* +by a given [`Receiver`], use [`Receiver::borrow_and_update()`]. + +To access the current value **without** marking it as *seen*, use +[`Receiver::borrow()`]. (If the value has already been marked *seen*, +[`Receiver::borrow()`] is equivalent to [`Receiver::borrow_and_update()`].) + +For more information on when to use these methods, see +[here](#borrow_and_update-versus-borrow). + +## Change notifications + +The [`Receiver`] half provides an asynchronous [`changed`] method. This +method is ready when a new, *unseen* value is sent via the [`Sender`] half. + +* [`Receiver::changed()`] returns: + * `Ok(())` on receiving a new value. + * `Err(`[`RecvError`](error::RecvError)`)` if the + channel has been closed __AND__ the current value is *seen*. +* If the current value is *unseen* when calling [`changed`], then + [`changed`] will return immediately. If the current value is *seen*, then + it will sleep until either a new message is sent via the [`Sender`] half, + or the [`Sender`] is dropped. +* On completion, the [`changed`] method marks the new value as *seen*. +* At creation, the initial value is considered *seen*. In other words, + [`Receiver::changed()`] will not return until a subsequent value is sent. +* New [`Receiver`] instances can be created with [`Sender::subscribe()`]. + The current value at the time the [`Receiver`] is created is considered + *seen*. + +## [`changed`] versus [`has_changed`] + +The [`Receiver`] half provides two methods for checking for changes +in the channel, [`has_changed`] and [`changed`]. + +* [`has_changed`] is a *synchronous* method that checks whether the current + value is seen or not and returns a boolean. This method does __not__ mark the + value as seen. + +* [`changed`] is an *asynchronous* method that will return once an unseen + value is in the channel. This method does mark the value as seen. + +Note there are two behavioral differences on when these two methods return +an error. + +- [`has_changed`] errors if and only if the channel is closed. +- [`changed`] errors if the channel has been closed __AND__ + the current value is seen. + +See the example below that shows how these methods have different fallibility. + +## [`borrow_and_update`] versus [`borrow`] + +If the receiver intends to await notifications from [`changed`] in a loop, +[`Receiver::borrow_and_update()`] should be preferred over +[`Receiver::borrow()`]. This avoids a potential race where a new value is +sent between [`changed`] being ready and the value being read. (If +[`Receiver::borrow()`] is used, the loop may run twice with the same value.) + +If the receiver is only interested in the current value, and does not intend +to wait for changes, then [`Receiver::borrow()`] can be used. It may be more +convenient to use [`borrow`](Receiver::borrow) since it's an `&self` +method---[`borrow_and_update`](Receiver::borrow_and_update) requires `&mut +self`. + +# Examples + +The following example prints `hello! world! `. + +``` +use tokio::sync::watch; +use tokio::time::{Duration, sleep}; + +# async fn dox() -> Result<(), Box> { +let (tx, mut rx) = watch::channel("hello"); + +tokio::spawn(async move { + // Use the equivalent of a "do-while" loop so the initial value is + // processed before awaiting the `changed()` future. + loop { + println!("{}! ", *rx.borrow_and_update()); + if rx.changed().await.is_err() { + break; + } + } +}); + +sleep(Duration::from_millis(100)).await; +tx.send("world")?; +# Ok(()) +# } +``` + +Difference on fallibility of [`changed`] versus [`has_changed`]. +``` +use tokio::sync::watch; + +#[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx, mut rx) = watch::channel("hello"); +tx.send("goodbye").unwrap(); +drop(tx); + +// `has_changed` does not mark the value as seen and errors +// since the channel is closed. +assert!(rx.has_changed().is_err()); + +// `changed` returns Ok since the value is not already marked as seen +// even if the channel is closed. +assert!(rx.changed().await.is_ok()); + +// The `changed` call above marks the value as seen. +// The next `changed` call now returns an error as the channel is closed +// AND the current value is seen. +assert!(rx.changed().await.is_err()); +# } +``` + +# Closing + +[`Sender::is_closed`] and [`Sender::closed`] allow the producer to detect +when all [`Receiver`] handles have been dropped. This indicates that there +is no further interest in the values being produced and work can be stopped. + +The value in the channel will not be dropped until all senders and all +receivers have been dropped. + +# Thread safety + +Both [`Sender`] and [`Receiver`] are thread safe. They can be moved to other +threads and can be used in a concurrent environment. Clones of [`Receiver`] +handles may be moved to separate threads and also used concurrently. + +[`Sender`]: crate::sync::watch::Sender +[`Receiver`]: crate::sync::watch::Receiver +[`changed`]: crate::sync::watch::Receiver::changed +[`has_changed`]: crate::sync::watch::Receiver::has_changed +[`borrow`]: crate::sync::watch::Receiver::borrow +[`borrow_and_update`]: crate::sync::watch::Receiver::borrow_and_update +[`Receiver::changed()`]: crate::sync::watch::Receiver::changed +[`Receiver::borrow()`]: crate::sync::watch::Receiver::borrow +[`Receiver::borrow_and_update()`]: + crate::sync::watch::Receiver::borrow_and_update +[`channel`]: crate::sync::watch::channel +[`Sender::is_closed`]: crate::sync::watch::Sender::is_closed +[`Sender::closed`]: crate::sync::watch::Sender::closed +[`Sender::subscribe()`]: crate::sync::watch::Sender::subscribe + +```rust +pub mod watch { /* ... */ } +``` + +### Modules + +## Module `error` + +Watch error types. + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `SendError` + +Error produced when sending a value fails. + +```rust +pub struct SendError(pub T); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `T` | | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> SendError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &SendError) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `RecvError` + +Error produced when receiving a change notification. + +```rust +pub struct RecvError(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> RecvError { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Types + +#### Struct `Receiver` + +Receives values from the associated [`Sender`](struct@Sender). + +Instances are created by the [`channel`](fn@channel) function. + +To turn this receiver into a `Stream`, you can use the [`WatchStream`] +wrapper. + +[`WatchStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.WatchStream.html + +```rust +pub struct Receiver { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn borrow(self: &Self) -> Ref<''_, T> { /* ... */ } + ``` + Returns a reference to the most recently sent value. + +- ```rust + pub fn borrow_and_update(self: &mut Self) -> Ref<''_, T> { /* ... */ } + ``` + Returns a reference to the most recently sent value and marks that value + +- ```rust + pub fn has_changed(self: &Self) -> Result { /* ... */ } + ``` + Checks if this channel contains a message that this receiver has not yet + +- ```rust + pub fn mark_changed(self: &mut Self) { /* ... */ } + ``` + Marks the state as changed. + +- ```rust + pub fn mark_unchanged(self: &mut Self) { /* ... */ } + ``` + Marks the state as unchanged. + +- ```rust + pub async fn changed(self: &mut Self) -> Result<(), error::RecvError> { /* ... */ } + ``` + Waits for a change notification, then marks the current value as seen. + +- ```rust + pub async fn wait_for bool: FnMut(&T) -> bool>(self: &mut Self, f: impl FnMut(&T) -> bool) -> Result, error::RecvError> { /* ... */ } + ``` + Waits for a value that satisfies the provided condition. + +- ```rust + pub fn same_channel(self: &Self, other: &Self) -> bool { /* ... */ } + ``` + Returns `true` if receivers belong to the same channel. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Sender` + +Sends values to the associated [`Receiver`](struct@Receiver). + +Instances are created by the [`channel`](fn@channel) function. + +```rust +pub struct Sender { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new(init: T) -> Self { /* ... */ } + ``` + Creates the sending-half of the [`watch`] channel. + +- ```rust + pub fn send(self: &Self, value: T) -> Result<(), error::SendError> { /* ... */ } + ``` + Sends a new value via the channel, notifying all receivers. + +- ```rust + pub fn send_modify(self: &Self, modify: F) +where + F: FnOnce(&mut T) { /* ... */ } + ``` + Modifies the watched value **unconditionally** in-place, + +- ```rust + pub fn send_if_modified(self: &Self, modify: F) -> bool +where + F: FnOnce(&mut T) -> bool { /* ... */ } + ``` + Modifies the watched value **conditionally** in-place, + +- ```rust + pub fn send_replace(self: &Self, value: T) -> T { /* ... */ } + ``` + Sends a new value via the channel, notifying all receivers and returning + +- ```rust + pub fn borrow(self: &Self) -> Ref<''_, T> { /* ... */ } + ``` + Returns a reference to the most recently sent value + +- ```rust + pub fn is_closed(self: &Self) -> bool { /* ... */ } + ``` + Checks if the channel has been closed. This happens when all receivers + +- ```rust + pub async fn closed(self: &Self) { /* ... */ } + ``` + Completes when all receivers have dropped. + +- ```rust + pub fn subscribe(self: &Self) -> Receiver { /* ... */ } + ``` + Creates a new [`Receiver`] connected to this `Sender`. + +- ```rust + pub fn receiver_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of receivers that currently exist. + +- ```rust + pub fn sender_count(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of senders that currently exist. + +- ```rust + pub fn same_channel(self: &Self, other: &Self) -> bool { /* ... */ } + ``` + Returns `true` if senders belong to the same channel. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Self { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Ref` + +Returns a reference to the inner value. + +Outstanding borrows hold a read lock on the inner value. This means that +long-lived borrows could cause the producer half to block. It is recommended +to keep the borrow as short-lived as possible. Additionally, if you are +running in an environment that allows `!Send` futures, you must ensure that +the returned `Ref` type is never held alive across an `.await` point, +otherwise, it can lead to a deadlock. + +The priority policy of the lock is dependent on the underlying lock +implementation, and this type does not guarantee that any particular policy +will be used. In particular, a producer which is waiting to acquire the lock +in `send` might or might not block concurrent calls to `borrow`, e.g.: + +
Potential deadlock example + +```text +// Task 1 (on thread A) | // Task 2 (on thread B) +let _ref1 = rx.borrow(); | + | // will block + | let _ = tx.send(()); +// may deadlock | +let _ref2 = rx.borrow(); | +``` +
+ +```rust +pub struct Ref<''a, T> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn has_changed(self: &Self) -> bool { /* ... */ } + ``` + Indicates if the borrowed value is considered as _changed_ since the last + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Deref** + - ```rust + fn deref(self: &Self) -> &T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **Receiver** +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `channel` + +Creates a new watch channel, returning the "send" and "receive" handles. + +All values sent by [`Sender`] will become visible to the [`Receiver`] handles. +Only the last value sent is made available to the [`Receiver`] half. All +intermediate values are dropped. + +# Examples + +The following example prints `hello! world! `. + +``` +use tokio::sync::watch; +use tokio::time::{Duration, sleep}; + +# async fn dox() -> Result<(), Box> { +let (tx, mut rx) = watch::channel("hello"); + +tokio::spawn(async move { + // Use the equivalent of a "do-while" loop so the initial value is + // processed before awaiting the `changed()` future. + loop { + println!("{}! ", *rx.borrow_and_update()); + if rx.changed().await.is_err() { + break; + } + } +}); + +sleep(Duration::from_millis(100)).await; +tx.send("world")?; +# Ok(()) +# } +``` + +[`Sender`]: struct@Sender +[`Receiver`]: struct@Receiver + +```rust +pub fn channel(init: T) -> (Sender, Receiver) { /* ... */ } +``` + +### Re-exports + +#### Re-export `Barrier` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use barrier::Barrier; +``` + +#### Re-export `BarrierWaitResult` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use barrier::BarrierWaitResult; +``` + +#### Re-export `Mutex` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::Mutex; +``` + +#### Re-export `MutexGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::MutexGuard; +``` + +#### Re-export `TryLockError` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::TryLockError; +``` + +#### Re-export `OwnedMutexGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::OwnedMutexGuard; +``` + +#### Re-export `MappedMutexGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::MappedMutexGuard; +``` + +#### Re-export `OwnedMappedMutexGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use mutex::OwnedMappedMutexGuard; +``` + +#### Re-export `Notify` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use notify::Notify; +``` + +#### Re-export `AcquireError` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use batch_semaphore::AcquireError; +``` + +#### Re-export `TryAcquireError` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use batch_semaphore::TryAcquireError; +``` + +#### Re-export `Semaphore` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use semaphore::Semaphore; +``` + +#### Re-export `SemaphorePermit` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use semaphore::SemaphorePermit; +``` + +#### Re-export `OwnedSemaphorePermit` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use semaphore::OwnedSemaphorePermit; +``` + +#### Re-export `RwLock` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::RwLock; +``` + +#### Re-export `OwnedRwLockReadGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::owned_read_guard::OwnedRwLockReadGuard; +``` + +#### Re-export `OwnedRwLockWriteGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::owned_write_guard::OwnedRwLockWriteGuard; +``` + +#### Re-export `OwnedRwLockMappedWriteGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::owned_write_guard_mapped::OwnedRwLockMappedWriteGuard; +``` + +#### Re-export `RwLockReadGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::read_guard::RwLockReadGuard; +``` + +#### Re-export `RwLockWriteGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::write_guard::RwLockWriteGuard; +``` + +#### Re-export `RwLockMappedWriteGuard` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use rwlock::write_guard_mapped::RwLockMappedWriteGuard; +``` + +#### Re-export `OnceCell` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use self::once_cell::OnceCell; +``` + +#### Re-export `SetError` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use self::once_cell::SetError; +``` + +#### Re-export `SetOnce` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use self::set_once::SetOnce; +``` + +#### Re-export `SetOnceError` + +**Attributes:** + +- `Other("#[(feature = \"sync\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"sync\")))]")` +- `Other("#[doc(cfg(feature = \"sync\"))]")` + +```rust +pub use self::set_once::SetOnceError; +``` + +## Module `task` + +Asynchronous green-threads. + +## What are Tasks? + +A _task_ is a light weight, non-blocking unit of execution. A task is similar +to an OS thread, but rather than being managed by the OS scheduler, they are +managed by the [Tokio runtime][rt]. Another name for this general pattern is +[green threads]. If you are familiar with [Go's goroutines], [Kotlin's +coroutines], or [Erlang's processes], you can think of Tokio's tasks as +something similar. + +Key points about tasks include: + +* Tasks are **light weight**. Because tasks are scheduled by the Tokio + runtime rather than the operating system, creating new tasks or switching + between tasks does not require a context switch and has fairly low + overhead. Creating, running, and destroying large numbers of tasks is + quite cheap, especially compared to OS threads. + +* Tasks are scheduled **cooperatively**. Most operating systems implement + _preemptive multitasking_. This is a scheduling technique where the + operating system allows each thread to run for a period of time, and then + _preempts_ it, temporarily pausing that thread and switching to another. + Tasks, on the other hand, implement _cooperative multitasking_. In + cooperative multitasking, a task is allowed to run until it _yields_, + indicating to the Tokio runtime's scheduler that it cannot currently + continue executing. When a task yields, the Tokio runtime switches to + executing the next task. + +* Tasks are **non-blocking**. Typically, when an OS thread performs I/O or + must synchronize with another thread, it _blocks_, allowing the OS to + schedule another thread. When a task cannot continue executing, it must + yield instead, allowing the Tokio runtime to schedule another task. Tasks + should generally not perform system calls or other operations that could + block a thread, as this would prevent other tasks running on the same + thread from executing as well. Instead, this module provides APIs for + running blocking operations in an asynchronous context. + +[rt]: crate::runtime +[green threads]: https://en.wikipedia.org/wiki/Green_threads +[Go's goroutines]: https://tour.golang.org/concurrency/1 +[Kotlin's coroutines]: https://kotlinlang.org/docs/reference/coroutines-overview.html +[Erlang's processes]: http://erlang.org/doc/getting_started/conc_prog.html#processes + +## Working with Tasks + +This module provides the following APIs for working with tasks: + +### Spawning + +Perhaps the most important function in this module is [`task::spawn`]. This +function can be thought of as an async equivalent to the standard library's +[`thread::spawn`][`std::thread::spawn`]. It takes an `async` block or other +[future], and creates a new task to run that work concurrently: + +``` +use tokio::task; + +# async fn doc() { +task::spawn(async { + // perform some work here... +}); +# } +``` + +Like [`std::thread::spawn`], `task::spawn` returns a [`JoinHandle`] struct. +A `JoinHandle` is itself a future which may be used to await the output of +the spawned task. For example: + +``` +use tokio::task; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() -> Result<(), Box> { +let join = task::spawn(async { + // ... + "hello world!" +}); + +// ... + +// Await the result of the spawned task. +let result = join.await?; +assert_eq!(result, "hello world!"); +# Ok(()) +# } +``` + +Again, like `std::thread`'s [`JoinHandle` type][thread_join], if the spawned +task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For +example: + +``` +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::task; + +# #[tokio::main] async fn main() { +let join = task::spawn(async { + panic!("something bad happened!") +}); + +// The returned result indicates that the task failed. +assert!(join.await.is_err()); +# } +# } +``` + +`spawn`, `JoinHandle`, and `JoinError` are present when the "rt" +feature flag is enabled. + +[`task::spawn`]: crate::task::spawn() +[future]: std::future::Future +[`std::thread::spawn`]: std::thread::spawn +[`JoinHandle`]: crate::task::JoinHandle +[thread_join]: std::thread::JoinHandle +[`JoinError`]: crate::task::JoinError + +#### Cancellation + +Spawned tasks may be cancelled using the [`JoinHandle::abort`] or +[`AbortHandle::abort`] methods. When one of these methods are called, the +task is signalled to shut down next time it yields at an `.await` point. If +the task is already idle, then it will be shut down as soon as possible +without running again before being shut down. Additionally, shutting down a +Tokio runtime (e.g. by returning from `#[tokio::main]`) immediately cancels +all tasks on it. + +When tasks are shut down, it will stop running at whichever `.await` it has +yielded at. All local variables are destroyed by running their destructor. +Once shutdown has completed, awaiting the [`JoinHandle`] will fail with a +[cancelled error](crate::task::JoinError::is_cancelled). + +Note that aborting a task does not guarantee that it fails with a cancelled +error, since it may complete normally first. For example, if the task does +not yield to the runtime at any point between the call to `abort` and the +end of the task, then the [`JoinHandle`] will instead report that the task +exited normally. + +Be aware that tasks spawned using [`spawn_blocking`] cannot be aborted +because they are not async. If you call `abort` on a `spawn_blocking` +task, then this *will not have any effect*, and the task will continue +running normally. The exception is if the task has not started running +yet; in that case, calling `abort` may prevent the task from starting. + +Be aware that calls to [`JoinHandle::abort`] just schedule the task for +cancellation, and will return before the cancellation has completed. To wait +for cancellation to complete, wait for the task to finish by awaiting the +[`JoinHandle`]. Similarly, the [`JoinHandle::is_finished`] method does not +return `true` until the cancellation has finished. + +Calling [`JoinHandle::abort`] multiple times has the same effect as calling +it once. + +Tokio also provides an [`AbortHandle`], which is like the [`JoinHandle`], +except that it does not provide a mechanism to wait for the task to finish. +Each task can only have one [`JoinHandle`], but it can have more than one +[`AbortHandle`]. + +[`JoinHandle::abort`]: crate::task::JoinHandle::abort +[`AbortHandle::abort`]: crate::task::AbortHandle::abort +[`AbortHandle`]: crate::task::AbortHandle +[`JoinHandle::is_finished`]: crate::task::JoinHandle::is_finished + +### Blocking and Yielding + +As we discussed above, code running in asynchronous tasks should not perform +operations that can block. A blocking operation performed in a task running +on a thread that is also running other tasks would block the entire thread, +preventing other tasks from running. + +Instead, Tokio provides two APIs for running blocking operations in an +asynchronous context: [`task::spawn_blocking`] and [`task::block_in_place`]. + +Be aware that if you call a non-async method from async code, that non-async +method is still inside the asynchronous context, so you should also avoid +blocking operations there. This includes destructors of objects destroyed in +async code. + +#### `spawn_blocking` + +The `task::spawn_blocking` function is similar to the `task::spawn` function +discussed in the previous section, but rather than spawning an +_non-blocking_ future on the Tokio runtime, it instead spawns a +_blocking_ function on a dedicated thread pool for blocking tasks. For +example: + +``` +use tokio::task; + +# async fn docs() { +task::spawn_blocking(|| { + // do some compute-heavy work or call synchronous code +}); +# } +``` + +Just like `task::spawn`, `task::spawn_blocking` returns a `JoinHandle` +which we can use to await the result of the blocking operation: + +```rust +# use tokio::task; +# async fn docs() -> Result<(), Box>{ +let join = task::spawn_blocking(|| { + // do some compute-heavy work or call synchronous code + "blocking completed" +}); + +let result = join.await?; +assert_eq!(result, "blocking completed"); +# Ok(()) +# } +``` + +#### `block_in_place` + +When using the [multi-threaded runtime][rt-multi-thread], the [`task::block_in_place`] +function is also available. Like `task::spawn_blocking`, this function +allows running a blocking operation from an asynchronous context. Unlike +`spawn_blocking`, however, `block_in_place` works by transitioning the +_current_ worker thread to a blocking thread, moving other tasks running on +that thread to another worker thread. This can improve performance by avoiding +context switches. + +For example: + +``` +# #[cfg(not(target_family = "wasm"))] +# { +use tokio::task; + +# async fn docs() { +let result = task::block_in_place(|| { + // do some compute-heavy work or call synchronous code + "blocking completed" +}); + +assert_eq!(result, "blocking completed"); +# } +# } +``` + +#### `yield_now` + +In addition, this module provides a [`task::yield_now`] async function +that is analogous to the standard library's [`thread::yield_now`]. Calling +and `await`ing this function will cause the current task to yield to the +Tokio runtime's scheduler, allowing other tasks to be +scheduled. Eventually, the yielding task will be polled again, allowing it +to execute. For example: + +```rust +use tokio::task; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +async { + task::spawn(async { + // ... + println!("spawned task done!") + }); + + // Yield, allowing the newly-spawned task to execute first. + task::yield_now().await; + println!("main task done!"); +} +# .await; +# } +``` + +[`task::spawn_blocking`]: crate::task::spawn_blocking +[`task::block_in_place`]: crate::task::block_in_place +[rt-multi-thread]: ../runtime/index.html#threaded-scheduler +[`task::yield_now`]: crate::task::yield_now() +[`thread::yield_now`]: std::thread::yield_now + +```rust +pub mod task { /* ... */ } +``` + +### Modules + +## Module `coop` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[(not(feature = \"full\"), allow(dead_code))]")` +- `Other("#[(not(feature = \"rt\"), allow(unreachable_pub))]")` + +Utilities for improved cooperative scheduling. + +### Cooperative scheduling + +A single call to [`poll`] on a top-level task may potentially do a lot of +work before it returns `Poll::Pending`. If a task runs for a long period of +time without yielding back to the executor, it can starve other tasks +waiting on that executor to execute them, or drive underlying resources. +Since Rust does not have a runtime, it is difficult to forcibly preempt a +long-running task. Instead, this module provides an opt-in mechanism for +futures to collaborate with the executor to avoid starvation. + +Consider a future like this one: + +``` +# use tokio_stream::{Stream, StreamExt}; +async fn drop_all(mut input: I) { + while let Some(_) = input.next().await {} +} +``` + +It may look harmless, but consider what happens under heavy load if the +input stream is _always_ ready. If we spawn `drop_all`, the task will never +yield, and will starve other tasks and resources on the same executor. + +To account for this, Tokio has explicit yield points in a number of library +functions, which force tasks to return to the executor periodically. + + +#### unconstrained + +If necessary, [`task::unconstrained`] lets you opt a future out of Tokio's cooperative +scheduling. When a future is wrapped with `unconstrained`, it will never be forced to yield to +Tokio. For example: + +``` +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +use tokio::{task, sync::mpsc}; + +let fut = async { + let (tx, mut rx) = mpsc::unbounded_channel(); + + for i in 0..1000 { + let _ = tx.send(()); + // This will always be ready. If coop was in effect, this code would be forced to yield + // periodically. However, if left unconstrained, then this code will never yield. + rx.recv().await; + } +}; + +task::coop::unconstrained(fut).await; +# } +``` +[`poll`]: method@std::future::Future::poll +[`task::unconstrained`]: crate::task::unconstrained() + +```rust +pub mod coop { /* ... */ } +``` + +### Types + +#### Struct `RestoreOnPending` + +**Attributes:** + +- `Other("#[(any(feature = \"fs\", feature = \"io-std\", feature = \"net\", feature =\n\"process\", feature = \"rt\", feature = \"signal\", feature = \"sync\", feature =\n\"time\",))]")` +- `MustUse { reason: None }` + +Value returned by the [`poll_proceed`] method. + +```rust +pub struct RestoreOnPending(/* private field */, /* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | +| 1 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn made_progress(self: &Self) { /* ... */ } + ``` + Signals that the task that obtained this `RestoreOnPending` was able to make + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Coop` + +**Attributes:** + +- `MustUse { reason: Some("futures do nothing unless polled") }` + +Future wrapper to ensure cooperative scheduling created by [`cooperative`]. + +```rust +pub struct Coop { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Future** + - ```rust + fn poll(self: Pin<&mut Self>, cx: &mut Context<''_>) -> Poll<::Output> { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **IntoFuture** + - ```rust + fn into_future(self: Self) -> ::IntoFuture { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Functions + +#### Function `has_budget_remaining` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[attr = Inline(Always)]")` + + Returns `true` if there is still budget left on the task. + + # Examples + + This example defines a `Timeout` future that requires a given `future` to complete before the + specified duration elapses. If it does, its result is returned; otherwise, an error is returned + and the future is canceled. + + Note that the future could exhaust the budget before we evaluate the timeout. Using `has_budget_remaining`, + we can detect this scenario and ensure the timeout is always checked. + + ``` + # use std::future::Future; + # use std::pin::{pin, Pin}; + # use std::task::{ready, Context, Poll}; + # use tokio::task::coop; + # use tokio::time::Sleep; + pub struct Timeout { + future: T, + delay: Pin>, + } + + impl Future for Timeout + where + T: Future + Unpin, + { + type Output = Result; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = Pin::into_inner(self); + let future = Pin::new(&mut this.future); + let delay = Pin::new(&mut this.delay); + + // check if the future is ready + let had_budget_before = coop::has_budget_remaining(); + if let Poll::Ready(v) = future.poll(cx) { + return Poll::Ready(Ok(v)); + } + let has_budget_now = coop::has_budget_remaining(); + + // evaluate the timeout + if let (true, false) = (had_budget_before, has_budget_now) { + // it is the underlying future that exhausted the budget + ready!(pin!(coop::unconstrained(delay)).poll(cx)); + } else { + ready!(delay.poll(cx)); + } + return Poll::Ready(Err(())); + } + } +``` + +```rust +pub fn has_budget_remaining() -> bool { /* ... */ } +``` + +#### Function `poll_proceed` + +**Attributes:** + +- `Other("#[(any(feature = \"fs\", feature = \"io-std\", feature = \"net\", feature =\n\"process\", feature = \"rt\", feature = \"signal\", feature = \"sync\", feature =\n\"time\",))]")` +- `Other("#[attr = Inline(Hint)]")` + +Decrements the task budget and returns [`Poll::Pending`] if the budget is depleted. +This indicates that the task should yield to the scheduler. Otherwise, returns +[`RestoreOnPending`] which can be used to commit the budget consumption. + +The returned [`RestoreOnPending`] will revert the budget to its former +value when dropped unless [`RestoreOnPending::made_progress`] +is called. It is the caller's responsibility to do so when it _was_ able to +make progress after the call to [`poll_proceed`]. +Restoring the budget automatically ensures the task can try to make progress in some other +way. + +Note that [`RestoreOnPending`] restores the budget **as it was before [`poll_proceed`]**. +Therefore, if the budget is _further_ adjusted between when [`poll_proceed`] returns and +[`RestoreOnPending`] is dropped, those adjustments are erased unless the caller indicates +that progress was made. + +# Examples + +This example wraps the `futures::channel::mpsc::UnboundedReceiver` to +cooperate with the Tokio scheduler. Each time a value is received, task budget +is consumed. If no budget is available, the task yields to the scheduler. + +``` +use std::pin::Pin; +use std::task::{ready, Context, Poll}; +use tokio::task::coop; +use futures::stream::{Stream, StreamExt}; +use futures::channel::mpsc::UnboundedReceiver; + +struct CoopUnboundedReceiver { + receiver: UnboundedReceiver, +} + +impl Stream for CoopUnboundedReceiver { + type Item = T; + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_> + ) -> Poll> { + let coop = ready!(coop::poll_proceed(cx)); + match self.receiver.poll_next_unpin(cx) { + Poll::Ready(v) => { + // We received a value, so consume budget. + coop.made_progress(); + Poll::Ready(v) + } + Poll::Pending => Poll::Pending, + } + } +} +``` + +```rust +pub fn poll_proceed(cx: &mut std::task::Context<''_>) -> std::task::Poll { /* ... */ } +``` + +#### Function `cooperative` + +**Attributes:** + +- `Other("#[(any(feature = \"fs\", feature = \"io-std\", feature = \"net\", feature =\n\"process\", feature = \"rt\", feature = \"signal\", feature = \"sync\", feature =\n\"time\",))]")` +- `Other("#[attr = Inline(Hint)]")` + +Creates a wrapper future that makes the inner future cooperate with the Tokio scheduler. + +When polled, the wrapper will first call [`poll_proceed`] to consume task budget, and +immediately yield if the budget has been depleted. If budget was available, the inner future +is polled. The budget consumption will be made final using [`RestoreOnPending::made_progress`] +if the inner future resolves to its final value. + +# Examples + +When you call `recv` on the `Receiver` of a [`tokio::sync::mpsc`](crate::sync::mpsc) +channel, task budget will automatically be consumed when the next value is returned. +This makes tasks that use Tokio mpsc channels automatically cooperative. + +If you're using [`futures::channel::mpsc`](https://docs.rs/futures/latest/futures/channel/mpsc/index.html) +instead, automatic task budget consumption will not happen. This example shows how can use +`cooperative` to make `futures::channel::mpsc` channels cooperate with the scheduler in the +same way Tokio channels do. + +``` +use tokio::task::coop::cooperative; +use futures::channel::mpsc::Receiver; +use futures::stream::StreamExt; + +async fn receive_next(receiver: &mut Receiver) -> Option { + // Use `StreamExt::next` to obtain a `Future` that resolves to the next value + let recv_future = receiver.next(); + // Wrap it a cooperative wrapper + let coop_future = cooperative(recv_future); + // And await + coop_future.await +} + +```rust +pub fn cooperative(fut: F) -> Coop { /* ... */ } +``` + +### Re-exports + +#### Re-export `consume_budget` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use consume_budget::consume_budget; +``` + +#### Re-export `unconstrained` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use unconstrained::unconstrained; +``` + +#### Re-export `Unconstrained` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use unconstrained::Unconstrained; +``` + +## Module `join_set` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[(tokio_unstable)]")` + +A collection of tasks spawned on a Tokio runtime. + +This module provides the [`JoinSet`] type, a collection which stores a set +of spawned tasks and allows asynchronously awaiting the output of those +tasks as they complete. See the documentation for the [`JoinSet`] type for +details. + +```rust +pub mod join_set { /* ... */ } +``` + +### Types + +#### Struct `JoinSet` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +A collection of tasks spawned on a Tokio runtime. + +A `JoinSet` can be used to await the completion of some or all of the tasks +in the set. The set is not ordered, and the tasks will be returned in the +order they complete. + +All of the tasks must have the same return type `T`. + +When the `JoinSet` is dropped, all tasks in the `JoinSet` are immediately aborted. + +# Examples + +Spawn multiple tasks and wait for them. + +``` +use tokio::task::JoinSet; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut set = JoinSet::new(); + +for i in 0..10 { + set.spawn(async move { i }); +} + +let mut seen = [false; 10]; +while let Some(res) = set.join_next().await { + let idx = res.unwrap(); + seen[idx] = true; +} + +for i in 0..10 { + assert!(seen[i]); +} +# } +``` + +# Task ID guarantees + +While a task is tracked in a `JoinSet`, that task's ID is unique relative +to all other running tasks in Tokio. For this purpose, tracking a task in a +`JoinSet` is equivalent to holding a [`JoinHandle`] to it. See the [task ID] +documentation for more info. + +[`JoinHandle`]: crate::task::JoinHandle +[task ID]: crate::task::Id + +```rust +pub struct JoinSet { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn new() -> Self { /* ... */ } + ``` + Create a new `JoinSet`. + +- ```rust + pub fn len(self: &Self) -> usize { /* ... */ } + ``` + Returns the number of tasks currently in the `JoinSet`. + +- ```rust + pub fn is_empty(self: &Self) -> bool { /* ... */ } + ``` + Returns whether the `JoinSet` is empty. + +- ```rust + pub fn build_task(self: &mut Self) -> Builder<''_, T> { /* ... */ } + ``` + Returns a [`Builder`] that can be used to configure a task prior to + +- ```rust + pub fn spawn(self: &mut Self, task: F) -> AbortHandle +where + F: Future + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the provided task on the `JoinSet`, returning an [`AbortHandle`] + +- ```rust + pub fn spawn_on(self: &mut Self, task: F, handle: &Handle) -> AbortHandle +where + F: Future + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the provided task on the provided runtime and store it in this + +- ```rust + pub fn spawn_local(self: &mut Self, task: F) -> AbortHandle +where + F: Future + ''static { /* ... */ } + ``` + Spawn the provided task on the current [`LocalSet`] or [`LocalRuntime`] + +- ```rust + pub fn spawn_local_on(self: &mut Self, task: F, local_set: &LocalSet) -> AbortHandle +where + F: Future + ''static { /* ... */ } + ``` + Spawn the provided task on the provided [`LocalSet`] and store it in + +- ```rust + pub fn spawn_blocking(self: &mut Self, f: F) -> AbortHandle +where + F: FnOnce() -> T + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the blocking code on the blocking threadpool and store + +- ```rust + pub fn spawn_blocking_on(self: &mut Self, f: F, handle: &Handle) -> AbortHandle +where + F: FnOnce() -> T + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the blocking code on the blocking threadpool of the + +- ```rust + pub async fn join_next(self: &mut Self) -> Option> { /* ... */ } + ``` + Waits until one of the tasks in the set completes and returns its output. + +- ```rust + pub async fn join_next_with_id(self: &mut Self) -> Option> { /* ... */ } + ``` + Waits until one of the tasks in the set completes and returns its + +- ```rust + pub fn try_join_next(self: &mut Self) -> Option> { /* ... */ } + ``` + Tries to join one of the tasks in the set that has completed and return its output. + +- ```rust + pub fn try_join_next_with_id(self: &mut Self) -> Option> { /* ... */ } + ``` + Tries to join one of the tasks in the set that has completed and return its output, + +- ```rust + pub async fn shutdown(self: &mut Self) { /* ... */ } + ``` + Aborts all tasks and waits for them to finish shutting down. + +- ```rust + pub async fn join_all(self: Self) -> Vec { /* ... */ } + ``` + Awaits the completion of all tasks in this `JoinSet`, returning a vector of their results. + +- ```rust + pub fn abort_all(self: &mut Self) { /* ... */ } + ``` + Aborts all tasks on this `JoinSet`. + +- ```rust + pub fn detach_all(self: &mut Self) { /* ... */ } + ``` + Removes all tasks from this `JoinSet` without aborting them. + +- ```rust + pub fn poll_join_next(self: &mut Self, cx: &mut Context<''_>) -> Poll>> { /* ... */ } + ``` + Polls for one of the tasks in the set to complete. + +- ```rust + pub fn poll_join_next_with_id(self: &mut Self, cx: &mut Context<''_>) -> Poll>> { /* ... */ } + ``` + Polls for one of the tasks in the set to complete. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Default** + - ```rust + fn default() -> Self { /* ... */ } + ``` + +- **Drop** + - ```rust + fn drop(self: &mut Self) { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **FromIterator** + - ```rust + fn from_iter>(iter: I) -> Self { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Builder` + +**Attributes:** + +- `Other("#[(all(tokio_unstable, feature = \"tracing\"))]")` +- `Other("#[(docsrs, doc(cfg(all(tokio_unstable, feature = \"tracing\"))))]")` +- `Other("#[doc(cfg(all(tokio_unstable, feature = \"tracing\")))]")` +- `MustUse { reason: Some("builders do nothing unless used to spawn a task") }` + +A variant of [`task::Builder`] that spawns tasks on a [`JoinSet`] rather +than on the current default runtime. + +[`task::Builder`]: crate::task::Builder + +```rust +pub struct Builder<''a, T> { + // Some fields omitted +} +``` + +##### Fields + +| Name | Type | Documentation | +|------|------|---------------| +| *private fields* | ... | *Some fields have been omitted* | + +##### Implementations + +###### Methods + +- ```rust + pub fn name(self: Self, name: &''a str) -> Self { /* ... */ } + ``` + Assigns a name to the task which will be spawned. + +- ```rust + pub fn spawn(self: Self, future: F) -> std::io::Result +where + F: Future + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the provided task with this builder's settings and store it in the + +- ```rust + pub fn spawn_on(self: Self, future: F, handle: &Handle) -> std::io::Result +where + F: Future + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the provided task on the provided [runtime handle] with this + +- ```rust + pub fn spawn_blocking(self: Self, f: F) -> std::io::Result +where + F: FnOnce() -> T + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the blocking code on the blocking threadpool with this builder's + +- ```rust + pub fn spawn_blocking_on(self: Self, f: F, handle: &Handle) -> std::io::Result +where + F: FnOnce() -> T + Send + ''static, + T: Send { /* ... */ } + ``` + Spawn the blocking code on the blocking threadpool of the provided + +- ```rust + pub fn spawn_local(self: Self, future: F) -> std::io::Result +where + F: Future + ''static { /* ... */ } + ``` + Spawn the provided task on the current [`LocalSet`] with this builder's + +- ```rust + pub fn spawn_local_on(self: Self, future: F, local_set: &LocalSet) -> std::io::Result +where + F: Future + ''static { /* ... */ } + ``` + Spawn the provided task on the provided [`LocalSet`] with this builder's + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +## Module `futures` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +Task-related futures. + +```rust +pub mod futures { /* ... */ } +``` + +### Re-exports + +#### Re-export `TaskLocalFuture` + +```rust +pub use super::task_local::TaskLocalFuture; +``` + +### Re-exports + +#### Re-export `JoinError` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::JoinError; +``` + +#### Re-export `JoinHandle` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::JoinHandle; +``` + +#### Re-export `spawn_blocking` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use blocking::spawn_blocking; +``` + +#### Re-export `spawn` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use spawn::spawn; +``` + +#### Re-export `block_in_place` + +**Attributes:** + +- `Other("#[(feature = \"rt-multi-thread\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt-multi-thread\")))]")` +- `Other("#[doc(cfg(feature = \"rt-multi-thread\"))]")` + +```rust +pub use blocking::block_in_place; +``` + +#### Re-export `yield_now` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use yield_now::yield_now; +``` + +#### Re-export `spawn_local` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use local::spawn_local; +``` + +#### Re-export `LocalSet` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use local::LocalSet; +``` + +#### Re-export `LocalEnterGuard` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use local::LocalEnterGuard; +``` + +#### Re-export `LocalKey` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use task_local::LocalKey; +``` + +#### Re-export `JoinSet` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use join_set::JoinSet; +``` + +#### Re-export `AbortHandle` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::AbortHandle; +``` + +#### Re-export `Id` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::Id; +``` + +#### Re-export `id` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::id; +``` + +#### Re-export `try_id` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use crate::runtime::task::try_id; +``` + +#### Re-export `Builder` + +**Attributes:** + +- `Other("#[(all(tokio_unstable, feature = \"tracing\"))]")` +- `Other("#[(docsrs, doc(cfg(all(tokio_unstable, feature = \"tracing\"))))]")` +- `Other("#[doc(cfg(all(tokio_unstable, feature = \"tracing\")))]")` + +```rust +pub use builder::Builder; +``` + +## Module `time` + +**Attributes:** + +- `Other("#[(feature = \"time\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"time\")))]")` +- `Other("#[doc(cfg(feature = \"time\"))]")` + +Utilities for tracking time. + +This module provides a number of types for executing code after a set period +of time. + +* [`Sleep`] is a future that does no work and completes at a specific [`Instant`] + in time. + +* [`Interval`] is a stream yielding a value at a fixed period. It is + initialized with a [`Duration`] and repeatedly yields each time the duration + elapses. + +* [`Timeout`]: Wraps a future or stream, setting an upper bound to the amount + of time it is allowed to execute. If the future or stream does not + complete in time, then it is canceled and an error is returned. + +These types are sufficient for handling a large number of scenarios +involving time. + +These types must be used from within the context of the [`Runtime`](crate::runtime::Runtime). + +# Examples + +Wait 100ms and print "100 ms have elapsed" + +``` +use std::time::Duration; +use tokio::time::sleep; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +sleep(Duration::from_millis(100)).await; +println!("100 ms have elapsed"); +# } +``` + +Require that an operation takes no more than 1s. + +``` +use tokio::time::{timeout, Duration}; + +async fn long_future() { + // do work here +} + +# async fn dox() { +let res = timeout(Duration::from_secs(1), long_future()).await; + +if res.is_err() { + println!("operation timed out"); +} +# } +``` + +A simple example using [`interval`] to execute a task every two seconds. + +The difference between [`interval`] and [`sleep`] is that an [`interval`] +measures the time since the last tick, which means that `.tick().await` may +wait for a shorter time than the duration specified for the interval +if some time has passed between calls to `.tick().await`. + +If the tick in the example below was replaced with [`sleep`], the task +would only be executed once every three seconds, and not every two +seconds. + +``` +use tokio::time; + +async fn task_that_takes_a_second() { + println!("hello"); + time::sleep(time::Duration::from_secs(1)).await +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut interval = time::interval(time::Duration::from_secs(2)); +for _i in 0..5 { + interval.tick().await; + task_that_takes_a_second().await; +} +# } +``` + +[`interval`]: crate::time::interval() +[`sleep`]: sleep() + +```rust +pub mod time { /* ... */ } +``` + +### Modules + +## Module `error` + +Time error types. + +```rust +pub mod error { /* ... */ } +``` + +### Types + +#### Struct `Error` + +Errors encountered by the timer implementation. + +Currently, there are two different errors that can occur: + +* `shutdown` occurs when a timer operation is attempted, but the timer + instance has been dropped. In this case, the operation will never be able + to complete and the `shutdown` error is returned. This is a permanent + error, i.e., once this error is observed, timer operations will never + succeed in the future. + +* `at_capacity` occurs when a timer operation is attempted, but the timer + instance is currently handling its maximum number of outstanding sleep instances. + In this case, the operation is not able to be performed at the current + moment, and `at_capacity` is returned. This is a transient error, i.e., at + some point in the future, if the operation is attempted again, it might + succeed. Callers that observe this error should attempt to [shed load]. One + way to do this would be dropping the future that issued the timer operation. + +[shed load]: https://en.wikipedia.org/wiki/Load_Shedding + +```rust +pub struct Error(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Methods + +- ```rust + pub fn shutdown() -> Error { /* ... */ } + ``` + Creates an error representing a shutdown timer. + +- ```rust + pub fn is_shutdown(self: &Self) -> bool { /* ... */ } + ``` + Returns `true` if the error was caused by the timer being shutdown. + +- ```rust + pub fn at_capacity() -> Error { /* ... */ } + ``` + Creates an error representing a timer at capacity. + +- ```rust + pub fn is_at_capacity(self: &Self) -> bool { /* ... */ } + ``` + Returns `true` if the error was caused by the timer being at capacity. + +- ```rust + pub fn invalid() -> Error { /* ... */ } + ``` + Creates an error representing a misconfigured timer. + +- ```rust + pub fn is_invalid(self: &Self) -> bool { /* ... */ } + ``` + Returns `true` if the error was caused by the timer being misconfigured. + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Clone** + - ```rust + fn clone(self: &Self) -> Error { /* ... */ } + ``` + +- **CloneToUninit** + - ```rust + unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ } + ``` + +- **Copy** +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Sync** +- **ToOwned** + - ```rust + fn to_owned(self: &Self) -> T { /* ... */ } + ``` + + - ```rust + fn clone_into(self: &Self, target: &mut T) { /* ... */ } + ``` + +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +#### Struct `Elapsed` + +Errors returned by `Timeout`. + +This error is returned when a timeout expires before the function was able +to finish. + +```rust +pub struct Elapsed(/* private field */); +``` + +##### Fields + +| Index | Type | Documentation | +|-------|------|---------------| +| 0 | `private` | *Private field* | + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Display** + - ```rust + fn fmt(self: &Self, fmt: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ } + ``` + +- **Eq** +- **Error** +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + + - ```rust + fn from(_err: Elapsed) -> std::io::Error { /* ... */ } + ``` + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **PartialEq** + - ```rust + fn eq(self: &Self, other: &Elapsed) -> bool { /* ... */ } + ``` + +- **RefUnwindSafe** +- **Send** +- **StructuralPartialEq** +- **Sync** +- **ToString** + - ```rust + fn to_string(self: &Self) -> String { /* ... */ } + ``` + +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +### Re-exports + +#### Re-export `advance` + +**Attributes:** + +- `Other("#[(feature = \"test-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"test-util\")))]")` +- `Other("#[doc(cfg(feature = \"test-util\"))]")` + +```rust +pub use clock::advance; +``` + +#### Re-export `pause` + +**Attributes:** + +- `Other("#[(feature = \"test-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"test-util\")))]")` +- `Other("#[doc(cfg(feature = \"test-util\"))]")` + +```rust +pub use clock::pause; +``` + +#### Re-export `resume` + +**Attributes:** + +- `Other("#[(feature = \"test-util\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"test-util\")))]")` +- `Other("#[doc(cfg(feature = \"test-util\"))]")` + +```rust +pub use clock::resume; +``` + +#### Re-export `Instant` + +```rust +pub use self::instant::Instant; +``` + +#### Re-export `interval` + +```rust +pub use interval::interval; +``` + +#### Re-export `interval_at` + +```rust +pub use interval::interval_at; +``` + +#### Re-export `Interval` + +```rust +pub use interval::Interval; +``` + +#### Re-export `MissedTickBehavior` + +```rust +pub use interval::MissedTickBehavior; +``` + +#### Re-export `sleep` + +```rust +pub use sleep::sleep; +``` + +#### Re-export `sleep_until` + +```rust +pub use sleep::sleep_until; +``` + +#### Re-export `Sleep` + +```rust +pub use sleep::Sleep; +``` + +#### Re-export `timeout` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use timeout::timeout; +``` + +#### Re-export `timeout_at` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use timeout::timeout_at; +``` + +#### Re-export `Timeout` + +**Attributes:** + +- `Other("#[doc(inline)]")` + +```rust +pub use timeout::Timeout; +``` + +#### Re-export `Duration` + +**Attributes:** + +- `Other("#[doc(no_inline)]")` + +```rust +pub use std::time::Duration; +``` + +## Module `stream` + +Due to the `Stream` trait's inclusion in `std` landing later than Tokio's 1.0 +release, most of the Tokio stream utilities have been moved into the [`tokio-stream`] +crate. + +# Why was `Stream` not included in Tokio 1.0? + +Originally, we had planned to ship Tokio 1.0 with a stable `Stream` type +but unfortunately the [RFC] had not been merged in time for `Stream` to +reach `std` on a stable compiler in time for the 1.0 release of Tokio. For +this reason, the team has decided to move all `Stream` based utilities to +the [`tokio-stream`] crate. While this is not ideal, once `Stream` has made +it into the standard library and the `MSRV` period has passed, we will implement +stream for our different types. + +While this may seem unfortunate, not all is lost as you can get much of the +`Stream` support with `async/await` and `while let` loops. It is also possible +to create a `impl Stream` from `async fn` using the [`async-stream`] crate. + +[`tokio-stream`]: https://docs.rs/tokio-stream +[`async-stream`]: https://docs.rs/async-stream +[RFC]: https://github.com/rust-lang/rfcs/pull/2996 + +# Example + +Convert a [`sync::mpsc::Receiver`] to an `impl Stream`. + +```rust,no_run +use tokio::sync::mpsc; + +let (tx, mut rx) = mpsc::channel::(16); + +let stream = async_stream::stream! { + while let Some(item) = rx.recv().await { + yield item; + } +}; +``` + +```rust +pub mod stream { /* ... */ } +``` + +## Module `doc` + +**Attributes:** + +- `Other("#[(all(docsrs, unix))]")` + +Types which are documented locally in the Tokio crate, but does not actually +live here. + +**Note** this module is only visible on docs.rs, you cannot use it directly +in your own code. + +```rust +pub mod doc { /* ... */ } +``` + +### Modules + +## Module `os` + +**Attributes:** + +- `Other("#[(any(feature = \"net\", feature = \"fs\"))]")` + +See [`std::os`](https://doc.rust-lang.org/std/os/index.html). + +```rust +pub mod os { /* ... */ } +``` + +### Modules + +## Module `windows` + +Platform-specific extensions to `std` for Windows. + +See [`std::os::windows`](https://doc.rust-lang.org/std/os/windows/index.html). + +```rust +pub mod windows { /* ... */ } +``` + +### Modules + +## Module `io` + +Windows-specific extensions to general I/O primitives. + +See [`std::os::windows::io`](https://doc.rust-lang.org/std/os/windows/io/index.html). + +```rust +pub mod io { /* ... */ } +``` + +### Types + +#### Type Alias `RawHandle` + +See [`std::os::windows::io::RawHandle`](https://doc.rust-lang.org/std/os/windows/io/type.RawHandle.html) + +```rust +pub type RawHandle = crate::doc::NotDefinedHere; +``` + +#### Type Alias `OwnedHandle` + +See [`std::os::windows::io::OwnedHandle`](https://doc.rust-lang.org/std/os/windows/io/struct.OwnedHandle.html) + +```rust +pub type OwnedHandle = crate::doc::NotDefinedHere; +``` + +#### Type Alias `RawSocket` + +See [`std::os::windows::io::RawSocket`](https://doc.rust-lang.org/std/os/windows/io/type.RawSocket.html) + +```rust +pub type RawSocket = crate::doc::NotDefinedHere; +``` + +#### Type Alias `BorrowedHandle` + +See [`std::os::windows::io::BorrowedHandle`](https://doc.rust-lang.org/std/os/windows/io/struct.BorrowedHandle.html) + +```rust +pub type BorrowedHandle<''handle> = crate::doc::NotDefinedHere; +``` + +#### Type Alias `BorrowedSocket` + +See [`std::os::windows::io::BorrowedSocket`](https://doc.rust-lang.org/std/os/windows/io/struct.BorrowedSocket.html) + +```rust +pub type BorrowedSocket<''socket> = crate::doc::NotDefinedHere; +``` + +### Traits + +#### Trait `AsRawHandle` + +See [`std::os::windows::io::AsRawHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawHandle.html) + +```rust +pub trait AsRawHandle { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `as_raw_handle`: See [`std::os::windows::io::AsRawHandle::as_raw_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawHandle.html#tymethod.as_raw_handle) + +##### Implementations + +This trait is implemented for the following types: + +- `File` +- `Stderr` +- `Stdin` +- `Stdout` +- `NamedPipeServer` +- `NamedPipeClient` +- `ChildStdin` +- `ChildStdout` +- `ChildStderr` + +#### Trait `FromRawHandle` + +See [`std::os::windows::io::FromRawHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawHandle.html) + +```rust +pub trait FromRawHandle { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `from_raw_handle`: See [`std::os::windows::io::FromRawHandle::from_raw_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawHandle.html#tymethod.from_raw_handle) + +##### Implementations + +This trait is implemented for the following types: + +- `File` + +#### Trait `AsRawSocket` + +See [`std::os::windows::io::AsRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html) + +```rust +pub trait AsRawSocket { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `as_raw_socket`: See [`std::os::windows::io::AsRawSocket::as_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html#tymethod.as_raw_socket) + +##### Implementations + +This trait is implemented for the following types: + +- `TcpListener` +- `TcpSocket` +- `TcpStream` +- `UdpSocket` + +#### Trait `FromRawSocket` + +See [`std::os::windows::io::FromRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawSocket.html) + +```rust +pub trait FromRawSocket { + /* Associated items */ +} +``` + +> This trait is not object-safe and cannot be used in dynamic trait objects. + +##### Required Items + +###### Required Methods + +- `from_raw_socket`: See [`std::os::windows::io::FromRawSocket::from_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawSocket.html#tymethod.from_raw_socket) + +##### Implementations + +This trait is implemented for the following types: + +- `TcpSocket` + +#### Trait `IntoRawSocket` + +See [`std::os::windows::io::IntoRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.IntoRawSocket.html) + +```rust +pub trait IntoRawSocket { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `into_raw_socket`: See [`std::os::windows::io::IntoRawSocket::into_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.IntoRawSocket.html#tymethod.into_raw_socket) + +##### Implementations + +This trait is implemented for the following types: + +- `TcpSocket` + +#### Trait `AsHandle` + +See [`std::os::windows::io::AsHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsHandle.html) + +```rust +pub trait AsHandle { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `as_handle`: See [`std::os::windows::io::AsHandle::as_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsHandle.html#tymethod.as_handle) + +##### Implementations + +This trait is implemented for the following types: + +- `File` +- `Stderr` +- `Stdin` +- `Stdout` +- `NamedPipeServer` +- `NamedPipeClient` +- `ChildStdin` +- `ChildStdout` +- `ChildStderr` + +#### Trait `AsSocket` + +See [`std::os::windows::io::AsSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsSocket.html) + +```rust +pub trait AsSocket { + /* Associated items */ +} +``` + +##### Required Items + +###### Required Methods + +- `as_socket`: See [`std::os::windows::io::AsSocket::as_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsSocket.html#tymethod.as_socket) + +##### Implementations + +This trait is implemented for the following types: + +- `TcpListener` +- `TcpSocket` +- `TcpStream` +- `UdpSocket` + +### Types + +#### Enum `NotDefinedHere` + +The name of a type which is not defined here. + +This is typically used as an alias for another type, like so: + +```rust,ignore +/// See [some::other::location](https://example.com). +type DEFINED_ELSEWHERE = crate::doc::NotDefinedHere; +``` + +This type is uninhabitable like the [`never` type] to ensure that no one +will ever accidentally use it. + +[`never` type]: https://doc.rust-lang.org/std/primitive.never.html + +```rust +pub enum NotDefinedHere { +} +``` + +##### Variants + +##### Implementations + +###### Trait Implementations + +- **Any** + - ```rust + fn type_id(self: &Self) -> TypeId { /* ... */ } + ``` + +- **Borrow** + - ```rust + fn borrow(self: &Self) -> &T { /* ... */ } + ``` + +- **BorrowMut** + - ```rust + fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ } + ``` + +- **Debug** + - ```rust + fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ } + ``` + +- **Freeze** +- **From** + - ```rust + fn from(t: T) -> T { /* ... */ } + ``` + Returns the argument unchanged. + +- **Instrument** +- **Into** + - ```rust + fn into(self: Self) -> U { /* ... */ } + ``` + Calls `U::from(self)`. + +- **RefUnwindSafe** +- **Send** +- **Source** + - ```rust + fn register(self: &mut Self, _registry: &mio::Registry, _token: mio::Token, _interests: mio::Interest) -> std::io::Result<()> { /* ... */ } + ``` + + - ```rust + fn reregister(self: &mut Self, _registry: &mio::Registry, _token: mio::Token, _interests: mio::Interest) -> std::io::Result<()> { /* ... */ } + ``` + + - ```rust + fn deregister(self: &mut Self, _registry: &mio::Registry) -> std::io::Result<()> { /* ... */ } + ``` + +- **Sync** +- **TryFrom** + - ```rust + fn try_from(value: U) -> Result>::Error> { /* ... */ } + ``` + +- **TryInto** + - ```rust + fn try_into(self: Self) -> Result>::Error> { /* ... */ } + ``` + +- **Unpin** +- **UnwindSafe** +- **WithSubscriber** +## Macros + +### Macro `pin` + +**Attributes:** + +- `MacroExport` + +Pins a value on the stack. + +Calls to `async fn` return anonymous [`Future`] values that are `!Unpin`. +These values must be pinned before they can be polled. Calling `.await` will +handle this, but consumes the future. If it is required to call `.await` on +a `&mut _` reference, the caller is responsible for pinning the future. + +Pinning may be done by allocating with [`Box::pin`] or by using the stack +with the `pin!` macro. + +The following will **fail to compile**: + +```compile_fail +async fn my_async_fn() { + // async logic here +} + +#[tokio::main] +async fn main() { + let mut future = my_async_fn(); + (&mut future).await; +} +``` + +To make this work requires pinning: + +``` +use tokio::pin; + +async fn my_async_fn() { + // async logic here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let future = my_async_fn(); +pin!(future); + +(&mut future).await; +# } +``` + +Pinning is useful when using `select!` and stream operators that require `T: +Stream + Unpin`. + +[`Future`]: trait@std::future::Future +[`Box::pin`]: std::boxed::Box::pin + +# Usage + +The `pin!` macro takes **identifiers** as arguments. It does **not** work +with expressions. + +The following does not compile as an expression is passed to `pin!`. + +```compile_fail +async fn my_async_fn() { + // async logic here +} + +#[tokio::main] +async fn main() { + let mut future = pin!(my_async_fn()); + (&mut future).await; +} +``` + +# Examples + +Using with select: + +``` +use tokio::{pin, select}; +use tokio_stream::{self as stream, StreamExt}; + +async fn my_async_fn() { + // async logic here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut stream = stream::iter(vec![1, 2, 3, 4]); + +let future = my_async_fn(); +pin!(future); + +loop { + select! { + _ = &mut future => { + // Stop looping `future` will be polled after completion + break; + } + Some(val) = stream.next() => { + println!("got value = {}", val); + } + } +} +# } +``` + +Because assigning to a variable followed by pinning is common, there is also +a variant of the macro that supports doing both in one go. + +``` +use tokio::{pin, select}; + +async fn my_async_fn() { + // async logic here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +pin! { + let future1 = my_async_fn(); + let future2 = my_async_fn(); +} + +select! { + _ = &mut future1 => {} + _ = &mut future2 => {} +} +# } +``` + +```rust +pub macro_rules! pin { + /* macro_rules! pin { + ($($x:ident),*) => { ... }; + ($( + let $x:ident = $init:expr; + )*) => { ... }; +} */ +} +``` + +### Macro `select` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"macros\")))]")` +- `Other("#[doc(cfg(feature = \"macros\"))]")` +- `MacroExport` + +Waits on multiple concurrent branches, returning when the **first** branch +completes, cancelling the remaining branches. + +The `select!` macro must be used inside of async functions, closures, and +blocks. + +The `select!` macro accepts one or more branches with the following pattern: + +```text + = (, if )? => , +``` + +Additionally, the `select!` macro may include a single, optional `else` +branch, which evaluates if none of the other branches match their patterns: + +```text +else => +``` + +The macro aggregates all `` expressions and runs them +concurrently on the **current** task. Once the **first** expression +completes with a value that matches its ``, the `select!` macro +returns the result of evaluating the completed branch's `` +expression. + +Additionally, each branch may include an optional `if` precondition. If the +precondition returns `false`, then the branch is disabled. The provided +`` is still evaluated but the resulting future is never +polled. This capability is useful when using `select!` within a loop. + +The complete lifecycle of a `select!` expression is as follows: + +1. Evaluate all provided `` expressions. If the precondition + returns `false`, disable the branch for the remainder of the current call + to `select!`. Re-entering `select!` due to a loop clears the "disabled" + state. +2. Aggregate the ``s from each branch, including the + disabled ones. If the branch is disabled, `` is still + evaluated, but the resulting future is not polled. +3. If **all** branches are disabled: go to step 6. +4. Concurrently await on the results for all remaining ``s. +5. Once an `` returns a value, attempt to apply the value to the + provided ``. If the pattern matches, evaluate the `` and return. + If the pattern **does not** match, disable the current branch for the remainder of + the current call to `select!`. Continue from step 3. +6. Evaluate the `else` expression. If no else expression is provided, panic. + +# Runtime characteristics + +By running all async expressions on the current task, the expressions are +able to run **concurrently** but not in **parallel**. This means all +expressions are run on the same thread and if one branch blocks the thread, +all other expressions will be unable to continue. If parallelism is +required, spawn each async expression using [`tokio::spawn`] and pass the +join handle to `select!`. + +[`tokio::spawn`]: crate::spawn + +# Fairness + +By default, `select!` randomly picks a branch to check first. This provides +some level of fairness when calling `select!` in a loop with branches that +are always ready. + +This behavior can be overridden by adding `biased;` to the beginning of the +macro usage. See the examples for details. This will cause `select` to poll +the futures in the order they appear from top to bottom. There are a few +reasons you may want this: + +- The random number generation of `tokio::select!` has a non-zero CPU cost +- Your futures may interact in a way where known polling order is significant + +But there is an important caveat to this mode. It becomes your responsibility +to ensure that the polling order of your futures is fair. If for example you +are selecting between a stream and a shutdown future, and the stream has a +huge volume of messages and zero or nearly zero time between them, you should +place the shutdown future earlier in the `select!` list to ensure that it is +always polled, and will not be ignored due to the stream being constantly +ready. + +# Panics + +The `select!` macro panics if all branches are disabled **and** there is no +provided `else` branch. A branch is disabled when the provided `if` +precondition returns `false` **or** when the pattern does not match the +result of ``. + +# Cancellation safety + +When using `select!` in a loop to receive messages from multiple sources, +you should make sure that the receive call is cancellation safe to avoid +losing messages. This section goes through various common methods and +describes whether they are cancel safe. The lists in this section are not +exhaustive. + +The following methods are cancellation safe: + + * [`tokio::sync::mpsc::Receiver::recv`](crate::sync::mpsc::Receiver::recv) + * [`tokio::sync::mpsc::UnboundedReceiver::recv`](crate::sync::mpsc::UnboundedReceiver::recv) + * [`tokio::sync::broadcast::Receiver::recv`](crate::sync::broadcast::Receiver::recv) + * [`tokio::sync::watch::Receiver::changed`](crate::sync::watch::Receiver::changed) + * [`tokio::net::TcpListener::accept`](crate::net::TcpListener::accept) + * [`tokio::net::UnixListener::accept`](crate::net::UnixListener::accept) + * [`tokio::signal::unix::Signal::recv`](crate::signal::unix::Signal::recv) + * [`tokio::io::AsyncReadExt::read`](crate::io::AsyncReadExt::read) on any `AsyncRead` + * [`tokio::io::AsyncReadExt::read_buf`](crate::io::AsyncReadExt::read_buf) on any `AsyncRead` + * [`tokio::io::AsyncWriteExt::write`](crate::io::AsyncWriteExt::write) on any `AsyncWrite` + * [`tokio::io::AsyncWriteExt::write_buf`](crate::io::AsyncWriteExt::write_buf) on any `AsyncWrite` + * [`tokio_stream::StreamExt::next`](https://docs.rs/tokio-stream/0.1/tokio_stream/trait.StreamExt.html#method.next) on any `Stream` + * [`futures::stream::StreamExt::next`](https://docs.rs/futures/0.3/futures/stream/trait.StreamExt.html#method.next) on any `Stream` + +The following methods are not cancellation safe and can lead to loss of data: + + * [`tokio::io::AsyncReadExt::read_exact`](crate::io::AsyncReadExt::read_exact) + * [`tokio::io::AsyncReadExt::read_to_end`](crate::io::AsyncReadExt::read_to_end) + * [`tokio::io::AsyncReadExt::read_to_string`](crate::io::AsyncReadExt::read_to_string) + * [`tokio::io::AsyncWriteExt::write_all`](crate::io::AsyncWriteExt::write_all) + +The following methods are not cancellation safe because they use a queue for +fairness and cancellation makes you lose your place in the queue: + + * [`tokio::sync::Mutex::lock`](crate::sync::Mutex::lock) + * [`tokio::sync::RwLock::read`](crate::sync::RwLock::read) + * [`tokio::sync::RwLock::write`](crate::sync::RwLock::write) + * [`tokio::sync::Semaphore::acquire`](crate::sync::Semaphore::acquire) + * [`tokio::sync::Notify::notified`](crate::sync::Notify::notified) + +To determine whether your own methods are cancellation safe, look for the +location of uses of `.await`. This is because when an asynchronous method is +cancelled, that always happens at an `.await`. If your function behaves +correctly even if it is restarted while waiting at an `.await`, then it is +cancellation safe. + +Cancellation safety can be defined in the following way: If you have a +future that has not yet completed, then it must be a no-op to drop that +future and recreate it. This definition is motivated by the situation where +a `select!` is used in a loop. Without this guarantee, you would lose your +progress when another branch completes and you restart the `select!` by +going around the loop. + +Be aware that cancelling something that is not cancellation safe is not +necessarily wrong. For example, if you are cancelling a task because the +application is shutting down, then you probably don't care that partially +read data is lost. + +# Examples + +Basic select with two branches. + +``` +async fn do_stuff_async() { + // async work +} + +async fn more_async_work() { + // more here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +tokio::select! { + _ = do_stuff_async() => { + println!("do_stuff_async() completed first") + } + _ = more_async_work() => { + println!("more_async_work() completed first") + } +}; +# } +``` + +Basic stream selecting. + +``` +use tokio_stream::{self as stream, StreamExt}; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut stream1 = stream::iter(vec![1, 2, 3]); +let mut stream2 = stream::iter(vec![4, 5, 6]); + +let next = tokio::select! { + v = stream1.next() => v.unwrap(), + v = stream2.next() => v.unwrap(), +}; + +assert!(next == 1 || next == 4); +# } +``` + +Collect the contents of two streams. In this example, we rely on pattern +matching and the fact that `stream::iter` is "fused", i.e. once the stream +is complete, all calls to `next()` return `None`. + +``` +use tokio_stream::{self as stream, StreamExt}; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut stream1 = stream::iter(vec![1, 2, 3]); +let mut stream2 = stream::iter(vec![4, 5, 6]); + +let mut values = vec![]; + +loop { + tokio::select! { + Some(v) = stream1.next() => values.push(v), + Some(v) = stream2.next() => values.push(v), + else => break, + } +} + +values.sort(); +assert_eq!(&[1, 2, 3, 4, 5, 6], &values[..]); +# } +``` + +Using the same future in multiple `select!` expressions can be done by passing +a reference to the future. Doing so requires the future to be [`Unpin`]. A +future can be made [`Unpin`] by either using [`Box::pin`] or stack pinning. + +[`Unpin`]: std::marker::Unpin +[`Box::pin`]: std::boxed::Box::pin + +Here, a stream is consumed for at most 1 second. + +``` +use tokio_stream::{self as stream, StreamExt}; +use tokio::time::{self, Duration}; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut stream = stream::iter(vec![1, 2, 3]); +let sleep = time::sleep(Duration::from_secs(1)); +tokio::pin!(sleep); + +loop { + tokio::select! { + maybe_v = stream.next() => { + if let Some(v) = maybe_v { + println!("got = {}", v); + } else { + break; + } + } + _ = &mut sleep => { + println!("timeout"); + break; + } + } +} +# } +``` + +Joining two values using `select!`. + +``` +use tokio::sync::oneshot; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (tx1, mut rx1) = oneshot::channel(); +let (tx2, mut rx2) = oneshot::channel(); + +tokio::spawn(async move { + tx1.send("first").unwrap(); +}); + +tokio::spawn(async move { + tx2.send("second").unwrap(); +}); + +let mut a = None; +let mut b = None; + +while a.is_none() || b.is_none() { + tokio::select! { + v1 = (&mut rx1), if a.is_none() => a = Some(v1.unwrap()), + v2 = (&mut rx2), if b.is_none() => b = Some(v2.unwrap()), + } +} + +let res = (a.unwrap(), b.unwrap()); + +assert_eq!(res.0, "first"); +assert_eq!(res.1, "second"); +# } +``` + +Using the `biased;` mode to control polling order. + +``` +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let mut count = 0u8; + +loop { + tokio::select! { + // If you run this example without `biased;`, the polling order is + // pseudo-random, and the assertions on the value of count will + // (probably) fail. + biased; + + _ = async {}, if count < 1 => { + count += 1; + assert_eq!(count, 1); + } + _ = async {}, if count < 2 => { + count += 1; + assert_eq!(count, 2); + } + _ = async {}, if count < 3 => { + count += 1; + assert_eq!(count, 3); + } + _ = async {}, if count < 4 => { + count += 1; + assert_eq!(count, 4); + } + + else => { + break; + } + }; +} +# } +``` + +## Avoid racy `if` preconditions + +Given that `if` preconditions are used to disable `select!` branches, some +caution must be used to avoid missing values. + +For example, here is **incorrect** usage of `sleep` with `if`. The objective +is to repeatedly run an asynchronous task for up to 50 milliseconds. +However, there is a potential for the `sleep` completion to be missed. + +```no_run,should_panic +use tokio::time::{self, Duration}; + +async fn some_async_work() { + // do work +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let sleep = time::sleep(Duration::from_millis(50)); +tokio::pin!(sleep); + +while !sleep.is_elapsed() { + tokio::select! { + _ = &mut sleep, if !sleep.is_elapsed() => { + println!("operation timed out"); + } + _ = some_async_work() => { + println!("operation completed"); + } + } +} + +panic!("This example shows how not to do it!"); +# } +``` + +In the above example, `sleep.is_elapsed()` may return `true` even if +`sleep.poll()` never returned `Ready`. This opens up a potential race +condition where `sleep` expires between the `while !sleep.is_elapsed()` +check and the call to `select!` resulting in the `some_async_work()` call to +run uninterrupted despite the sleep having elapsed. + +One way to write the above example without the race would be: + +``` +use tokio::time::{self, Duration}; + +async fn some_async_work() { +# time::sleep(Duration::from_millis(10)).await; + // do work +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let sleep = time::sleep(Duration::from_millis(50)); +tokio::pin!(sleep); + +loop { + tokio::select! { + _ = &mut sleep => { + println!("operation timed out"); + break; + } + _ = some_async_work() => { + println!("operation completed"); + } + } +} +# } +``` +# Alternatives from the Ecosystem + +The `select!` macro is a powerful tool for managing multiple asynchronous +branches, enabling tasks to run concurrently within the same thread. However, +its use can introduce challenges, particularly around cancellation safety, which +can lead to subtle and hard-to-debug errors. For many use cases, ecosystem +alternatives may be preferable as they mitigate these concerns by offering +clearer syntax, more predictable control flow, and reducing the need to manually +handle issues like fuse semantics or cancellation safety. + +## Merging Streams + +For cases where `loop { select! { ... } }` is used to poll multiple tasks, +stream merging offers a concise alternative, inherently handle cancellation-safe +processing, removing the risk of data loss. Libraries such as [`tokio_stream`], +[`futures::stream`] and [`futures_concurrency`] provide tools for merging +streams and handling their outputs sequentially. + +[`tokio_stream`]: https://docs.rs/tokio-stream/latest/tokio_stream/ +[`futures::stream`]: https://docs.rs/futures/latest/futures/stream/ +[`futures_concurrency`]: https://docs.rs/futures-concurrency/latest/futures_concurrency/ + +### Example with `select!` + +``` +struct File; +struct Channel; +struct Socket; + +impl Socket { + async fn read_packet(&mut self) -> Vec { + vec![] + } +} + +async fn read_send(_file: &mut File, _channel: &mut Channel) { + // do work that is not cancel safe +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +// open our IO types +let mut file = File; +let mut channel = Channel; +let mut socket = Socket; + +loop { + tokio::select! { + _ = read_send(&mut file, &mut channel) => { /* ... */ }, + _data = socket.read_packet() => { /* ... */ } + _ = futures::future::ready(()) => break + } +} +# } +``` + +### Moving to `merge` + +By using merge, you can unify multiple asynchronous tasks into a single stream, +eliminating the need to manage tasks manually and reducing the risk of +unintended behavior like data loss. + +``` +use std::pin::pin; + +use futures::stream::unfold; +use tokio_stream::StreamExt; + +struct File; +struct Channel; +struct Socket; + +impl Socket { + async fn read_packet(&mut self) -> Vec { + vec![] + } +} + +async fn read_send(_file: &mut File, _channel: &mut Channel) { + // do work that is not cancel safe +} + +enum Message { + Stop, + Sent, + Data(Vec), +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +// open our IO types +let file = File; +let channel = Channel; +let socket = Socket; + +let a = unfold((file, channel), |(mut file, mut channel)| async { + read_send(&mut file, &mut channel).await; + Some((Message::Sent, (file, channel))) +}); +let b = unfold(socket, |mut socket| async { + let data = socket.read_packet().await; + Some((Message::Data(data), socket)) +}); +let c = tokio_stream::iter([Message::Stop]); + +let mut s = pin!(a.merge(b).merge(c)); +while let Some(msg) = s.next().await { + match msg { + Message::Data(_data) => { /* ... */ } + Message::Sent => continue, + Message::Stop => break, + } +} +# } +``` + +## Racing Futures + +If you need to wait for the first completion among several asynchronous tasks, +ecosystem utilities such as +[`futures`](https://docs.rs/futures/latest/futures/), +[`futures-lite`](https://docs.rs/futures-lite/latest/futures_lite/) or +[`futures-concurrency`](https://docs.rs/futures-concurrency/latest/futures_concurrency/) +provide streamlined syntax for racing futures: + +- [`futures_concurrency::future::Race`](https://docs.rs/futures-concurrency/latest/futures_concurrency/future/trait.Race.html) +- [`futures::select`](https://docs.rs/futures/latest/futures/macro.select.html) +- [`futures::stream::select_all`](https://docs.rs/futures/latest/futures/stream/select_all/index.html) (for streams) +- [`futures_lite::future::or`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.or.html) +- [`futures_lite::future::race`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.race.html) + +``` +use futures_concurrency::future::Race; + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let task_a = async { Ok("ok") }; +let task_b = async { Err("error") }; +let result = (task_a, task_b).race().await; + +match result { + Ok(output) => println!("First task completed with: {output}"), + Err(err) => eprintln!("Error occurred: {err}"), +} +# } +``` + +```rust +pub macro_rules! select { + /* macro_rules! select { + { + $( + biased; + )? + $( + $bind:pat = $fut:expr $(, if $cond:expr)? => $handler:expr, + )* + $( + else => $els:expr $(,)? + )? + } => { ... }; +} */ +} +``` + +### Macro `join` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"macros\")))]")` +- `Other("#[doc(cfg(feature = \"macros\"))]")` +- `MacroExport` + +Waits on multiple concurrent branches, returning when **all** branches +complete. + +The `join!` macro must be used inside of async functions, closures, and +blocks. + +The `join!` macro takes a list of async expressions and evaluates them +concurrently on the same task. Each async expression evaluates to a future +and the futures from each expression are multiplexed on the current task. + +When working with async expressions returning `Result`, `join!` will wait +for **all** branches complete regardless if any complete with `Err`. Use +[`try_join!`] to return early when `Err` is encountered. + +[`try_join!`]: crate::try_join + +# Notes + +The supplied futures are stored inline and do not require allocating a +`Vec`. + +## Runtime characteristics + +By running all async expressions on the current task, the expressions are +able to run **concurrently** but not in **parallel**. This means all +expressions are run on the same thread and if one branch blocks the thread, +all other expressions will be unable to continue. If parallelism is +required, spawn each async expression using [`tokio::spawn`] and pass the +join handle to `join!`. + +[`tokio::spawn`]: crate::spawn + +## Fairness + +By default, `join!`'s generated future rotates which contained +future is polled first whenever it is woken. + +This behavior can be overridden by adding `biased;` to the beginning of the +macro usage. See the examples for details. This will cause `join` to poll +the futures in the order they appear from top to bottom. + +You may want this if your futures may interact in a way where known polling order is significant. + +But there is an important caveat to this mode. It becomes your responsibility +to ensure that the polling order of your futures is fair. If for example you +are joining a stream and a shutdown future, and the stream has a +huge volume of messages that takes a long time to finish processing per poll, you should +place the shutdown future earlier in the `join!` list to ensure that it is +always polled, and will not be delayed due to the stream future taking a long time to return +`Poll::Pending`. + +# Examples + +Basic join with two branches + +``` +async fn do_stuff_async() { + // async work +} + +async fn more_async_work() { + // more here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (first, second) = tokio::join!( + do_stuff_async(), + more_async_work()); + +// do something with the values +# } +``` + +Using the `biased;` mode to control polling order. + +``` +# #[cfg(not(target_family = "wasm"))] +# { +async fn do_stuff_async() { + // async work +} + +async fn more_async_work() { + // more here +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let (first, second) = tokio::join!( + biased; + do_stuff_async(), + more_async_work() +); + +// do something with the values +# } +# } +``` + +```rust +pub macro_rules! join { + /* macro_rules! join { + ($(biased;)? $($future:expr),*) => { ... }; +} */ +} +``` + +### Macro `try_join` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"macros\")))]")` +- `Other("#[doc(cfg(feature = \"macros\"))]")` +- `MacroExport` + +Waits on multiple concurrent branches, returning when **all** branches +complete with `Ok(_)` or on the first `Err(_)`. + +The `try_join!` macro must be used inside of async functions, closures, and +blocks. + +Similar to [`join!`], the `try_join!` macro takes a list of async +expressions and evaluates them concurrently on the same task. Each async +expression evaluates to a future and the futures from each expression are +multiplexed on the current task. The `try_join!` macro returns when **all** +branches return with `Ok` or when the **first** branch returns with `Err`. + +[`join!`]: macro@join + +# Notes + +The supplied futures are stored inline and do not require allocating a +`Vec`. + +## Runtime characteristics + +By running all async expressions on the current task, the expressions are +able to run **concurrently** but not in **parallel**. This means all +expressions are run on the same thread and if one branch blocks the thread, +all other expressions will be unable to continue. If parallelism is +required, spawn each async expression using [`tokio::spawn`] and pass the +join handle to `try_join!`. + +[`tokio::spawn`]: crate::spawn + +## Fairness + +By default, `try_join!`'s generated future rotates which +contained future is polled first whenever it is woken. + +This behavior can be overridden by adding `biased;` to the beginning of the +macro usage. See the examples for details. This will cause `try_join` to poll +the futures in the order they appear from top to bottom. + +You may want this if your futures may interact in a way where known polling order is significant. + +But there is an important caveat to this mode. It becomes your responsibility +to ensure that the polling order of your futures is fair. If for example you +are joining a stream and a shutdown future, and the stream has a +huge volume of messages that takes a long time to finish processing per poll, you should +place the shutdown future earlier in the `try_join!` list to ensure that it is +always polled, and will not be delayed due to the stream future taking a long time to return +`Poll::Pending`. + +# Examples + +Basic `try_join` with two branches. + +``` +async fn do_stuff_async() -> Result<(), &'static str> { + // async work +# Ok(()) +} + +async fn more_async_work() -> Result<(), &'static str> { + // more here +# Ok(()) +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let res = tokio::try_join!( + do_stuff_async(), + more_async_work()); + +match res { + Ok((first, second)) => { + // do something with the values + } + Err(err) => { + println!("processing failed; error = {}", err); + } +} +# } +``` + +Using `try_join!` with spawned tasks. + +``` +use tokio::task::JoinHandle; + +async fn do_stuff_async() -> Result<(), &'static str> { + // async work +# Err("failed") +} + +async fn more_async_work() -> Result<(), &'static str> { + // more here +# Ok(()) +} + +async fn flatten(handle: JoinHandle>) -> Result { + match handle.await { + Ok(Ok(result)) => Ok(result), + Ok(Err(err)) => Err(err), + Err(err) => Err("handling failed"), + } +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let handle1 = tokio::spawn(do_stuff_async()); +let handle2 = tokio::spawn(more_async_work()); +match tokio::try_join!(flatten(handle1), flatten(handle2)) { + Ok(val) => { + // do something with the values + } + Err(err) => { + println!("Failed with {}.", err); + # assert_eq!(err, "failed"); + } +} +# } +``` +Using the `biased;` mode to control polling order. + +``` +async fn do_stuff_async() -> Result<(), &'static str> { + // async work +# Ok(()) +} + +async fn more_async_work() -> Result<(), &'static str> { + // more here +# Ok(()) +} + +# #[tokio::main(flavor = "current_thread")] +# async fn main() { +let res = tokio::try_join!( + biased; + do_stuff_async(), + more_async_work() +); + +match res { + Ok((first, second)) => { + // do something with the values + } + Err(err) => { + println!("processing failed; error = {}", err); + } +} +# } +``` + +```rust +pub macro_rules! try_join { + /* macro_rules! try_join { + ($(biased;)? $($future:expr),*) => { ... }; +} */ +} +``` + +### Macro `task_local` + +**Attributes:** + +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `MacroExport` + +Declares a new task-local key of type [`tokio::task::LocalKey`]. + +# Syntax + +The macro wraps any number of static declarations and makes them local to the current task. +Publicity and attributes for each static is preserved. For example: + +# Examples + +``` +# use tokio::task_local; +task_local! { + pub static ONE: u32; + + #[allow(unused)] + static TWO: f32; +} +# fn main() {} +``` + +See [`LocalKey` documentation][`tokio::task::LocalKey`] for more +information. + +[`tokio::task::LocalKey`]: struct@crate::task::LocalKey + +```rust +pub macro_rules! task_local { + /* macro_rules! task_local { + () => { ... }; + ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty; $($rest:tt)*) => { ... }; + ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty) => { ... }; +} */ +} +``` + +## Re-exports + +### Re-export `spawn` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` + +```rust +pub use task::spawn; +``` + +### Re-export `main` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[(feature = \"rt-multi-thread\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"macros\")))]")` +- `Other("#[doc(cfg(feature = \"macros\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use tokio_macros::main; +``` + +### Re-export `test` + +**Attributes:** + +- `Other("#[(feature = \"rt\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"rt\")))]")` +- `Other("#[doc(cfg(feature = \"rt\"))]")` +- `Other("#[(feature = \"rt-multi-thread\")]")` +- `Other("#[(docsrs, doc(cfg(feature = \"macros\")))]")` +- `Other("#[doc(cfg(feature = \"macros\"))]")` +- `Other("#[doc(inline)]")` + +```rust +pub use tokio_macros::test; +``` + diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +}