[
  {
    "path": ".gitignore",
    "content": "doc\ntarget\n*.swp\nCargo.lock\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: rust\ncache: cargo\nsudo: false\naddons:\n  apt:\n    packages:\n      - libcurl4-openssl-dev\n      - libelf-dev\n      - libdw-dev\nrust:\n    - nightly\n    - beta\n    - stable\nmatrix:\n  allow_failures:\n    - rust: nightly\nbefore_script:\n  - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH\nafter_success: |\n  export RUSTFLAGS=\"$RUSTFLAGS -C link-dead-code\" &&\n  travis-cargo --only stable doc &&\n  travis-cargo --only stable doc-upload &&\n  wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz &&\n  tar xzf master.tar.gz &&\n  mv kcov-master kcov\n  cd kcov &&\n  mkdir build &&\n  cd build &&\n  cmake .. &&\n  make &&\n  cd ../.. &&\n  for file in target/debug/{utp,stream}-*; do mkdir -p \"target/cov/$(basename $file)\"; kcov/build/src/kcov --exclude-pattern=/.cargo,/usr/lib --verify \"target/cov/$(basename $file)\" \"$file\"; done &&\n  bash <(curl -s https://codecov.io/bash) &&\n  echo \"Uploaded code coverage\"\nenv:\n  global:\n    secure: cqq4PpUsrmCNLbWrmkkuf/SaCKET0+QN5w0lXmuOndBES5C+m/aR417T3Pb+7PR4gqibf47eSXgaVCQa64eZAI5PjgXrdZ7FtPRu/mgcsgcgiVrSUz5C/KSMsmp876Gl67csjCZ6SZXJ3YC0/Jh3jiJLiRt9Giqzn/s1v15j/CY=\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\n## [0.6.3]\n\n### Added\n\n- Added `peer_fn` method to UtpSocket.\n\n### Fixed\n\n- Fixed arithmetic operation overflow when calculating the delay between peers.\n- Unconnected sockets and streams no longer send fast resend requests before failing.\n\n## [0.6.2]\n\n### Fixed\n\n- Fixed Windows build.\n\n## [0.6.1]\n\n### Added\n\n- Packets are resent if no acknowledgment is received before timeout.\n- Sockets time out after too many retransmissions (configurable), returning an error.\n\n### Fixed\n\n- Socket creation no longer fails with arithmetic overflow when generating a\n  random connection identifier.\n- SACK extension generation no longer fails with arithmetic overflow.\n- Resending lost packets no longer floods the connection.\n- Fixed packet extension encoding.\n- Many protocol bug fixes.\n- Fixed warning about Sized in trait on rustc 1.4.0-nightly (10d69db0a 2015-08-23) (RFC 1214 fallout)\n\n## [0.6.0]\n\n### Added\n\n- Implemented the `Deref` trait for easy conversion from `UtpStream` instances into the underlying `UtpSocket`.\n\n### Changed\n\n- `UtpSocket::connect` is now a function instead of a method on a `UtpSocket` instance (i.e., it doesn't require a socket to be called).\n\n## [0.5.1]\n\n### Added\n\n- Added `local_addr` for both `UtpSocket` and `UtpStream`.\n\n## [0.5.0]\n\n### Added\n\n- Added `local_addr` for both `UtpSocket` and `UtpStream`.\n- Added the `Into` trait for easy conversion from `UtpSocket` instances into `UtpStream`.\n\n### Changed\n\n- `UtpListener::accept` now returns both the new socket and the remote peer's address (`Result<UtpSocket, SocketAddr>`), similarly to `TcpListener`.\n- `UtpListener::incoming` now also returns the remote peer's address, similarly to `accept` but unlike `TcpListener::incoming`.\n\n## [0.4.0]\n\n### Added\n\n- Added `UtpListener` (similar to [`TcpListener`][http://doc.rust-lang.org/std/net/struct.TcpListener.html]).\n\n## [0.3.1]\n\n### Fixed\n\n- Removed assertions about `off_target`, which were killing innocent connections.\n\n## [0.3.0]\n\n### Fixed\n\n- Fixed bug when adjusting congestion window caused by miscalculating the delay between peers.\n- Fixed bug where missing packets weren't being re-sent after sending a FIN.\n- Fixed bug where a stream wouldn't bind to an address of the appropriate family when the remote peer had an IPv6 address.\n- Fixed bug where the congestion window would only shrink when packet loss was detected and not on delay changes.\n\n### Changed\n\n- A call to `UtpStream::write` or `UtpSocket::send_to` no longer blocks until every packet is acknowledged. To force the old, slower behaviour, call `flush` after the usual calls (usually you won't need to do this, as the socket/stream is flushed on close/drop).\n\n## [0.2.8]\n\n### Fixed\n\n- Fixed bug where extensions could be skipped when parsing a packet.\n- Improved reliability of packet parsing.\n\n## [0.2.7]\n\n### Fixed\n\n- Fixed compilation errors in 1.0.0-beta.2\n\n### Changed\n\n- Improved resilience to errors --- receiving an invalid packet no longer leads to a panic\n- Sockets with established connections refuse new connections\n\n## [0.2.6]\n\nNo functional changes.\n\n### Changed\n\n- Removed stability attributes.\n- Removed an unnecessary partial clone when handling a received packet.\n\n## [0.2.5]\n\n### Changed\n\n- Dropping an `UtpSocket` (or a wrapping struct like `UtpStream`) properly closes open connections.\n\n## [0.2.4]\n\nImproved performance encoding and decoding packets.\n\n## [0.2.3]\n\n### Fixed\n- Now the crate builds in both the latest nightly and 1.0.0-beta.\n\n## [0.2.2]\n\nNo functional changes, mostly just changes to conform to changes in the Rust API.\n\n## [0.2.1]\n\n### Changed\n- Updated the `rand` dependency because the previous one didn't build on the latest Rust nightly.\n\n### Fixed\n- Some `UtpStream` tests were failing because of improperly sized buffers.\n\n## [0.2.0]\n\nThis release is now compatible with the 2015-03-28 nightly of the Rust compiler.\nSome things changed during the migration to the new `std::net` API and performance is now much lower. It might take me a while to come up with performance improvements and a replacement for the lost `set_timeout` method in `UdpSocket`.\n\n### Changed\n- Updated example in README.\n- `UtpStream` and `UtpSocket` now accept variables implementing the `ToSocketAddrs` trait, like `UdpSocket` in the standard library.\n- Reading from a socket now returns `Result<(usize, SocketAddr)>`.\n- Reading from a stream now returns `Result<usize>`.\n- Reading from a closed socket/stream now returns `Ok((0, remote_peer))`/`Ok(0)` instead of `Err(Closed)`.\n\n### Added\n- `UtpStream` now implements the `Read` and `Write` traits.\n\n### Removed\n- The `Reader` and `Writer` traits were removed, in accordance to the recent IO reform in Rust.\n- Support for connection timeouts were removed, which may impact packet loss handling in some cases.\n"
  },
  {
    "path": "COPYRIGHT",
    "content": "This project is dual-licensed under the terms of the MIT and Apache (version 2.0) licenses.\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nauthors = [\"Ricardo Martins <ricardo@scarybox.net>\"]\ndescription = \"A µTP (Micro/uTorrent Transport Library) library implemented in Rust\"\ndocumentation = \"http://meqif.github.io/rust-utp\"\nhomepage = \"https://github.com/meqif/rust-utp\"\nkeywords = [\"utp\", \"networking\", \"protocol\", \"transport\"]\nlicense = \"MIT/Apache-2.0\"\nname = \"utp\"\nreadme = \"README.md\"\nrepository = \"https://github.com/meqif/rust-utp\"\nversion = \"0.7.1-pre\"\nedition = \"2018\"\n\n[badges]\nmaintenance = { status = \"experimental\" }\n\n[dependencies]\nlog = \"0.4.14\"\nnum-traits = \"0.2.14\"\nrand = \"0.8.3\"\n\n[dev-dependencies]\nquickcheck = \"1.0.3\"\nenv_logger = \"0.8.3\"\n\n[lib]\nname = \"utp\"\n\n[features]\nunstable = []\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014 Ricardo Martins\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# rust-utp\n\n[![Crate Version](https://img.shields.io/crates/v/utp.svg?style=flat)](https://crates.io/crates/utp)\n[![Build Status](https://img.shields.io/travis/meqif/rust-utp.svg?style=flat)](http://travis-ci.org/meqif/rust-utp)\n[![Windows Build Status](https://ci.appveyor.com/api/projects/status/q38b38fendqat8o6?svg=true)](https://ci.appveyor.com/project/meqif/rust-utp)\n[![codecov](https://codecov.io/gh/meqif/rust-utp/branch/master/graph/badge.svg)](https://codecov.io/gh/meqif/rust-utp)\n[![Dependency Status](https://dependencyci.com/github/meqif/rust-utp/badge)](https://dependencyci.com/github/meqif/rust-utp)\n![Maintenance: experimental](https://img.shields.io/badge/maintenance-experimental-red.svg)\n\nA [Micro Transport Protocol](http://www.bittorrent.org/beps/bep_0029.html)\nlibrary implemented in Rust.\n\n[API documentation](http://meqif.github.io/rust-utp/)\n\n## Overview\n\nThe Micro Transport Protocol is a reliable transport protocol built over\nUDP. Its congestion control algorithm is\n[LEDBAT](http://tools.ietf.org/html/rfc6817), which tries to use as much unused\nbandwidth as it can but readily yields to competing flows, making it useful for\nbulk transfers without introducing congestion in the network.\n\nThe current implementation is somewhat incomplete, lacking a complete implementation of congestion\ncontrol. However, it does support packet loss detection (except by timeout) the\nSelective Acknowledgment extension, handles unordered and duplicate packets and\npresents a stream interface (`UtpStream`).\n\n## Usage\n\nTo use `utp`, add this to your `Cargo.toml`:\n\n```toml\n[dependencies]\nutp = \"*\"\n```\n\nThen, import it in your crate root or wherever you need it:\n\n```rust\nextern crate utp;\n```\n\n## Examples\n\nThe simplest example program would be:\n\n```rust\nextern crate utp;\n\nuse utp::UtpStream;\nuse std::io::Write;\n\nfn main() {\n    // Connect to an hypothetical local server running on port 8080\n    let addr = \"127.0.0.1:8080\";\n    let mut stream = UtpStream::connect(addr).expect(\"Error connecting to remote peer\");\n\n    // Send a string\n    stream.write(\"Hi there!\".as_bytes()).expect(\"Write failed\");\n\n    // Close the stream\n    stream.close().expect(\"Error closing connection\");\n}\n```\n\nCheck out the files under the \"examples\" directory for more example programs, or run them with `cargo run --example <example_name>`.\n\n## Roadmap\n\n- [x] congestion control\n- [x] proper connection closing\n    - [x] handle both RST and FIN\n    - [x] send FIN on close\n    - [x] automatically send FIN on `drop` if not already closed\n- [x] sending RST on mismatch\n- [x] setters and getters that hide header field endianness conversion\n- [x] SACK extension\n- [x] handle packet loss\n    - [x] send triple-ACK to re-request lost packet (fast resend request)\n    - [x] rewind send window and resend in reply to triple-ACK (fast resend)\n    - [x] resend packet on ACK timeout\n- [x] stream interface\n- [x] handle unordered packets\n- [x] duplicate packet handling\n- [x] listener abstraction\n- [x] incoming connections iterator\n- [x] time out connection after too many retransmissions\n- [ ] path MTU discovery\n\n## License\n\nThis library is distributed under similar terms to Rust: dual licensed under the MIT license and the Apache license (version 2.0).\n\nSee LICENSE-APACHE, LICENSE-MIT, and COPYRIGHT for details.\n"
  },
  {
    "path": "appveyor.yml",
    "content": "install:\n  - ps: Start-FileDownload 'https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.exe'\n  - rust-nightly-i686-pc-windows-gnu.exe /VERYSILENT /NORESTART /DIR=\"C:\\Program Files (x86)\\Rust\"\n  - SET PATH=%PATH%;C:\\Program Files (x86)\\Rust\\bin\n  - SET PATH=%PATH%;C:\\MinGW\\bin\n  - rustc -V\n  - cargo -V\n  - git submodule update --init --recursive\n\nbuild: false\n\ntest_script:\n  - cargo test --verbose\n"
  },
  {
    "path": "benches/socket.rs",
    "content": "#![feature(test)]\n\nextern crate test;\nextern crate utp;\n\nuse std::sync::Arc;\nuse std::thread;\nuse test::Bencher;\nuse utp::UtpSocket;\n\nmacro_rules! iotry {\n    ($e:expr) => {\n        match $e {\n            Ok(e) => e,\n            Err(e) => panic!(\"{}\", e),\n        }\n    };\n}\n\nfn next_test_port() -> u16 {\n    use std::sync::atomic::{AtomicUsize, Ordering};\n    static NEXT_OFFSET: AtomicUsize = AtomicUsize::new(0);\n    const BASE_PORT: u16 = 9600;\n    BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16\n}\n\nfn next_test_ip4<'a>() -> (&'a str, u16) {\n    (\"127.0.0.1\", next_test_port())\n}\n\n#[bench]\nfn bench_connection_setup_and_teardown(b: &mut Bencher) {\n    let server_addr = next_test_ip4();\n    let mut buf = [0; 1500];\n\n    b.iter(|| {\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.close());\n        });\n\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok(_) => (),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        iotry!(server.close());\n    });\n}\n\n#[bench]\nfn bench_transfer_one_packet(b: &mut Bencher) {\n    let len = 1024;\n    let server_addr = next_test_ip4();\n    let mut buf = [0; 1500];\n    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();\n    let data_arc = Arc::new(data);\n\n    b.iter(|| {\n        let data = data_arc.clone();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&data[..]));\n            iotry!(client.close());\n        });\n\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok(_) => (),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        iotry!(server.close());\n    });\n    b.bytes = len as u64;\n}\n\n#[bench]\nfn bench_transfer_one_megabyte(b: &mut Bencher) {\n    let len = 1024 * 1024;\n    let server_addr = next_test_ip4();\n    let mut buf = [0; 1500];\n    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();\n    let data_arc = Arc::new(data);\n\n    b.iter(|| {\n        let data = data_arc.clone();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&data[..]));\n            iotry!(client.close());\n        });\n\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok(_) => (),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        iotry!(server.close());\n    });\n    b.bytes = len as u64;\n}\n"
  },
  {
    "path": "benches/stream.rs",
    "content": "#![feature(test)]\n\nextern crate test;\nextern crate utp;\n\nuse std::io::{Read, Write};\nuse std::sync::Arc;\nuse std::thread;\nuse test::Bencher;\nuse utp::UtpStream;\n\nmacro_rules! iotry {\n    ($e:expr) => {\n        match $e {\n            Ok(e) => e,\n            Err(e) => panic!(\"{}\", e),\n        }\n    };\n}\n\nfn next_test_port() -> u16 {\n    use std::sync::atomic::{AtomicUsize, Ordering};\n    static NEXT_OFFSET: AtomicUsize = AtomicUsize::new(0);\n    const BASE_PORT: u16 = 9600;\n    BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16\n}\n\nfn next_test_ip4<'a>() -> (&'a str, u16) {\n    (\"127.0.0.1\", next_test_port())\n}\n\n#[bench]\nfn bench_connection_setup_and_teardown(b: &mut Bencher) {\n    let server_addr = next_test_ip4();\n    let mut received = vec![];\n    b.iter(|| {\n        let mut server = iotry!(UtpStream::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpStream::connect(server_addr));\n            iotry!(client.close());\n        });\n\n        iotry!(server.read_to_end(&mut received));\n        iotry!(server.close());\n    });\n}\n\n#[bench]\nfn bench_transfer_one_packet(b: &mut Bencher) {\n    let len = 1024;\n    let server_addr = next_test_ip4();\n    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();\n    let data_arc = Arc::new(data);\n    let mut received = Vec::with_capacity(len);\n\n    b.iter(|| {\n        let data = data_arc.clone();\n        let mut server = iotry!(UtpStream::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpStream::connect(server_addr));\n            iotry!(client.write(&data[..]));\n            iotry!(client.close());\n        });\n\n        iotry!(server.read_to_end(&mut received));\n        iotry!(server.close());\n    });\n    b.bytes = len as u64;\n}\n\n#[bench]\nfn bench_transfer_one_megabyte(b: &mut Bencher) {\n    let len = 1024 * 1024;\n    let server_addr = next_test_ip4();\n    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();\n    let data_arc = Arc::new(data);\n    let mut received = Vec::with_capacity(len);\n\n    b.iter(|| {\n        let data = data_arc.clone();\n        let mut server = iotry!(UtpStream::bind(server_addr));\n\n        thread::spawn(move || {\n            let mut client = iotry!(UtpStream::connect(server_addr));\n            iotry!(client.write(&data[..]));\n            iotry!(client.close());\n        });\n\n        iotry!(server.read_to_end(&mut received));\n        iotry!(server.close());\n    });\n    b.bytes = len as u64;\n}\n"
  },
  {
    "path": "examples/echo-server.rs",
    "content": "use env_logger;\n\nuse std::thread;\nuse utp::{UtpListener, UtpSocket};\n\nfn handle_client(mut s: UtpSocket) {\n    let mut buf = [0; 1500];\n\n    // Reply to a data packet with its own payload, then end the connection\n    match s.recv_from(&mut buf) {\n        Ok((nread, src)) => {\n            println!(\"<= [{}] {:?}\", src, &buf[..nread]);\n            let _ = s.send_to(&buf[..nread]);\n        }\n        Err(e) => println!(\"{}\", e),\n    }\n}\n\nfn main() {\n    // Start logger\n    env_logger::init();\n\n    // Create a listener\n    let addr = \"127.0.0.1:8080\";\n    let listener = UtpListener::bind(addr).expect(\"Error binding listener\");\n\n    for connection in listener.incoming() {\n        // Spawn a new handler for each new connection\n        match connection {\n            Ok((socket, _src)) => {\n                thread::spawn(move || handle_client(socket));\n            }\n            _ => (),\n        }\n    }\n}\n"
  },
  {
    "path": "examples/utpcat.rs",
    "content": "//! Implementation of a simple uTP client and server.\nuse env_logger;\n\nuse std::process;\n\nfn usage() -> ! {\n    println!(\"Usage: utp [-s|-c] <address> <port>\");\n    process::exit(1);\n}\n\nfn main() {\n    use std::io::{stderr, stdin, stdout, Read, Write};\n    use utp::UtpStream;\n\n    // This example may run in either server or client mode.\n    // Using an enum tends to make the code cleaner and easier to read.\n    enum Mode {\n        Server,\n        Client,\n    }\n\n    // Start logging\n    env_logger::init();\n\n    // Fetch arguments\n    let mut args = std::env::args();\n\n    // Skip program name\n    args.next();\n\n    // Parse the mode argument\n    let mode: Mode = match args.next() {\n        Some(ref s) if s == \"-s\" => Mode::Server,\n        Some(ref s) if s == \"-c\" => Mode::Client,\n        _ => usage(),\n    };\n\n    // Parse the address argument or use a default if none is provided\n    let addr = match (args.next(), args.next()) {\n        (None, None) => \"127.0.0.1:8080\".to_owned(),\n        (Some(ip), Some(port)) => format!(\"{}:{}\", ip, port),\n        _ => usage(),\n    };\n    let addr: &str = &addr;\n\n    match mode {\n        Mode::Server => {\n            // Create a listening stream\n            let mut stream = UtpStream::bind(addr).expect(\"Error binding stream\");\n            let mut writer = stdout();\n            let _ = writeln!(&mut stderr(), \"Serving on {}\", addr);\n\n            // Create a reasonably sized buffer\n            let mut payload = vec![0; 1024 * 1024];\n\n            // Wait for a new connection and print the received data to stdout.\n            // Reading and printing chunks like this feels more interactive than trying to read\n            // everything with `read_to_end` and avoids resizing the buffer multiple times.\n            loop {\n                match stream.read(&mut payload) {\n                    Ok(0) => break,\n                    Ok(read) => writer\n                        .write(&payload[..read])\n                        .expect(\"Error writing to stdout\"),\n                    Err(e) => panic!(\"{}\", e),\n                };\n            }\n        }\n        Mode::Client => {\n            // Create a stream and try to connect to the remote address\n            let mut stream = UtpStream::connect(addr).expect(\"Error connecting to remote peer\");\n            let mut reader = stdin();\n\n            // Create a reasonably sized buffer\n            let mut payload = vec![0; 1024 * 1024];\n\n            // Read from stdin and send it to the remote server.\n            // Once again, reading and sending small chunks like this avoids having to read the\n            // entire input (which may be endless!) before starting to send, unlike what would\n            // happen if we were to use `read_to_end` on `reader`.\n            loop {\n                match reader.read(&mut payload) {\n                    Ok(0) => break,\n                    Ok(read) => stream\n                        .write(&payload[..read])\n                        .expect(\"Error writing to stream\"),\n                    Err(e) => {\n                        stream.close().expect(\"Error closing stream\");\n                        panic!(\"{:?}\", e);\n                    }\n                };\n            }\n\n            // Explicitly close the stream.\n            stream.close().expect(\"Error closing stream\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/bit_iterator.rs",
    "content": "// How many bits in a `u8`\nconst U8BITS: usize = 8;\n\n/// Lazy iterator over bits of a vector of bytes, starting with the LSB\n/// (least-significat bit) of the first element of the vector.\npub struct BitIterator<'a> {\n    object: &'a [u8],\n    next_index: usize,\n    end_index: usize,\n}\n\nimpl<'a> BitIterator<'a> {\n    /// Creates an iterator from a vector of bytes. Each byte becomes eight bits, with the least\n    /// significant bits coming first.\n    pub fn from_bytes(obj: &'a [u8]) -> BitIterator<'_> {\n        BitIterator {\n            object: obj,\n            next_index: 0,\n            end_index: obj.len() * U8BITS,\n        }\n    }\n\n    /// Returns the number of ones in the binary representation of the underlying object.\n    pub fn count_ones(&self) -> u32 {\n        self.object.iter().fold(0, |acc, bv| acc + bv.count_ones())\n    }\n}\n\nimpl<'a> Iterator for BitIterator<'a> {\n    type Item = bool;\n\n    fn next(&mut self) -> Option<bool> {\n        if self.next_index != self.end_index {\n            let (byte_index, bit_index) = (self.next_index / U8BITS, self.next_index % U8BITS);\n            let bit = self.object[byte_index] >> bit_index & 0x1;\n            self.next_index += 1;\n            Some(bit == 0x1)\n        } else {\n            None\n        }\n    }\n\n    fn size_hint(&self) -> (usize, Option<usize>) {\n        (self.end_index, Some(self.end_index))\n    }\n}\n\nimpl<'a> ExactSizeIterator for BitIterator<'a> {}\n\n#[test]\nfn test_iterator() {\n    let bytes = vec![0xCA, 0xFE];\n    let expected_bits = vec![0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1];\n\n    for (i, bit) in BitIterator::from_bytes(&bytes).enumerate() {\n        println!(\"{} == {}\", bit, expected_bits[i] == 1);\n        assert_eq!(bit, expected_bits[i] == 1);\n    }\n}\n"
  },
  {
    "path": "src/error.rs",
    "content": "use std::error::Error;\nuse std::fmt;\nuse std::io::{self, ErrorKind};\n\n#[derive(Debug)]\npub enum SocketError {\n    ConnectionClosed,\n    ConnectionReset,\n    ConnectionTimedOut,\n    InvalidAddress,\n    InvalidReply,\n    NotConnected,\n    Other(String),\n}\n\nimpl Error for SocketError {\n    fn description(&self) -> &str {\n        use self::SocketError::*;\n        match *self {\n            ConnectionClosed => \"The socket is closed\",\n            ConnectionReset => \"Connection reset by remote peer\",\n            ConnectionTimedOut => \"Connection timed out\",\n            InvalidAddress => \"Invalid address\",\n            InvalidReply => \"The remote peer sent an invalid reply\",\n            NotConnected => \"The socket is not connected\",\n            Other(ref s) => s,\n        }\n    }\n}\n\nimpl fmt::Display for SocketError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{:?}\", &self)\n    }\n}\n\nimpl From<SocketError> for io::Error {\n    fn from(error: SocketError) -> io::Error {\n        use self::SocketError::*;\n        let kind = match error {\n            ConnectionClosed | NotConnected => ErrorKind::NotConnected,\n            ConnectionReset => ErrorKind::ConnectionReset,\n            ConnectionTimedOut => ErrorKind::TimedOut,\n            InvalidAddress => ErrorKind::InvalidInput,\n            InvalidReply => ErrorKind::ConnectionRefused,\n            Other(_) => ErrorKind::Other,\n        };\n        io::Error::new(kind, error.to_string())\n    }\n}\n\n#[derive(Debug)]\npub enum ParseError {\n    InvalidExtensionLength,\n    InvalidPacketLength,\n    InvalidPacketType(u8),\n    UnsupportedVersion,\n}\n\nimpl fmt::Display for ParseError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{:?}\", &self)\n    }\n}\n\nimpl Error for ParseError {\n    fn description(&self) -> &str {\n        use self::ParseError::*;\n        match *self {\n            InvalidExtensionLength => \"Invalid extension length (must be a non-zero multiple of 4)\",\n            InvalidPacketLength => \"The packet is too small\",\n            InvalidPacketType(_) => \"Invalid packet type\",\n            UnsupportedVersion => \"Unsupported packet version\",\n        }\n    }\n}\n\nimpl From<ParseError> for io::Error {\n    fn from(error: ParseError) -> io::Error {\n        io::Error::new(ErrorKind::Other, error.to_string())\n    }\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "//! Implementation of the [Micro Transport Protocol][spec].\n//!\n//! This library provides both a socket interface (`UtpSocket`) and a stream interface\n//! (`UtpStream`).\n//! I recommend that you use `UtpStream`, as it implements the `Read` and `Write`\n//! traits we all know (and love) from `std::io`, which makes it generally easier to work with than\n//! `UtpSocket`.\n//!\n//! [spec]: http://www.bittorrent.org/beps/bep_0029.html\n//!\n//! # Installation\n//!\n//! Ensure your `Cargo.toml` contains:\n//!\n//! ```toml\n//! [dependencies]\n//! utp = \"*\"\n//! ```\n//!\n//! # Examples\n//!\n//! ```no_run\n//! extern crate utp;\n//!\n//! use utp::UtpStream;\n//! use std::io::Write;\n//!\n//! fn main() {\n//!     // Connect to an hypothetical local server running on port 8080\n//!     let addr = \"127.0.0.1:8080\";\n//!     let mut stream = UtpStream::connect(addr).expect(\"Error connecting to remote peer\");\n//!\n//!     // Send a string\n//!     stream.write(\"Hi there!\".as_bytes()).expect(\"Write failed\");\n//!\n//!     // Close the stream\n//!     stream.close().expect(\"Error closing connection\");\n//! }\n//! ```\n//!\n//! Note that you can easily convert a socket to a stream using the `Into` trait, like so:\n//!\n//! ```no_run\n//! # use utp::{UtpStream, UtpSocket};\n//! let socket = UtpSocket::bind(\"0.0.0.0:0\").expect(\"Error binding socket\");\n//! let stream: UtpStream = socket.into();\n//! ```\n\n#![deny(missing_docs)]\n// Optional features\n#![cfg_attr(feature = \"clippy\", feature(plugin))]\n#![cfg_attr(feature = \"clippy\", plugin(clippy))]\n#![cfg_attr(\n    feature = \"clippy\",\n    allow(\n        len_without_is_empty,\n        doc_markdown,\n        needless_return,\n        transmute_ptr_to_ref\n    )\n)]\n#![cfg_attr(feature = \"unstable\", feature(test))]\n\n// Public API\npub use crate::socket::UtpListener;\npub use crate::socket::UtpSocket;\npub use crate::stream::UtpStream;\n\nmod bit_iterator;\nmod error;\nmod packet;\nmod socket;\nmod stream;\nmod time;\nmod util;\n"
  },
  {
    "path": "src/packet.rs",
    "content": "#![allow(dead_code)]\n\nuse crate::bit_iterator::BitIterator;\nuse crate::error::ParseError;\nuse crate::time::{Delay, Timestamp};\nuse std::fmt;\n\npub const HEADER_SIZE: usize = 20;\n\nmacro_rules! u8_to_unsigned_be {\n    ($src:ident, $start:expr, $end:expr, $t:ty) => ({\n        (0 .. $end - $start + 1).rev().fold(0, |acc, i| acc | $src[$start+i] as $t << (i * 8))\n    })\n}\n\nmacro_rules! make_getter {\n    ($name:ident, $t:ty, $m:ident) => {\n        pub fn $name(&self) -> $t {\n            let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n            $m::from_be(header.$name)\n        }\n    };\n}\n\nmacro_rules! make_setter {\n    ($fn_name:ident, $field:ident, $t: ty) => {\n        pub fn $fn_name(&mut self, new: $t) {\n            let mut header = unsafe { &mut *(self.0.as_mut_ptr() as *mut PacketHeader) };\n            header.$field = new.to_be();\n        }\n    };\n}\n\n/// Attempt to construct `Self` through conversion.\n///\n/// Waiting for rust-lang/rust#33417 to become stable.\npub trait TryFrom<T>: Sized {\n    type Err;\n    fn try_from(_: T) -> Result<Self, Self::Err>;\n}\n\n#[derive(PartialEq, Eq, Debug)]\npub enum PacketType {\n    Data,  // packet carries a data payload\n    Fin,   // signals the end of a connection\n    State, // signals acknowledgment of a packet\n    Reset, // forcibly terminates a connection\n    Syn,   // initiates a new connection with a peer\n}\n\nimpl TryFrom<u8> for PacketType {\n    type Err = ParseError;\n    fn try_from(original: u8) -> Result<Self, Self::Err> {\n        match original {\n            0 => Ok(PacketType::Data),\n            1 => Ok(PacketType::Fin),\n            2 => Ok(PacketType::State),\n            3 => Ok(PacketType::Reset),\n            4 => Ok(PacketType::Syn),\n            n => Err(ParseError::InvalidPacketType(n)),\n        }\n    }\n}\n\nimpl From<PacketType> for u8 {\n    fn from(original: PacketType) -> u8 {\n        match original {\n            PacketType::Data => 0,\n            PacketType::Fin => 1,\n            PacketType::State => 2,\n            PacketType::Reset => 3,\n            PacketType::Syn => 4,\n        }\n    }\n}\n\n#[derive(PartialEq, Eq, Debug, Clone, Copy)]\npub enum ExtensionType {\n    None,\n    SelectiveAck,\n    Unknown(u8),\n}\n\nimpl From<u8> for ExtensionType {\n    fn from(original: u8) -> Self {\n        match original {\n            0 => ExtensionType::None,\n            1 => ExtensionType::SelectiveAck,\n            n => ExtensionType::Unknown(n),\n        }\n    }\n}\n\nimpl From<ExtensionType> for u8 {\n    fn from(original: ExtensionType) -> u8 {\n        match original {\n            ExtensionType::None => 0,\n            ExtensionType::SelectiveAck => 1,\n            ExtensionType::Unknown(n) => n,\n        }\n    }\n}\n\n#[derive(Clone)]\npub struct Extension<'a> {\n    ty: ExtensionType,\n    pub data: &'a [u8],\n}\n\nimpl<'a> Extension<'a> {\n    pub fn len(&self) -> usize {\n        self.data.len()\n    }\n\n    pub fn get_type(&self) -> ExtensionType {\n        self.ty\n    }\n\n    pub fn iter(&self) -> BitIterator<'_> {\n        BitIterator::from_bytes(self.data)\n    }\n}\n\n#[repr(C)]\nstruct PacketHeader {\n    type_ver: u8, // type: u4, ver: u4\n    extension: u8,\n    connection_id: u16,\n    // Both timestamps are in microseconds\n    timestamp: u32,\n    timestamp_difference: u32,\n    wnd_size: u32,\n    seq_nr: u16,\n    ack_nr: u16,\n}\n\nimpl PacketHeader {\n    /// Sets the type of packet to the specified type.\n    pub fn set_type(&mut self, t: PacketType) {\n        let version = 0x0F & self.type_ver;\n        self.type_ver = u8::from(t) << 4 | version;\n    }\n\n    /// Returns the packet's type.\n    pub fn get_type(&self) -> PacketType {\n        PacketType::try_from(self.type_ver >> 4).unwrap()\n    }\n\n    /// Returns the packet's version.\n    pub fn get_version(&self) -> u8 {\n        self.type_ver & 0x0F\n    }\n\n    /// Returns the type of the first extension\n    pub fn get_extension_type(&self) -> ExtensionType {\n        self.extension.into()\n    }\n}\n\nimpl AsRef<[u8]> for PacketHeader {\n    /// Returns the packet header as a slice of bytes.\n    fn as_ref(&self) -> &[u8] {\n        unsafe { &*(self as *const PacketHeader as *const [u8; HEADER_SIZE]) }\n    }\n}\n\nimpl<'a> TryFrom<&'a [u8]> for PacketHeader {\n    type Err = ParseError;\n    /// Reads a byte buffer and returns the corresponding packet header.\n    /// It assumes the fields are in network (big-endian) byte order,\n    /// preserving it.\n    fn try_from(buf: &[u8]) -> Result<Self, Self::Err> {\n        // Check length\n        if buf.len() < HEADER_SIZE {\n            return Err(ParseError::InvalidPacketLength);\n        }\n\n        // Check version\n        if buf[0] & 0x0F != 1 {\n            return Err(ParseError::UnsupportedVersion);\n        }\n\n        // Check packet type\n        if let Err(e) = PacketType::try_from(buf[0] >> 4) {\n            return Err(e);\n        }\n\n        Ok(PacketHeader {\n            type_ver: buf[0],\n            extension: buf[1],\n            connection_id: u8_to_unsigned_be!(buf, 2, 3, u16),\n            timestamp: u8_to_unsigned_be!(buf, 4, 7, u32),\n            timestamp_difference: u8_to_unsigned_be!(buf, 8, 11, u32),\n            wnd_size: u8_to_unsigned_be!(buf, 12, 15, u32),\n            seq_nr: u8_to_unsigned_be!(buf, 16, 17, u16),\n            ack_nr: u8_to_unsigned_be!(buf, 18, 19, u16),\n        })\n    }\n}\n\nimpl Default for PacketHeader {\n    fn default() -> PacketHeader {\n        PacketHeader {\n            type_ver: u8::from(PacketType::Data) << 4 | 1,\n            extension: 0,\n            connection_id: 0,\n            timestamp: 0,\n            timestamp_difference: 0,\n            wnd_size: 0,\n            seq_nr: 0,\n            ack_nr: 0,\n        }\n    }\n}\n\npub struct Packet(Vec<u8>);\n\nimpl AsRef<[u8]> for Packet {\n    fn as_ref(&self) -> &[u8] {\n        self.0.as_ref()\n    }\n}\n\nimpl Packet {\n    /// Constructs a new, empty packet.\n    pub fn new() -> Packet {\n        Packet(PacketHeader::default().as_ref().to_owned())\n    }\n\n    /// Constructs a new data packet with the given payload.\n    pub fn with_payload(payload: &[u8]) -> Packet {\n        let mut inner = Vec::with_capacity(HEADER_SIZE + payload.len());\n        let mut header = PacketHeader::default();\n        header.set_type(PacketType::Data);\n        // inner.copy_from_slice(header.as_ref());\n        // inner.copy_from_slice(payload);\n        inner.extend_from_slice(header.as_ref());\n        inner.extend_from_slice(payload);\n\n        Packet(inner)\n    }\n\n    #[inline]\n    pub fn set_type(&mut self, t: PacketType) {\n        let header = unsafe { &mut *(self.0.as_mut_ptr() as *mut PacketHeader) };\n        header.set_type(t);\n    }\n\n    #[inline]\n    pub fn get_type(&self) -> PacketType {\n        let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n        header.get_type()\n    }\n\n    pub fn get_version(&self) -> u8 {\n        let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n        header.get_version()\n    }\n\n    pub fn get_extension_type(&self) -> ExtensionType {\n        let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n        header.get_extension_type()\n    }\n\n    pub fn extensions(&self) -> ExtensionIterator<'_> {\n        ExtensionIterator::new(self)\n    }\n\n    pub fn payload(&self) -> &[u8] {\n        let mut index = HEADER_SIZE;\n        let mut extension_type = ExtensionType::from(self.0[1]);\n\n        // Consume known extensions and skip over unknown ones\n        while index < self.0.len() && extension_type != ExtensionType::None {\n            let len = self.0[index + 1] as usize;\n\n            // Assume extension is valid because the bytes come from a (valid) Packet\n            // ...\n\n            extension_type = ExtensionType::from(self.0[index]);\n            index += len + 2;\n        }\n\n        &self.0[index..]\n    }\n\n    pub fn timestamp(&self) -> Timestamp {\n        let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n        u32::from_be(header.timestamp).into()\n    }\n\n    pub fn set_timestamp(&mut self, timestamp: Timestamp) {\n        let header = unsafe { &mut *(self.0.as_mut_ptr() as *mut PacketHeader) };\n        header.timestamp = u32::from(timestamp).to_be();\n    }\n\n    pub fn timestamp_difference(&self) -> Delay {\n        let header = unsafe { &*(self.0.as_ptr() as *const PacketHeader) };\n        u32::from_be(header.timestamp_difference).into()\n    }\n\n    pub fn set_timestamp_difference(&mut self, delay: Delay) {\n        let header = unsafe { &mut *(self.0.as_mut_ptr() as *mut PacketHeader) };\n        header.timestamp_difference = u32::from(delay).to_be();\n    }\n\n    make_getter!(seq_nr, u16, u16);\n    make_getter!(ack_nr, u16, u16);\n    make_getter!(connection_id, u16, u16);\n    make_getter!(wnd_size, u32, u32);\n\n    make_setter!(set_seq_nr, seq_nr, u16);\n    make_setter!(set_ack_nr, ack_nr, u16);\n    make_setter!(set_connection_id, connection_id, u16);\n    make_setter!(set_wnd_size, wnd_size, u32);\n\n    /// Sets Selective ACK field in packet header and adds appropriate data.\n    ///\n    /// The length of the SACK extension is expressed in bytes, which\n    /// must be a multiple of 4 and at least 4.\n    pub fn set_sack(&mut self, bv: Vec<u8>) {\n        // The length of the SACK extension is expressed in bytes, which\n        // must be a multiple of 4 and at least 4.\n        assert!(bv.len() >= 4);\n        assert_eq!(bv.len() % 4, 0);\n\n        let mut index = HEADER_SIZE;\n        let mut extension_type = ExtensionType::from(self.0[1]);\n\n        // Set extension type in header if none is used, otherwise find and update the\n        // \"next extension type\" marker in the last extension before payload\n        if extension_type == ExtensionType::None {\n            self.0[1] = ExtensionType::SelectiveAck.into();\n        } else {\n            // Skip over all extensions until last, then modify its \"next extension type\" field and\n            // add the new extension after it.\n\n            // Consume known extensions and skip over unknown ones\n            while index < self.0.len() && extension_type != ExtensionType::None {\n                let len = self.0[index + 1] as usize;\n                // No validity checks needed\n                // ...\n\n                extension_type = ExtensionType::from(self.0[index]);\n\n                // Arrived at last extension\n                if extension_type == ExtensionType::None {\n                    // Mark existence of an additional extension\n                    self.0[index] = ExtensionType::SelectiveAck.into();\n                }\n                index += len + 2;\n            }\n        }\n\n        // Insert the new extension into the packet's data.\n        // The way this is currently done is potentially slower than the alternative of resizing the\n        // underlying Vec, moving the payload forward and then writing the extension in the \"new\"\n        // place before the payload.\n\n        // Set the type of the following (non-existent) extension\n        self.0.insert(index, ExtensionType::None.into());\n        // Set this extension's length\n        self.0.insert(index + 1, bv.len() as u8);\n        // Write this extension's data\n        for (i, &value) in bv.iter().enumerate() {\n            self.0.insert(index + 2 + i, value);\n        }\n    }\n\n    pub fn len(&self) -> usize {\n        self.0.len()\n    }\n}\n\nimpl<'a> TryFrom<&'a [u8]> for Packet {\n    type Err = ParseError;\n\n    /// Decodes a byte slice and construct the equivalent Packet.\n    ///\n    /// Note that this method makes no attempt to guess the payload size, saving\n    /// all except the initial 20 bytes corresponding to the header as payload.\n    /// It's the caller's responsibility to use an appropriately sized buffer.\n    fn try_from(buf: &[u8]) -> Result<Self, Self::Err> {\n        PacketHeader::try_from(buf)\n            .and(check_extensions(buf))\n            .and(Ok(Packet(buf.to_owned())))\n    }\n}\n\nimpl Clone for Packet {\n    fn clone(&self) -> Packet {\n        Packet(self.0.clone())\n    }\n}\n\nimpl fmt::Debug for Packet {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        f.debug_struct(\"Packet\")\n            .field(\"type\", &self.get_type())\n            .field(\"version\", &self.get_version())\n            .field(\"extension\", &self.get_extension_type())\n            .field(\"connection_id\", &self.connection_id())\n            .field(\"timestamp\", &self.timestamp())\n            .field(\"timestamp_difference\", &self.timestamp_difference())\n            .field(\"wnd_size\", &self.wnd_size())\n            .field(\"seq_nr\", &self.seq_nr())\n            .field(\"ack_nr\", &self.ack_nr())\n            .finish()\n    }\n}\n\npub struct ExtensionIterator<'a> {\n    raw_bytes: &'a [u8],\n    next_extension: ExtensionType,\n    index: usize,\n}\n\nimpl<'a> ExtensionIterator<'a> {\n    fn new(packet: &'a Packet) -> Self {\n        ExtensionIterator {\n            raw_bytes: packet.as_ref(),\n            next_extension: ExtensionType::from(packet.as_ref()[1]),\n            index: HEADER_SIZE,\n        }\n    }\n}\n\nimpl<'a> Iterator for ExtensionIterator<'a> {\n    type Item = Extension<'a>;\n\n    fn next(&mut self) -> Option<Self::Item> {\n        if self.next_extension == ExtensionType::None {\n            None\n        } else if self.index < self.raw_bytes.len() {\n            let len = self.raw_bytes[self.index + 1] as usize;\n            let extension_start = self.index + 2;\n            let extension_end = extension_start + len;\n\n            // Assume extension is valid because the bytes come from a (valid) Packet\n            let extension = Extension {\n                ty: self.next_extension,\n                data: &self.raw_bytes[extension_start..extension_end],\n            };\n\n            self.next_extension = self.raw_bytes[self.index].into();\n            self.index += len + 2;\n\n            Some(extension)\n        } else {\n            None\n        }\n    }\n}\n\n/// Validate correctness of packet extensions, if any, in byte slice\nfn check_extensions(data: &[u8]) -> Result<(), ParseError> {\n    if data.len() < HEADER_SIZE {\n        return Err(ParseError::InvalidPacketLength);\n    }\n\n    let mut index = HEADER_SIZE;\n    let mut extension_type = ExtensionType::from(data[1]);\n\n    if data.len() == HEADER_SIZE && extension_type != ExtensionType::None {\n        return Err(ParseError::InvalidExtensionLength);\n    }\n\n    // Consume known extensions and skip over unknown ones\n    while index < data.len() && extension_type != ExtensionType::None {\n        if data.len() < index + 2 {\n            return Err(ParseError::InvalidPacketLength);\n        }\n        let len = data[index + 1] as usize;\n        let extension_start = index + 2;\n        let extension_end = extension_start + len;\n\n        // Check validity of extension length:\n        // - non-zero,\n        // - multiple of 4,\n        // - does not exceed packet length\n        if len == 0 || len % 4 != 0 || extension_end > data.len() {\n            return Err(ParseError::InvalidExtensionLength);\n        }\n\n        extension_type = ExtensionType::from(data[index]);\n        index += len + 2;\n    }\n    // Check for pending extensions (early exit of previous loop)\n    if extension_type != ExtensionType::None {\n        return Err(ParseError::InvalidPacketLength);\n    }\n\n    Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n    use crate::packet::PacketType::{Data, State};\n    use crate::packet::*;\n    use crate::packet::{check_extensions, PacketHeader};\n    use crate::time::*;\n    use quickcheck::{QuickCheck, TestResult};\n\n    #[test]\n    fn test_packet_decode() {\n        let buf = [\n            0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a, 0x26, 0x21, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79,\n        ];\n        let packet = Packet::try_from(&buf);\n        assert!(packet.is_ok());\n        let packet = packet.unwrap();\n        assert_eq!(packet.get_version(), 1);\n        assert_eq!(packet.get_extension_type(), ExtensionType::None);\n        assert_eq!(packet.get_type(), State);\n        assert_eq!(packet.connection_id(), 16808);\n        assert_eq!(packet.timestamp(), Timestamp(2570047530));\n        assert_eq!(packet.timestamp_difference(), Delay(2672436769));\n        assert_eq!(packet.wnd_size(), 2u32.pow(20));\n        assert_eq!(packet.seq_nr(), 15090);\n        assert_eq!(packet.ack_nr(), 27769);\n        assert_eq!(packet.len(), buf.len());\n        assert!(packet.payload().is_empty());\n    }\n\n    #[test]\n    fn test_decode_packet_with_extension() {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n        ];\n        let packet = Packet::try_from(&buf);\n        assert!(packet.is_ok());\n        let packet = packet.unwrap();\n        assert_eq!(packet.get_version(), 1);\n        assert_eq!(packet.get_extension_type(), ExtensionType::SelectiveAck);\n        assert_eq!(packet.get_type(), State);\n        assert_eq!(packet.connection_id(), 16807);\n        assert_eq!(packet.timestamp(), Timestamp(0));\n        assert_eq!(packet.timestamp_difference(), Delay(0));\n        assert_eq!(packet.wnd_size(), 1500);\n        assert_eq!(packet.seq_nr(), 43859);\n        assert_eq!(packet.ack_nr(), 15093);\n        assert_eq!(packet.len(), buf.len());\n        assert!(packet.payload().is_empty());\n        let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n        assert_eq!(extensions.len(), 1);\n        assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n        assert_eq!(extensions[0].data, &[0, 0, 0, 0]);\n        assert_eq!(extensions[0].len(), extensions[0].data.len());\n        assert_eq!(extensions[0].len(), 4);\n        // Reversible\n        assert_eq!(packet.as_ref(), &buf);\n    }\n\n    #[test]\n    fn test_packet_decode_with_missing_extension() {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a, 0x26, 0x21, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79,\n        ];\n        let packet = Packet::try_from(&buf);\n        assert!(packet.is_err());\n    }\n\n    #[test]\n    fn test_packet_decode_with_malformed_extension() {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a, 0x26, 0x21, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79, 0x00, 0x04, 0x00,\n        ];\n        let packet = Packet::try_from(&buf);\n        assert!(packet.is_err());\n    }\n\n    #[test]\n    fn test_decode_packet_with_unknown_extensions() {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0xff, 0x04, 0x00, 0x00, 0x00,\n            0x00, // Imaginary extension\n            0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n        ];\n        match Packet::try_from(&buf) {\n            Ok(packet) => {\n                assert_eq!(packet.get_version(), 1);\n                assert_eq!(packet.get_extension_type(), ExtensionType::SelectiveAck);\n                assert_eq!(packet.get_type(), State);\n                assert_eq!(packet.connection_id(), 16807);\n                assert_eq!(packet.timestamp(), Timestamp(0));\n                assert_eq!(packet.timestamp_difference(), Delay(0));\n                assert_eq!(packet.wnd_size(), 1500);\n                assert_eq!(packet.seq_nr(), 43859);\n                assert_eq!(packet.ack_nr(), 15093);\n                assert!(packet.payload().is_empty());\n                // The invalid extension is discarded\n                let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n                assert_eq!(extensions.len(), 2);\n                assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n                assert_eq!(extensions[0].data, &[0, 0, 0, 0]);\n                assert_eq!(extensions[0].len(), extensions[0].data.len());\n                assert_eq!(extensions[0].len(), 4);\n            }\n            Err(ref e) => panic!(\"{}\", e),\n        }\n    }\n\n    #[test]\n    fn test_packet_set_type() {\n        let mut packet = Packet::new();\n        packet.set_type(PacketType::Syn);\n        assert_eq!(packet.get_type(), PacketType::Syn);\n        packet.set_type(PacketType::State);\n        assert_eq!(packet.get_type(), PacketType::State);\n        packet.set_type(PacketType::Fin);\n        assert_eq!(packet.get_type(), PacketType::Fin);\n        packet.set_type(PacketType::Reset);\n        assert_eq!(packet.get_type(), PacketType::Reset);\n        packet.set_type(PacketType::Data);\n        assert_eq!(packet.get_type(), PacketType::Data);\n    }\n\n    #[test]\n    fn test_packet_set_selective_acknowledgment() {\n        let mut packet = Packet::new();\n        packet.set_sack(vec![1, 2, 3, 4]);\n\n        {\n            let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n            assert_eq!(extensions.len(), 1);\n            assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n            assert_eq!(extensions[0].data, &[1, 2, 3, 4]);\n            assert_eq!(extensions[0].len(), extensions[0].data.len());\n            assert_eq!(extensions[0].len(), 4);\n        }\n\n        // Add a second sack\n        packet.set_sack(vec![5, 6, 7, 8, 9, 10, 11, 12]);\n\n        let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n        assert_eq!(extensions.len(), 2);\n        assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n        assert_eq!(extensions[0].data, &[1, 2, 3, 4]);\n        assert_eq!(extensions[0].len(), extensions[0].data.len());\n        assert_eq!(extensions[0].len(), 4);\n        assert_eq!(extensions[1].ty, ExtensionType::SelectiveAck);\n        assert_eq!(extensions[1].data, &[5, 6, 7, 8, 9, 10, 11, 12]);\n        assert_eq!(extensions[1].len(), extensions[1].data.len());\n        assert_eq!(extensions[1].len(), 8);\n    }\n\n    #[test]\n    fn test_packet_encode() {\n        let payload = b\"Hello\\n\".to_vec();\n        let timestamp = Timestamp(15270793);\n        let timestamp_diff = Delay(1707040186);\n        let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);\n        let window_size: u32 = 1048576;\n        let mut packet = Packet::with_payload(&payload[..]);\n        packet.set_type(Data);\n        packet.set_timestamp(timestamp);\n        packet.set_timestamp_difference(timestamp_diff);\n        packet.set_connection_id(connection_id);\n        packet.set_seq_nr(seq_nr);\n        packet.set_ack_nr(ack_nr);\n        packet.set_wnd_size(window_size);\n        let buf = [\n            0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89, 0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x0a,\n        ];\n\n        assert_eq!(packet.len(), buf.len());\n        assert_eq!(packet.len(), HEADER_SIZE + payload.len());\n        assert_eq!(&packet.payload(), &payload.as_slice());\n        assert_eq!(packet.get_version(), 1);\n        assert_eq!(packet.get_extension_type(), ExtensionType::None);\n        assert_eq!(packet.get_type(), Data);\n        assert_eq!(packet.connection_id(), connection_id);\n        assert_eq!(packet.seq_nr(), seq_nr);\n        assert_eq!(packet.ack_nr(), ack_nr);\n        assert_eq!(packet.wnd_size(), window_size);\n        assert_eq!(packet.timestamp(), timestamp);\n        assert_eq!(packet.timestamp_difference(), timestamp_diff);\n        assert_eq!(packet.as_ref(), buf);\n    }\n\n    #[test]\n    fn test_packet_encode_with_payload() {\n        let payload = b\"Hello\\n\".to_vec();\n        let timestamp = Timestamp(15270793);\n        let timestamp_diff = Delay(1707040186);\n        let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);\n        let window_size: u32 = 1048576;\n        let mut packet = Packet::with_payload(&payload[..]);\n        packet.set_timestamp(timestamp);\n        packet.set_timestamp_difference(timestamp_diff);\n        packet.set_connection_id(connection_id);\n        packet.set_seq_nr(seq_nr);\n        packet.set_ack_nr(ack_nr);\n        packet.set_wnd_size(window_size);\n        let buf = [\n            0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89, 0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x0a,\n        ];\n\n        assert_eq!(packet.len(), buf.len());\n        assert_eq!(packet.len(), HEADER_SIZE + payload.len());\n        assert_eq!(&packet.payload(), &payload.as_slice());\n        assert_eq!(packet.get_version(), 1);\n        assert_eq!(packet.get_type(), Data);\n        assert_eq!(packet.get_extension_type(), ExtensionType::None);\n        assert_eq!(packet.connection_id(), connection_id);\n        assert_eq!(packet.seq_nr(), seq_nr);\n        assert_eq!(packet.ack_nr(), ack_nr);\n        assert_eq!(packet.wnd_size(), window_size);\n        assert_eq!(packet.timestamp(), timestamp);\n        assert_eq!(packet.timestamp_difference(), timestamp_diff);\n        assert_eq!(packet.as_ref(), buf);\n    }\n\n    #[test]\n    fn test_reversible() {\n        let buf = [\n            0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89, 0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x0a,\n        ];\n        assert_eq!(&Packet::try_from(&buf).unwrap().as_ref(), &buf);\n    }\n\n    #[test]\n    fn test_decode_evil_sequence() {\n        let buf = [\n            0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n        ];\n        let packet = Packet::try_from(&buf);\n        assert!(packet.is_err());\n    }\n\n    #[test]\n    fn test_decode_empty_packet() {\n        let packet = Packet::try_from(&[]);\n        assert!(packet.is_err());\n    }\n\n    // Use quickcheck to simulate a malicious attacker sending malformed packets\n    #[test]\n    fn quicktest() {\n        fn run(x: Vec<u8>) -> TestResult {\n            let packet = Packet::try_from(&x);\n\n            if PacketHeader::try_from(&x)\n                .and(check_extensions(&x))\n                .is_err()\n            {\n                TestResult::from_bool(packet.is_err())\n            } else if let Ok(packet) = packet {\n                TestResult::from_bool(&packet.as_ref() == &x.as_slice())\n            } else {\n                TestResult::from_bool(false)\n            }\n        }\n        QuickCheck::new()\n            .tests(10000)\n            .quickcheck(run as fn(Vec<u8>) -> TestResult)\n    }\n\n    #[test]\n    fn extension_iterator() {\n        let buf = [\n            0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a, 0x26, 0x21, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79,\n        ];\n        let packet = Packet::try_from(&buf).unwrap();\n        assert_eq!(packet.extensions().count(), 0);\n\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,\n        ];\n        let packet = Packet::try_from(&buf).unwrap();\n        let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n        assert_eq!(extensions.len(), 1);\n        assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n        assert_eq!(extensions[0].data, &[0, 0, 0, 0]);\n        assert_eq!(extensions[0].len(), extensions[0].data.len());\n        assert_eq!(extensions[0].len(), 4);\n\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0xff, 0x04, 0x01, 0x02, 0x03,\n            0x04, // Imaginary extension\n            0x00, 0x04, 0x05, 0x06, 0x07, 0x08,\n        ];\n\n        let packet = Packet::try_from(&buf).unwrap();\n        let extensions: Vec<Extension<'_>> = packet.extensions().collect();\n        assert_eq!(extensions.len(), 2);\n        assert_eq!(extensions[0].ty, ExtensionType::SelectiveAck);\n        assert_eq!(extensions[0].data, &[1, 2, 3, 4]);\n        assert_eq!(extensions[0].len(), extensions[0].data.len());\n        assert_eq!(extensions[0].len(), 4);\n        assert_eq!(extensions[1].ty, ExtensionType::Unknown(0xff));\n        assert_eq!(extensions[1].data, &[5, 6, 7, 8]);\n        assert_eq!(extensions[1].len(), extensions[1].data.len());\n        assert_eq!(extensions[1].len(), 4);\n    }\n}\n\n#[cfg(all(feature = \"unstable\", test))]\nmod bench {\n    extern crate test;\n\n    use self::test::Bencher;\n    use packet::{Packet, TryFrom};\n\n    #[bench]\n    fn bench_decode(b: &mut Bencher) {\n        let buf = [\n            0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a, 0x26, 0x21, 0x00, 0x10,\n            0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n            0x09, 0x0a,\n        ];\n        b.iter(|| {\n            let _ = test::black_box(Packet::try_from(&buf));\n        });\n    }\n\n    #[bench]\n    fn bench_encode(b: &mut Bencher) {\n        let packet = Packet::with_payload(&[1, 2, 3, 4, 5, 6]);\n        b.iter(|| {\n            let _ = test::black_box(packet.as_ref());\n        });\n    }\n\n    #[bench]\n    fn bench_extract_payload(b: &mut Bencher) {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0xff, 0x04, 0x01, 0x02, 0x03,\n            0x04, // First extension\n            0x00, 0x04, 0x05, 0x06, 0x07, 0x08, // Second extension, followed by data\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        ];\n        let packet = Packet::try_from(&buf).unwrap();\n        b.iter(|| {\n            let _ = test::black_box(packet.payload());\n        });\n    }\n\n    #[bench]\n    fn bench_extract_extensions(b: &mut Bencher) {\n        let buf = [\n            0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5, 0xff, 0x04, 0x01, 0x02, 0x03,\n            0x04, // First extension\n            0x00, 0x04, 0x05, 0x06, 0x07, 0x08, // Second extension, followed by data\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        ];\n        let packet = Packet::try_from(&buf).unwrap();\n        b.iter(|| {\n            let _ = test::black_box(packet.extensions().count());\n        });\n    }\n}\n"
  },
  {
    "path": "src/socket.rs",
    "content": "use crate::error::SocketError;\nuse crate::packet::*;\nuse crate::time::*;\nuse crate::util::*;\nuse log::debug;\nuse std::cmp::{max, min};\nuse std::collections::VecDeque;\nuse std::io::{ErrorKind, Result};\nuse std::net::{SocketAddr, ToSocketAddrs, UdpSocket};\nuse std::time::{Duration, Instant};\n\n// For simplicity's sake, let us assume no packet will ever exceed the\n// Ethernet maximum transfer unit of 1500 bytes.\nconst BUF_SIZE: usize = 1500;\nconst GAIN: f64 = 1.0;\nconst ALLOWED_INCREASE: u32 = 1;\nconst TARGET: f64 = 100_000.0; // 100 milliseconds\nconst MSS: u32 = 1400;\nconst MIN_CWND: u32 = 2;\nconst INIT_CWND: u32 = 2;\nconst INITIAL_CONGESTION_TIMEOUT: u64 = 1000; // one second\nconst MIN_CONGESTION_TIMEOUT: u64 = 500; // 500 ms\nconst MAX_CONGESTION_TIMEOUT: u64 = 60_000; // one minute\nconst BASE_HISTORY: usize = 10; // base delays history size\nconst MAX_SYN_RETRIES: u32 = 5; // maximum connection retries\nconst MAX_RETRANSMISSION_RETRIES: u32 = 5; // maximum retransmission retries\nconst WINDOW_SIZE: u32 = 1024 * 1024; // local receive window size\n\n// Maximum time (in microseconds) to wait for incoming packets when the send window is full\nconst PRE_SEND_TIMEOUT: u32 = 500_000;\n\n// Maximum age of base delay sample (60 seconds)\nconst MAX_BASE_DELAY_AGE: Delay = Delay(60_000_000);\n\n#[derive(PartialEq, Eq, Debug, Copy, Clone)]\nenum SocketState {\n    New,\n    Connected,\n    SynSent,\n    FinSent,\n    ResetReceived,\n    Closed,\n}\n\nstruct DelayDifferenceSample {\n    received_at: Timestamp,\n    difference: Delay,\n}\n\n/// Returns the first valid address in a `ToSocketAddrs` iterator.\nfn take_address<A: ToSocketAddrs>(addr: A) -> Result<SocketAddr> {\n    addr.to_socket_addrs()\n        .and_then(|mut it| it.next().ok_or_else(|| SocketError::InvalidAddress.into()))\n}\n\n/// A structure that represents a uTP (Micro Transport Protocol) connection between a local socket\n/// and a remote socket.\n///\n/// The socket will be closed when the value is dropped (either explicitly or when it goes out of\n/// scope).\n///\n/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be\n/// changed by assigning the desired maximum retransmission retries to a socket's\n/// `max_retransmission_retries` field. Notice that the initial congestion timeout is 500 ms and\n/// doubles with each timeout.\n///\n/// # Examples\n///\n/// ```no_run\n/// use utp::UtpSocket;\n///\n/// let mut socket = UtpSocket::bind(\"127.0.0.1:1234\").expect(\"Error binding socket\");\n///\n/// let mut buf = [0; 1000];\n/// let (amt, _src) = socket.recv_from(&mut buf).expect(\"Error receiving\");\n///\n/// let mut buf = &mut buf[..amt];\n/// buf.reverse();\n/// let _ = socket.send_to(buf).expect(\"Error sending\");\n///\n/// // Close the socket. You can either call `close` on the socket,\n/// // explicitly drop it or just let it go out of scope.\n/// socket.close();\n/// ```\npub struct UtpSocket {\n    /// The wrapped UDP socket\n    socket: UdpSocket,\n\n    /// Remote peer\n    connected_to: SocketAddr,\n\n    /// Sender connection identifier\n    sender_connection_id: u16,\n\n    /// Receiver connection identifier\n    receiver_connection_id: u16,\n\n    /// Sequence number for the next packet\n    seq_nr: u16,\n\n    /// Sequence number of the latest acknowledged packet sent by the remote peer\n    ack_nr: u16,\n\n    /// Socket state\n    state: SocketState,\n\n    /// Received but not acknowledged packets\n    incoming_buffer: Vec<Packet>,\n\n    /// Sent but not yet acknowledged packets\n    send_window: Vec<Packet>,\n\n    /// Packets not yet sent\n    unsent_queue: VecDeque<Packet>,\n\n    /// How many ACKs did the socket receive for packet with sequence number equal to `ack_nr`\n    duplicate_ack_count: u32,\n\n    /// Sequence number of the latest packet the remote peer acknowledged\n    last_acked: u16,\n\n    /// Timestamp of the latest packet the remote peer acknowledged\n    last_acked_timestamp: Timestamp,\n\n    /// Sequence number of the last packet removed from the incoming buffer\n    last_dropped: u16,\n\n    /// Round-trip time to remote peer\n    rtt: i32,\n\n    /// Variance of the round-trip time to the remote peer\n    rtt_variance: i32,\n\n    /// Data from the latest packet not yet returned in `recv_from`\n    pending_data: Vec<u8>,\n\n    /// Bytes in flight\n    curr_window: u32,\n\n    /// Window size of the remote peer\n    remote_wnd_size: u32,\n\n    /// Rolling window of packet delay to remote peer\n    base_delays: VecDeque<Delay>,\n\n    /// Rolling window of the difference between sending a packet and receiving its acknowledgement\n    current_delays: Vec<DelayDifferenceSample>,\n\n    /// Difference between timestamp of the latest packet received and time of reception\n    their_delay: Delay,\n\n    /// Start of the current minute for sampling purposes\n    last_rollover: Timestamp,\n\n    /// Current congestion timeout in milliseconds\n    congestion_timeout: u64,\n\n    /// Congestion window in bytes\n    cwnd: u32,\n\n    /// Maximum retransmission retries\n    pub max_retransmission_retries: u32,\n}\n\nimpl UtpSocket {\n    /// Creates a new UTP socket from the given UDP socket and the remote peer's address.\n    ///\n    /// The connection identifier of the resulting socket is randomly generated.\n    fn from_raw_parts(s: UdpSocket, src: SocketAddr) -> UtpSocket {\n        let (receiver_id, sender_id) = generate_sequential_identifiers();\n\n        UtpSocket {\n            socket: s,\n            connected_to: src,\n            receiver_connection_id: receiver_id,\n            sender_connection_id: sender_id,\n            seq_nr: 1,\n            ack_nr: 0,\n            state: SocketState::New,\n            incoming_buffer: Vec::new(),\n            send_window: Vec::new(),\n            unsent_queue: VecDeque::new(),\n            duplicate_ack_count: 0,\n            last_acked: 0,\n            last_acked_timestamp: Timestamp::default(),\n            last_dropped: 0,\n            rtt: 0,\n            rtt_variance: 0,\n            pending_data: Vec::new(),\n            curr_window: 0,\n            remote_wnd_size: 0,\n            current_delays: Vec::new(),\n            base_delays: VecDeque::with_capacity(BASE_HISTORY),\n            their_delay: Delay::default(),\n            last_rollover: Timestamp::default(),\n            congestion_timeout: INITIAL_CONGESTION_TIMEOUT,\n            cwnd: INIT_CWND * MSS,\n            max_retransmission_retries: MAX_RETRANSMISSION_RETRIES,\n        }\n    }\n\n    /// Creates a new UTP socket from the given address.\n    ///\n    /// The address type can be any implementer of the `ToSocketAddr` trait. See its documentation\n    /// for concrete examples.\n    ///\n    /// If more than one valid address is specified, only the first will be used.\n    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpSocket> {\n        take_address(addr).and_then(|a| UdpSocket::bind(a).map(|s| UtpSocket::from_raw_parts(s, a)))\n    }\n\n    /// Returns the socket address that this socket was created from.\n    pub fn local_addr(&self) -> Result<SocketAddr> {\n        self.socket.local_addr()\n    }\n\n    /// Returns the socket address of the remote peer of this UTP connection.\n    pub fn peer_addr(&self) -> Result<SocketAddr> {\n        if self.state == SocketState::Connected || self.state == SocketState::FinSent {\n            Ok(self.connected_to)\n        } else {\n            Err(SocketError::NotConnected.into())\n        }\n    }\n\n    /// Opens a connection to a remote host by hostname or IP address.\n    ///\n    /// The address type can be any implementer of the `ToSocketAddr` trait. See its documentation\n    /// for concrete examples.\n    ///\n    /// If more than one valid address is specified, only the first will be used.\n    pub fn connect<A: ToSocketAddrs>(other: A) -> Result<UtpSocket> {\n        let addr = take_address(other)?;\n        let my_addr = match addr {\n            SocketAddr::V4(_) => \"0.0.0.0:0\",\n            SocketAddr::V6(_) => \"[::]:0\",\n        };\n        let mut socket = UtpSocket::bind(my_addr)?;\n        socket.connected_to = addr;\n\n        let mut packet = Packet::new();\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(socket.receiver_connection_id);\n        packet.set_seq_nr(socket.seq_nr);\n\n        let mut len = 0;\n        let mut buf = [0; BUF_SIZE];\n\n        let mut syn_timeout = socket.congestion_timeout;\n        for _ in 0..MAX_SYN_RETRIES {\n            packet.set_timestamp(now_microseconds());\n\n            // Send packet\n            debug!(\"Connecting to {}\", socket.connected_to);\n            socket\n                .socket\n                .send_to(packet.as_ref(), socket.connected_to)?;\n            socket.state = SocketState::SynSent;\n            debug!(\"sent {:?}\", packet);\n\n            // Validate response\n            socket\n                .socket\n                .set_read_timeout(Some(Duration::from_millis(syn_timeout)))\n                .expect(\"Error setting read timeout\");\n            match socket.socket.recv_from(&mut buf) {\n                Ok((read, src)) => {\n                    socket.connected_to = src;\n                    len = read;\n                    break;\n                }\n                Err(ref e)\n                    if (e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut) =>\n                {\n                    debug!(\"Timed out, retrying\");\n                    syn_timeout *= 2;\n                    continue;\n                }\n                Err(e) => return Err(e),\n            };\n        }\n\n        let addr = socket.connected_to;\n        let packet = Packet::try_from(&buf[..len])?;\n        debug!(\"received {:?}\", packet);\n        socket.handle_packet(&packet, addr)?;\n\n        debug!(\"connected to: {}\", socket.connected_to);\n\n        Ok(socket)\n    }\n\n    /// Gracefully closes connection to peer.\n    ///\n    /// This method allows both peers to receive all packets still in\n    /// flight.\n    pub fn close(&mut self) -> Result<()> {\n        // Nothing to do if the socket's already closed or not connected\n        if self.state == SocketState::Closed\n            || self.state == SocketState::New\n            || self.state == SocketState::SynSent\n        {\n            return Ok(());\n        }\n\n        // Flush unsent and unacknowledged packets\n        self.flush()?;\n\n        let mut packet = Packet::new();\n        packet.set_connection_id(self.sender_connection_id);\n        packet.set_seq_nr(self.seq_nr);\n        packet.set_ack_nr(self.ack_nr);\n        packet.set_timestamp(now_microseconds());\n        packet.set_type(PacketType::Fin);\n\n        // Send FIN\n        self.socket.send_to(packet.as_ref(), self.connected_to)?;\n        debug!(\"sent {:?}\", packet);\n        self.state = SocketState::FinSent;\n\n        // Receive JAKE\n        let mut buf = [0; BUF_SIZE];\n        while self.state != SocketState::Closed {\n            self.recv(&mut buf)?;\n        }\n\n        Ok(())\n    }\n\n    /// Receives data from socket.\n    ///\n    /// On success, returns the number of bytes read and the sender's address.\n    /// Returns 0 bytes read after receiving a FIN packet when the remaining\n    /// in-flight packets are consumed.\n    pub fn recv_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {\n        let read = self.flush_incoming_buffer(buf);\n\n        if read > 0 {\n            return Ok((read, self.connected_to));\n        }\n\n        // If the socket received a reset packet and all data has been flushed, then it can't\n        // receive anything else\n        if self.state == SocketState::ResetReceived {\n            return Err(SocketError::ConnectionReset.into());\n        }\n\n        loop {\n            // A closed socket with no pending data can only \"read\" 0 new bytes.\n            if self.state == SocketState::Closed {\n                return Ok((0, self.connected_to));\n            }\n\n            match self.recv(buf) {\n                Ok((0, _src)) => continue,\n                Ok(x) => return Ok(x),\n                Err(e) => return Err(e),\n            }\n        }\n    }\n\n    fn recv(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {\n        let mut b = [0; BUF_SIZE + HEADER_SIZE];\n        let start = Instant::now();\n        let (read, src);\n        let mut retries = 0;\n\n        // Try to receive a packet and handle timeouts\n        loop {\n            // Abort loop if the current try exceeds the maximum number of retransmission retries.\n            if retries >= self.max_retransmission_retries {\n                self.state = SocketState::Closed;\n                return Err(SocketError::ConnectionTimedOut.into());\n            }\n\n            let timeout = if self.state != SocketState::New {\n                debug!(\"setting read timeout of {} ms\", self.congestion_timeout);\n                Some(Duration::from_millis(self.congestion_timeout))\n            } else {\n                None\n            };\n\n            self.socket\n                .set_read_timeout(timeout)\n                .expect(\"Error setting read timeout\");\n            match self.socket.recv_from(&mut b) {\n                Ok((r, s)) => {\n                    read = r;\n                    src = s;\n                    break;\n                }\n                Err(ref e)\n                    if (e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut) =>\n                {\n                    debug!(\"recv_from timed out\");\n                    self.handle_receive_timeout()?;\n                }\n                Err(e) => return Err(e),\n            };\n\n            let elapsed = start.elapsed();\n            let elapsed_ms = elapsed.as_secs() * 1000 + elapsed.subsec_millis() as u64;\n            debug!(\"{} ms elapsed\", elapsed_ms);\n            retries += 1;\n        }\n\n        // Decode received data into a packet\n        let packet = match Packet::try_from(&b[..read]) {\n            Ok(packet) => packet,\n            Err(e) => {\n                debug!(\"{}\", e);\n                debug!(\"Ignoring invalid packet\");\n                return Ok((0, self.connected_to));\n            }\n        };\n        debug!(\"received {:?}\", packet);\n\n        // Process packet, including sending a reply if necessary\n        if let Some(mut pkt) = self.handle_packet(&packet, src)? {\n            pkt.set_wnd_size(WINDOW_SIZE);\n            self.socket.send_to(pkt.as_ref(), src)?;\n            debug!(\"sent {:?}\", pkt);\n        }\n\n        // Insert data packet into the incoming buffer if it isn't a duplicate of a previously\n        // discarded packet\n        if packet.get_type() == PacketType::Data\n            && packet.seq_nr().wrapping_sub(self.last_dropped) > 0\n        {\n            self.insert_into_buffer(packet);\n        }\n\n        // Flush incoming buffer if possible\n        let read = self.flush_incoming_buffer(buf);\n\n        Ok((read, src))\n    }\n\n    fn handle_receive_timeout(&mut self) -> Result<()> {\n        self.congestion_timeout *= 2;\n        self.cwnd = MSS;\n\n        // There are three possible cases here:\n        //\n        // - If the socket is sending and waiting for acknowledgements (the send window is\n        //   not empty), resend the first unacknowledged packet;\n        //\n        // - If the socket is not sending and it hasn't sent a FIN yet, then it's waiting\n        //   for incoming packets: send a fast resend request;\n        //\n        // - If the socket sent a FIN previously, resend it.\n        debug!(\n            \"self.send_window: {:?}\",\n            self.send_window\n                .iter()\n                .map(Packet::seq_nr)\n                .collect::<Vec<u16>>()\n        );\n\n        if self.send_window.is_empty() {\n            // The socket is trying to close, all sent packets were acknowledged, and it has\n            // already sent a FIN: resend it.\n            if self.state == SocketState::FinSent {\n                let mut packet = Packet::new();\n                packet.set_connection_id(self.sender_connection_id);\n                packet.set_seq_nr(self.seq_nr);\n                packet.set_ack_nr(self.ack_nr);\n                packet.set_timestamp(now_microseconds());\n                packet.set_type(PacketType::Fin);\n\n                // Send FIN\n                self.socket.send_to(packet.as_ref(), self.connected_to)?;\n                debug!(\"resent FIN: {:?}\", packet);\n            } else if self.state != SocketState::New {\n                // The socket is waiting for incoming packets but the remote peer is silent:\n                // send a fast resend request.\n                debug!(\"sending fast resend request\");\n                self.send_fast_resend_request();\n            }\n        } else {\n            // The socket is sending data packets but there is no reply from the remote\n            // peer: resend the first unacknowledged packet with the current timestamp.\n            let packet = &mut self.send_window[0];\n            packet.set_timestamp(now_microseconds());\n            self.socket.send_to(packet.as_ref(), self.connected_to)?;\n            debug!(\"resent {:?}\", packet);\n        }\n\n        Ok(())\n    }\n\n    fn prepare_reply(&self, original: &Packet, t: PacketType) -> Packet {\n        let mut resp = Packet::new();\n        resp.set_type(t);\n        let self_t_micro = now_microseconds();\n        let other_t_micro = original.timestamp();\n        let time_difference: Delay = abs_diff(self_t_micro, other_t_micro);\n        resp.set_timestamp(self_t_micro);\n        resp.set_timestamp_difference(time_difference);\n        resp.set_connection_id(self.sender_connection_id);\n        resp.set_seq_nr(self.seq_nr);\n        resp.set_ack_nr(self.ack_nr);\n\n        resp\n    }\n\n    /// Removes a packet in the incoming buffer and updates the current acknowledgement number.\n    fn advance_incoming_buffer(&mut self) -> Option<Packet> {\n        if !self.incoming_buffer.is_empty() {\n            let packet = self.incoming_buffer.remove(0);\n            debug!(\"Removed packet from incoming buffer: {:?}\", packet);\n            self.ack_nr = packet.seq_nr();\n            self.last_dropped = self.ack_nr;\n            Some(packet)\n        } else {\n            None\n        }\n    }\n\n    /// Discards sequential, ordered packets in incoming buffer, starting from\n    /// the most recently acknowledged to the most recent, as long as there are\n    /// no missing packets. The discarded packets' payload is written to the\n    /// slice `buf`, starting in position `start`.\n    /// Returns the last written index.\n    fn flush_incoming_buffer(&mut self, buf: &mut [u8]) -> usize {\n        fn unsafe_copy(src: &[u8], dst: &mut [u8]) -> usize {\n            let max_len = min(src.len(), dst.len());\n            unsafe {\n                use std::ptr::copy;\n                copy(src.as_ptr(), dst.as_mut_ptr(), max_len);\n            }\n            max_len\n        }\n\n        // Return pending data from a partially read packet\n        if !self.pending_data.is_empty() {\n            let flushed = unsafe_copy(&self.pending_data[..], buf);\n\n            if flushed == self.pending_data.len() {\n                self.pending_data.clear();\n                self.advance_incoming_buffer();\n            } else {\n                self.pending_data = self.pending_data[flushed..].to_vec();\n            }\n\n            return flushed;\n        }\n\n        if !self.incoming_buffer.is_empty()\n            && (self.ack_nr == self.incoming_buffer[0].seq_nr()\n                || self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())\n        {\n            let flushed = unsafe_copy(&self.incoming_buffer[0].payload(), buf);\n\n            if flushed == self.incoming_buffer[0].payload().len() {\n                self.advance_incoming_buffer();\n            } else {\n                self.pending_data = self.incoming_buffer[0].payload()[flushed..].to_vec();\n            }\n\n            return flushed;\n        }\n\n        0\n    }\n\n    /// Sends data on the socket to the remote peer. On success, returns the number of bytes\n    /// written.\n    //\n    // # Implementation details\n    //\n    // This method inserts packets into the send buffer and keeps trying to\n    // advance the send window until an ACK corresponding to the last packet is\n    // received.\n    //\n    // Note that the buffer passed to `send_to` might exceed the maximum packet\n    // size, which will result in the data being split over several packets.\n    pub fn send_to(&mut self, buf: &[u8]) -> Result<usize> {\n        if self.state == SocketState::Closed {\n            return Err(SocketError::ConnectionClosed.into());\n        }\n\n        let total_length = buf.len();\n\n        for chunk in buf.chunks(MSS as usize - HEADER_SIZE) {\n            let mut packet = Packet::with_payload(chunk);\n            packet.set_seq_nr(self.seq_nr);\n            packet.set_ack_nr(self.ack_nr);\n            packet.set_connection_id(self.sender_connection_id);\n\n            self.unsent_queue.push_back(packet);\n\n            // Intentionally wrap around sequence number\n            self.seq_nr = self.seq_nr.wrapping_add(1);\n        }\n\n        // Send every packet in the queue\n        self.send()?;\n\n        Ok(total_length)\n    }\n\n    /// Consumes acknowledgements for every pending packet.\n    pub fn flush(&mut self) -> Result<()> {\n        let mut buf = [0u8; BUF_SIZE];\n        while !self.send_window.is_empty() {\n            debug!(\"packets in send window: {}\", self.send_window.len());\n            self.recv(&mut buf)?;\n        }\n\n        Ok(())\n    }\n\n    /// Sends every packet in the unsent packet queue.\n    fn send(&mut self) -> Result<()> {\n        while let Some(mut packet) = self.unsent_queue.pop_front() {\n            self.send_packet(&mut packet)?;\n            self.curr_window += packet.len() as u32;\n            self.send_window.push(packet);\n        }\n        Ok(())\n    }\n\n    /// Send one packet.\n    #[inline]\n    fn send_packet(&mut self, packet: &mut Packet) -> Result<()> {\n        debug!(\"current window: {}\", self.send_window.len());\n        let max_inflight = min(self.cwnd, self.remote_wnd_size);\n        let max_inflight = max(MIN_CWND * MSS, max_inflight);\n        let now = now_microseconds();\n\n        // Wait until enough in-flight packets are acknowledged for rate control purposes, but don't\n        // wait more than 500 ms (PRE_SEND_TIMEOUT) before sending the packet.\n        while self.curr_window >= max_inflight && now_microseconds() - now < PRE_SEND_TIMEOUT.into()\n        {\n            debug!(\"self.curr_window: {}\", self.curr_window);\n            debug!(\"max_inflight: {}\", max_inflight);\n            debug!(\"self.duplicate_ack_count: {}\", self.duplicate_ack_count);\n            debug!(\"now_microseconds() - now = {}\", now_microseconds() - now);\n            let mut buf = [0; BUF_SIZE];\n            self.recv(&mut buf)?;\n        }\n        debug!(\n            \"out: now_microseconds() - now = {}\",\n            now_microseconds() - now\n        );\n\n        // Check if it still makes sense to send packet, as we might be trying to resend a lost\n        // packet acknowledged in the receive loop above.\n        // If there were no wrapping around of sequence numbers, we'd simply check if the packet's\n        // sequence number is greater than `last_acked`.\n        let distance_a = packet.seq_nr().wrapping_sub(self.last_acked);\n        let distance_b = self.last_acked.wrapping_sub(packet.seq_nr());\n        if distance_a > distance_b {\n            debug!(\"Packet already acknowledged, skipping...\");\n            return Ok(());\n        }\n\n        packet.set_timestamp(now_microseconds());\n        packet.set_timestamp_difference(self.their_delay);\n        self.socket.send_to(packet.as_ref(), self.connected_to)?;\n        debug!(\"sent {:?}\", packet);\n\n        Ok(())\n    }\n\n    // Insert a new sample in the base delay list.\n    //\n    // The base delay list contains at most `BASE_HISTORY` samples, each sample is the minimum\n    // measured over a period of a minute (MAX_BASE_DELAY_AGE).\n    fn update_base_delay(&mut self, base_delay: Delay, now: Timestamp) {\n        if self.base_delays.is_empty() || now - self.last_rollover > MAX_BASE_DELAY_AGE {\n            // Update last rollover\n            self.last_rollover = now;\n\n            // Drop the oldest sample, if need be\n            if self.base_delays.len() == BASE_HISTORY {\n                self.base_delays.pop_front();\n            }\n\n            // Insert new sample\n            self.base_delays.push_back(base_delay);\n        } else {\n            // Replace sample for the current minute if the delay is lower\n            let last_idx = self.base_delays.len() - 1;\n            if base_delay < self.base_delays[last_idx] {\n                self.base_delays[last_idx] = base_delay;\n            }\n        }\n    }\n\n    /// Inserts a new sample in the current delay list after removing samples older than one RTT, as\n    /// specified in RFC6817.\n    fn update_current_delay(&mut self, v: Delay, now: Timestamp) {\n        // Remove samples more than one RTT old\n        let rtt = (self.rtt as i64 * 100).into();\n        while !self.current_delays.is_empty() && now - self.current_delays[0].received_at > rtt {\n            self.current_delays.remove(0);\n        }\n\n        // Insert new measurement\n        self.current_delays.push(DelayDifferenceSample {\n            received_at: now,\n            difference: v,\n        });\n    }\n\n    fn update_congestion_timeout(&mut self, current_delay: i32) {\n        let delta = self.rtt - current_delay;\n        self.rtt_variance += (delta.abs() - self.rtt_variance) / 4;\n        self.rtt += (current_delay - self.rtt) / 8;\n        self.congestion_timeout = max(\n            (self.rtt + self.rtt_variance * 4) as u64,\n            MIN_CONGESTION_TIMEOUT,\n        );\n        self.congestion_timeout = min(self.congestion_timeout, MAX_CONGESTION_TIMEOUT);\n\n        debug!(\"current_delay: {}\", current_delay);\n        debug!(\"delta: {}\", delta);\n        debug!(\"self.rtt_variance: {}\", self.rtt_variance);\n        debug!(\"self.rtt: {}\", self.rtt);\n        debug!(\"self.congestion_timeout: {}\", self.congestion_timeout);\n    }\n\n    /// Calculates the filtered current delay in the current window.\n    ///\n    /// The current delay is calculated through application of the exponential\n    /// weighted moving average filter with smoothing factor 0.333 over the\n    /// current delays in the current window.\n    fn filtered_current_delay(&self) -> Delay {\n        let input = self.current_delays.iter().map(|delay| &delay.difference);\n        (ewma(input, 0.333) as i64).into()\n    }\n\n    /// Calculates the lowest base delay in the current window.\n    fn min_base_delay(&self) -> Delay {\n        self.base_delays.iter().min().cloned().unwrap_or_default()\n    }\n\n    /// Builds the selective acknowledgement extension data for usage in packets.\n    fn build_selective_ack(&self) -> Vec<u8> {\n        let stashed = self\n            .incoming_buffer\n            .iter()\n            .filter(|pkt| pkt.seq_nr() > self.ack_nr + 1)\n            .map(|pkt| (pkt.seq_nr() - self.ack_nr - 2) as usize)\n            .map(|diff| (diff / 8, diff % 8));\n\n        let mut sack = Vec::new();\n        for (byte, bit) in stashed {\n            // Make sure the amount of elements in the SACK vector is a\n            // multiple of 4 and enough to represent the lost packets\n            while byte >= sack.len() || sack.len() % 4 != 0 {\n                sack.push(0u8);\n            }\n\n            sack[byte] |= 1 << bit;\n        }\n\n        sack\n    }\n\n    /// Sends a fast resend request to the remote peer.\n    ///\n    /// A fast resend request consists of sending three State packets (acknowledging the last\n    /// received packet) in quick succession.\n    fn send_fast_resend_request(&self) {\n        for _ in 0..3 {\n            let mut packet = Packet::new();\n            packet.set_type(PacketType::State);\n            let self_t_micro = now_microseconds();\n            packet.set_timestamp(self_t_micro);\n            packet.set_timestamp_difference(self.their_delay);\n            packet.set_connection_id(self.sender_connection_id);\n            packet.set_seq_nr(self.seq_nr);\n            packet.set_ack_nr(self.ack_nr);\n            let _ = self.socket.send_to(packet.as_ref(), self.connected_to);\n        }\n    }\n\n    fn resend_lost_packet(&mut self, lost_packet_nr: u16) {\n        debug!(\"---> resend_lost_packet({}) <---\", lost_packet_nr);\n        match self\n            .send_window\n            .iter()\n            .position(|pkt| pkt.seq_nr() == lost_packet_nr)\n        {\n            None => debug!(\"Packet {} not found\", lost_packet_nr),\n            Some(position) => {\n                debug!(\"self.send_window.len(): {}\", self.send_window.len());\n                debug!(\"position: {}\", position);\n                let mut packet = self.send_window[position].clone();\n                // FIXME: Unchecked result\n                let _ = self.send_packet(&mut packet);\n\n                // We intentionally don't increase `curr_window` because otherwise a packet's length\n                // would be counted more than once\n            }\n        }\n        debug!(\"---> END resend_lost_packet <---\");\n    }\n\n    /// Forgets sent packets that were acknowledged by the remote peer.\n    fn advance_send_window(&mut self) {\n        // The reason I'm not removing the first element in a loop while its sequence number is\n        // smaller than `last_acked` is because of wrapping sequence numbers, which would create the\n        // sequence [..., 65534, 65535, 0, 1, ...]. If `last_acked` is smaller than the first\n        // packet's sequence number because of wraparound (for instance, 1), no packets would be\n        // removed, as the condition `seq_nr < last_acked` would fail immediately.\n        //\n        // On the other hand, I can't keep removing the first packet in a loop until its sequence\n        // number matches `last_acked` because it might never match, and in that case no packets\n        // should be removed.\n        if let Some(position) = self\n            .send_window\n            .iter()\n            .position(|packet| packet.seq_nr() == self.last_acked)\n        {\n            for _ in 0..position + 1 {\n                let packet = self.send_window.remove(0);\n                self.curr_window -= packet.len() as u32;\n            }\n        }\n        debug!(\"self.curr_window: {}\", self.curr_window);\n    }\n\n    /// Handles an incoming packet, updating socket state accordingly.\n    ///\n    /// Returns the appropriate reply packet, if needed.\n    fn handle_packet(&mut self, packet: &Packet, src: SocketAddr) -> Result<Option<Packet>> {\n        debug!(\"({:?}, {:?})\", self.state, packet.get_type());\n\n        // Acknowledge only if the packet strictly follows the previous one\n        if packet.seq_nr().wrapping_sub(self.ack_nr) == 1 {\n            self.ack_nr = packet.seq_nr();\n        }\n\n        // Reset connection if connection id doesn't match and this isn't a SYN\n        if packet.get_type() != PacketType::Syn\n            && self.state != SocketState::SynSent\n            && !(packet.connection_id() == self.sender_connection_id\n                || packet.connection_id() == self.receiver_connection_id)\n        {\n            return Ok(Some(self.prepare_reply(packet, PacketType::Reset)));\n        }\n\n        // Update remote window size\n        self.remote_wnd_size = packet.wnd_size();\n        debug!(\"self.remote_wnd_size: {}\", self.remote_wnd_size);\n\n        // Update remote peer's delay between them sending the packet and us receiving it\n        let now = now_microseconds();\n        self.their_delay = abs_diff(now, packet.timestamp());\n        debug!(\"self.their_delay: {}\", self.their_delay);\n\n        match (self.state, packet.get_type()) {\n            (SocketState::New, PacketType::Syn) => {\n                self.connected_to = src;\n                self.ack_nr = packet.seq_nr();\n                self.seq_nr = rand::random();\n                self.receiver_connection_id = packet.connection_id() + 1;\n                self.sender_connection_id = packet.connection_id();\n                self.state = SocketState::Connected;\n                self.last_dropped = self.ack_nr;\n\n                Ok(Some(self.prepare_reply(packet, PacketType::State)))\n            }\n            (_, PacketType::Syn) => Ok(Some(self.prepare_reply(packet, PacketType::Reset))),\n            (SocketState::SynSent, PacketType::State) => {\n                self.connected_to = src;\n                self.ack_nr = packet.seq_nr();\n                self.seq_nr += 1;\n                self.state = SocketState::Connected;\n                self.last_acked = packet.ack_nr();\n                self.last_acked_timestamp = now_microseconds();\n                Ok(None)\n            }\n            (SocketState::SynSent, _) => Err(SocketError::InvalidReply.into()),\n            (SocketState::Connected, PacketType::Data)\n            | (SocketState::FinSent, PacketType::Data) => Ok(self.handle_data_packet(packet)),\n            (SocketState::Connected, PacketType::State) => {\n                self.handle_state_packet(packet);\n                Ok(None)\n            }\n            (SocketState::Connected, PacketType::Fin) | (SocketState::FinSent, PacketType::Fin) => {\n                if packet.ack_nr() < self.seq_nr {\n                    debug!(\"FIN received but there are missing acknowledgements for sent packets\");\n                }\n                let mut reply = self.prepare_reply(packet, PacketType::State);\n                if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {\n                    debug!(\n                        \"current ack_nr ({}) is behind received packet seq_nr ({})\",\n                        self.ack_nr,\n                        packet.seq_nr()\n                    );\n\n                    // Set SACK extension payload if the packet is not in order\n                    let sack = self.build_selective_ack();\n\n                    if !sack.is_empty() {\n                        reply.set_sack(sack);\n                    }\n                }\n\n                // Give up, the remote peer might not care about our missing packets\n                self.state = SocketState::Closed;\n                Ok(Some(reply))\n            }\n            (SocketState::Closed, PacketType::Fin) => {\n                Ok(Some(self.prepare_reply(packet, PacketType::State)))\n            }\n            (SocketState::FinSent, PacketType::State) => {\n                if packet.ack_nr() == self.seq_nr {\n                    self.state = SocketState::Closed;\n                } else {\n                    self.handle_state_packet(packet);\n                }\n                Ok(None)\n            }\n            (_, PacketType::Reset) => {\n                self.state = SocketState::ResetReceived;\n                Err(SocketError::ConnectionReset.into())\n            }\n            (state, ty) => {\n                let message = format!(\"Unimplemented handling for ({:?},{:?})\", state, ty);\n                debug!(\"{}\", message);\n                Err(SocketError::Other(message).into())\n            }\n        }\n    }\n\n    fn handle_data_packet(&mut self, packet: &Packet) -> Option<Packet> {\n        // If a FIN was previously sent, reply with a FIN packet acknowledging the received packet.\n        let packet_type = if self.state == SocketState::FinSent {\n            PacketType::Fin\n        } else {\n            PacketType::State\n        };\n        let mut reply = self.prepare_reply(packet, packet_type);\n\n        if packet.seq_nr().wrapping_sub(self.ack_nr) > 1 {\n            debug!(\n                \"current ack_nr ({}) is behind received packet seq_nr ({})\",\n                self.ack_nr,\n                packet.seq_nr()\n            );\n\n            // Set SACK extension payload if the packet is not in order\n            let sack = self.build_selective_ack();\n\n            if !sack.is_empty() {\n                reply.set_sack(sack);\n            }\n        }\n\n        Some(reply)\n    }\n\n    fn queuing_delay(&self) -> Delay {\n        let filtered_current_delay = self.filtered_current_delay();\n        let min_base_delay = self.min_base_delay();\n        let queuing_delay = filtered_current_delay - min_base_delay;\n\n        debug!(\"filtered_current_delay: {}\", filtered_current_delay);\n        debug!(\"min_base_delay: {}\", min_base_delay);\n        debug!(\"queuing_delay: {}\", queuing_delay);\n\n        queuing_delay\n    }\n\n    /// Calculates the new congestion window size, increasing it or decreasing it.\n    ///\n    /// This is the core of uTP, the [LEDBAT][ledbat_rfc] congestion algorithm. It depends on\n    /// estimating the queuing delay between the two peers, and adjusting the congestion window\n    /// accordingly.\n    ///\n    /// `off_target` is a normalized value representing the difference between the current queuing\n    /// delay and a fixed target delay (`TARGET`). `off_target` ranges between -1.0 and 1.0. A\n    /// positive value makes the congestion window increase, while a negative value makes the\n    /// congestion window decrease.\n    ///\n    /// `bytes_newly_acked` is the number of bytes acknowledged by an inbound `State` packet. It may\n    /// be the size of the packet explicitly acknowledged by the inbound packet (i.e., with sequence\n    /// number equal to the inbound packet's acknowledgement number), or every packet implicitly\n    /// acknowledged (every packet with sequence number between the previous inbound `State`\n    /// packet's acknowledgement number and the current inbound `State` packet's acknowledgement\n    /// number).\n    ///\n    ///[ledbat_rfc]: https://tools.ietf.org/html/rfc6817\n    fn update_congestion_window(&mut self, off_target: f64, bytes_newly_acked: u32) {\n        let flightsize = self.curr_window;\n\n        let cwnd_increase = GAIN * off_target * bytes_newly_acked as f64 * MSS as f64;\n        let cwnd_increase = cwnd_increase / self.cwnd as f64;\n        debug!(\"cwnd_increase: {}\", cwnd_increase);\n\n        self.cwnd = (self.cwnd as f64 + cwnd_increase) as u32;\n        let max_allowed_cwnd = flightsize + ALLOWED_INCREASE * MSS;\n        self.cwnd = min(self.cwnd, max_allowed_cwnd);\n        self.cwnd = max(self.cwnd, MIN_CWND * MSS);\n\n        debug!(\"cwnd: {}\", self.cwnd);\n        debug!(\"max_allowed_cwnd: {}\", max_allowed_cwnd);\n    }\n\n    fn handle_state_packet(&mut self, packet: &Packet) {\n        if packet.ack_nr() == self.last_acked {\n            self.duplicate_ack_count += 1;\n        } else {\n            self.last_acked = packet.ack_nr();\n            self.last_acked_timestamp = now_microseconds();\n            self.duplicate_ack_count = 1;\n        }\n\n        // Update congestion window size\n        if let Some(index) = self\n            .send_window\n            .iter()\n            .position(|p| packet.ack_nr() == p.seq_nr())\n        {\n            // Calculate the sum of the size of every packet implicitly and explicitly acknowledged\n            // by the inbound packet (i.e., every packet whose sequence number precedes the inbound\n            // packet's acknowledgement number, plus the packet whose sequence number matches)\n            let bytes_newly_acked = self\n                .send_window\n                .iter()\n                .take(index + 1)\n                .fold(0, |acc, p| acc + p.len());\n\n            // Update base and current delay\n            let now = now_microseconds();\n            let our_delay = now - self.send_window[index].timestamp();\n            debug!(\"our_delay: {}\", our_delay);\n            self.update_base_delay(our_delay, now);\n            self.update_current_delay(our_delay, now);\n\n            let off_target: f64 = (TARGET - u32::from(self.queuing_delay()) as f64) / TARGET;\n            debug!(\"off_target: {}\", off_target);\n\n            self.update_congestion_window(off_target, bytes_newly_acked as u32);\n\n            // Update congestion timeout\n            let rtt = u32::from(our_delay - self.queuing_delay()) / 1000; // in milliseconds\n            self.update_congestion_timeout(rtt as i32);\n        }\n\n        let mut packet_loss_detected: bool =\n            !self.send_window.is_empty() && self.duplicate_ack_count == 3;\n\n        // Process extensions, if any\n        for extension in packet.extensions() {\n            if extension.get_type() == ExtensionType::SelectiveAck {\n                // If three or more packets are acknowledged past the implicit missing one,\n                // assume it was lost.\n                if extension.iter().count_ones() >= 3 {\n                    self.resend_lost_packet(packet.ack_nr() + 1);\n                    packet_loss_detected = true;\n                }\n\n                if let Some(last_seq_nr) = self.send_window.last().map(Packet::seq_nr) {\n                    let lost_packets = extension\n                        .iter()\n                        .enumerate()\n                        .filter(|&(_, received)| !received)\n                        .map(|(idx, _)| packet.ack_nr() + 2 + idx as u16)\n                        .take_while(|&seq_nr| seq_nr < last_seq_nr);\n\n                    for seq_nr in lost_packets {\n                        debug!(\"SACK: packet {} lost\", seq_nr);\n                        self.resend_lost_packet(seq_nr);\n                        packet_loss_detected = true;\n                    }\n                }\n            } else {\n                debug!(\"Unknown extension {:?}, ignoring\", extension.get_type());\n            }\n        }\n\n        // Three duplicate ACKs mean a fast resend request. Resend the first unacknowledged packet\n        // if the incoming packet doesn't have a SACK extension. If it does, the lost packets were\n        // already resent.\n        if !self.send_window.is_empty()\n            && self.duplicate_ack_count == 3\n            && !packet\n                .extensions()\n                .any(|ext| ext.get_type() == ExtensionType::SelectiveAck)\n        {\n            self.resend_lost_packet(packet.ack_nr() + 1);\n        }\n\n        // Packet lost, halve the congestion window\n        if packet_loss_detected {\n            debug!(\"packet loss detected, halving congestion window\");\n            self.cwnd = max(self.cwnd / 2, MIN_CWND * MSS);\n            debug!(\"cwnd: {}\", self.cwnd);\n        }\n\n        // Success, advance send window\n        self.advance_send_window();\n    }\n\n    /// Inserts a packet into the socket's buffer.\n    ///\n    /// The packet is inserted in such a way that the packets in the buffer are sorted according to\n    /// their sequence number in ascending order. This allows storing packets that were received out\n    /// of order.\n    ///\n    /// Trying to insert a duplicate of a packet will silently fail.\n    /// it's more recent (larger timestamp).\n    fn insert_into_buffer(&mut self, packet: Packet) {\n        // Immediately push to the end if the packet's sequence number comes after the last\n        // packet's.\n        if self\n            .incoming_buffer\n            .last()\n            .map_or(false, |p| packet.seq_nr() > p.seq_nr())\n        {\n            self.incoming_buffer.push(packet);\n        } else {\n            // Find index following the most recent packet before the one we wish to insert\n            let i = self\n                .incoming_buffer\n                .iter()\n                .filter(|p| p.seq_nr() < packet.seq_nr())\n                .count();\n\n            if self\n                .incoming_buffer\n                .get(i)\n                .map_or(true, |p| p.seq_nr() != packet.seq_nr())\n            {\n                self.incoming_buffer.insert(i, packet);\n            }\n        }\n    }\n}\n\nimpl Drop for UtpSocket {\n    fn drop(&mut self) {\n        let _ = self.close();\n    }\n}\n\n/// A structure representing a socket server.\n///\n/// # Examples\n///\n/// ```no_run\n/// use utp::{UtpListener, UtpSocket};\n/// use std::thread;\n///\n/// fn handle_client(socket: UtpSocket) {\n///     // ...\n/// }\n///\n/// fn main() {\n///     // Create a listener\n///     let addr = \"127.0.0.1:8080\";\n///     let listener = UtpListener::bind(addr).expect(\"Error binding socket\");\n///\n///     for connection in listener.incoming() {\n///         // Spawn a new handler for each new connection\n///         if let Ok((socket, _src)) = connection {\n///             thread::spawn(move || handle_client(socket));\n///         }\n///     }\n/// }\n/// ```\npub struct UtpListener {\n    /// The public facing UDP socket\n    socket: UdpSocket,\n}\n\nimpl UtpListener {\n    /// Creates a new `UtpListener` bound to a specific address.\n    ///\n    /// The resulting listener is ready for accepting connections.\n    ///\n    /// The address type can be any implementer of the `ToSocketAddr` trait. See its documentation\n    /// for concrete examples.\n    ///\n    /// If more than one valid address is specified, only the first will be used.\n    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpListener> {\n        UdpSocket::bind(addr).map(|s| UtpListener { socket: s })\n    }\n\n    /// Accepts a new incoming connection from this listener.\n    ///\n    /// This function will block the caller until a new uTP connection is established. When\n    /// established, the corresponding `UtpSocket` and the peer's remote address will be returned.\n    ///\n    /// Notice that the resulting `UtpSocket` is bound to a different local port than the public\n    /// listening port (which `UtpListener` holds). This may confuse the remote peer!\n    pub fn accept(&self) -> Result<(UtpSocket, SocketAddr)> {\n        let mut buf = [0; BUF_SIZE];\n\n        self.socket.recv_from(&mut buf).and_then(|(nread, src)| {\n            let packet = Packet::try_from(&buf[..nread])?;\n\n            // Ignore non-SYN packets\n            if packet.get_type() != PacketType::Syn {\n                let message = format!(\"Expected SYN packet, got {:?} instead\", packet.get_type());\n                return Err(SocketError::Other(message).into());\n            }\n\n            // The address of the new socket will depend on the type of the listener.\n            let inner_socket = self.socket.local_addr().and_then(|addr| match addr {\n                SocketAddr::V4(_) => UdpSocket::bind(\"0.0.0.0:0\"),\n                SocketAddr::V6(_) => UdpSocket::bind(\"[::]:0\"),\n            });\n\n            let mut socket = inner_socket.map(|s| UtpSocket::from_raw_parts(s, src))?;\n\n            // Establish connection with remote peer\n            if let Ok(Some(reply)) = socket.handle_packet(&packet, src) {\n                socket\n                    .socket\n                    .send_to(reply.as_ref(), src)\n                    .and(Ok((socket, src)))\n            } else {\n                Err(SocketError::Other(\"Reached unreachable statement\".to_owned()).into())\n            }\n        })\n    }\n\n    /// Returns an iterator over the connections being received by this listener.\n    ///\n    /// The returned iterator will never return `None`.\n    pub fn incoming(&self) -> Incoming<'_> {\n        Incoming { listener: self }\n    }\n\n    /// Returns the local socket address of this listener.\n    pub fn local_addr(&self) -> Result<SocketAddr> {\n        self.socket.local_addr()\n    }\n}\n\npub struct Incoming<'a> {\n    listener: &'a UtpListener,\n}\n\nimpl<'a> Iterator for Incoming<'a> {\n    type Item = Result<(UtpSocket, SocketAddr)>;\n\n    fn next(&mut self) -> Option<Result<(UtpSocket, SocketAddr)>> {\n        Some(self.listener.accept())\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use crate::packet::*;\n    use crate::socket::{take_address, SocketState, UtpListener, UtpSocket, BUF_SIZE};\n    use crate::time::now_microseconds;\n    use rand;\n    use std::io::ErrorKind;\n    use std::net::ToSocketAddrs;\n    use std::thread;\n\n    macro_rules! iotry {\n        ($e:expr) => {\n            match $e {\n                Ok(e) => e,\n                Err(e) => panic!(\"{:?}\", e),\n            }\n        };\n    }\n\n    fn next_test_port() -> u16 {\n        use std::sync::atomic::{AtomicUsize, Ordering};\n        static NEXT_OFFSET: AtomicUsize = AtomicUsize::new(0);\n        const BASE_PORT: u16 = 9600;\n        BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16\n    }\n\n    fn next_test_ip4<'a>() -> (&'a str, u16) {\n        (\"127.0.0.1\", next_test_port())\n    }\n\n    fn next_test_ip6<'a>() -> (&'a str, u16) {\n        (\"::1\", next_test_port())\n    }\n\n    #[test]\n    fn test_socket_ipv4() {\n        let server_addr = next_test_ip4();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        assert_eq!(server.state, SocketState::New);\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n            // Check proper difference in client's send connection id and receive connection id\n            assert_eq!(\n                client.sender_connection_id,\n                client.receiver_connection_id + 1\n            );\n            assert_eq!(\n                client.connected_to,\n                server_addr.to_socket_addrs().unwrap().next().unwrap()\n            );\n            iotry!(client.close());\n            drop(client);\n        });\n\n        let mut buf = [0u8; BUF_SIZE];\n        match server.recv_from(&mut buf) {\n            e => println!(\"{:?}\", e),\n        }\n        // After establishing a new connection, the server's ids are a mirror of the client's.\n        assert_eq!(\n            server.receiver_connection_id,\n            server.sender_connection_id + 1\n        );\n\n        assert_eq!(server.state, SocketState::Closed);\n        drop(server);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_socket_ipv6() {\n        let server_addr = next_test_ip6();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        assert_eq!(server.state, SocketState::New);\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n            // Check proper difference in client's send connection id and receive connection id\n            assert_eq!(\n                client.sender_connection_id,\n                client.receiver_connection_id + 1\n            );\n            assert_eq!(\n                client.connected_to,\n                server_addr.to_socket_addrs().unwrap().next().unwrap()\n            );\n            iotry!(client.close());\n            drop(client);\n        });\n\n        let mut buf = [0u8; BUF_SIZE];\n        match server.recv_from(&mut buf) {\n            e => println!(\"{:?}\", e),\n        }\n        // After establishing a new connection, the server's ids are a mirror of the client's.\n        assert_eq!(\n            server.receiver_connection_id,\n            server.sender_connection_id + 1\n        );\n\n        assert_eq!(server.state, SocketState::Closed);\n        drop(server);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_recvfrom_on_closed_socket() {\n        let server_addr = next_test_ip4();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        assert_eq!(server.state, SocketState::New);\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n            assert!(client.close().is_ok());\n        });\n\n        // Make the server listen for incoming connections until the end of the input\n        let mut buf = [0u8; BUF_SIZE];\n        let _resp = server.recv_from(&mut buf);\n        assert_eq!(server.state, SocketState::Closed);\n\n        // Trying to receive again returns `Ok(0)` (equivalent to the old `EndOfFile`)\n        match server.recv_from(&mut buf) {\n            Ok((0, _src)) => {}\n            e => panic!(\"Expected Ok(0), got {:?}\", e),\n        }\n        assert_eq!(server.state, SocketState::Closed);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_sendto_on_closed_socket() {\n        let server_addr = next_test_ip4();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        assert_eq!(server.state, SocketState::New);\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n            iotry!(client.close());\n        });\n\n        // Make the server listen for incoming connections\n        let mut buf = [0u8; BUF_SIZE];\n        let (_read, _src) = iotry!(server.recv_from(&mut buf));\n        assert_eq!(server.state, SocketState::Closed);\n\n        // Trying to send to the socket after closing it raises an error\n        match server.send_to(&buf) {\n            Err(ref e) if e.kind() == ErrorKind::NotConnected => (),\n            v => panic!(\"expected {:?}, got {:?}\", ErrorKind::NotConnected, v),\n        }\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_acks_on_socket() {\n        use std::sync::mpsc::channel;\n        let server_addr = next_test_ip4();\n        let (tx, rx) = channel();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        let child = thread::spawn(move || {\n            // Make the server listen for incoming connections\n            let mut buf = [0u8; BUF_SIZE];\n            let _resp = server.recv(&mut buf);\n            tx.send(server.seq_nr).unwrap();\n\n            // Close the connection\n            iotry!(server.recv_from(&mut buf));\n\n            drop(server);\n        });\n\n        let mut client = iotry!(UtpSocket::connect(server_addr));\n        assert_eq!(client.state, SocketState::Connected);\n        let sender_seq_nr = rx.recv().unwrap();\n        let ack_nr = client.ack_nr;\n        assert_eq!(ack_nr, sender_seq_nr);\n        assert!(client.close().is_ok());\n\n        // The reply to both connect (SYN) and close (FIN) should be\n        // STATE packets, which don't increase the sequence number\n        // and, hence, the receiver's acknowledgement number.\n        assert_eq!(client.ack_nr, ack_nr);\n        drop(client);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_handle_packet() {\n        //fn test_connection_setup() {\n        let initial_connection_id: u16 = rand::random();\n        let sender_connection_id = initial_connection_id + 1;\n        let (server_addr, client_addr) = (\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n        );\n        let mut socket = iotry!(UtpSocket::bind(server_addr));\n\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(initial_connection_id);\n\n        // Do we have a response?\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n\n        // Is is of the correct type?\n        let response = response.unwrap();\n        assert_eq!(response.get_type(), PacketType::State);\n\n        // Same connection id on both ends during connection establishment\n        assert_eq!(response.connection_id(), packet.connection_id());\n\n        // Response acknowledges SYN\n        assert_eq!(response.ack_nr(), packet.seq_nr());\n\n        // No payload?\n        assert!(response.payload().is_empty());\n        //}\n\n        // ---------------------------------\n\n        // fn test_connection_usage() {\n        let old_packet = packet;\n        let old_response = response;\n\n        let mut packet = Packet::new();\n        packet.set_type(PacketType::Data);\n        packet.set_connection_id(sender_connection_id);\n        packet.set_seq_nr(old_packet.seq_nr() + 1);\n        packet.set_ack_nr(old_response.seq_nr());\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n\n        let response = response.unwrap();\n        assert_eq!(response.get_type(), PacketType::State);\n\n        // Sender (i.e., who the initiated connection and sent a SYN) has connection id equal to\n        // initial connection id + 1\n        // Receiver (i.e., who accepted connection) has connection id equal to initial connection id\n        assert_eq!(response.connection_id(), initial_connection_id);\n        assert_eq!(response.connection_id(), packet.connection_id() - 1);\n\n        // Previous packets should be ack'ed\n        assert_eq!(response.ack_nr(), packet.seq_nr());\n\n        // Responses with no payload should not increase the sequence number\n        assert!(response.payload().is_empty());\n        assert_eq!(response.seq_nr(), old_response.seq_nr());\n        // }\n\n        //fn test_connection_teardown() {\n        let old_packet = packet;\n        let old_response = response;\n\n        let mut packet = Packet::new();\n        packet.set_type(PacketType::Fin);\n        packet.set_connection_id(sender_connection_id);\n        packet.set_seq_nr(old_packet.seq_nr() + 1);\n        packet.set_ack_nr(old_response.seq_nr());\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n\n        let response = response.unwrap();\n\n        assert_eq!(response.get_type(), PacketType::State);\n\n        // FIN packets have no payload but the sequence number shouldn't increase\n        assert_eq!(packet.seq_nr(), old_packet.seq_nr() + 1);\n\n        // Nor should the ACK packet's sequence number\n        assert_eq!(response.seq_nr(), old_response.seq_nr());\n\n        // FIN should be acknowledged\n        assert_eq!(response.ack_nr(), packet.seq_nr());\n\n        //}\n    }\n\n    #[test]\n    fn test_response_to_keepalive_ack() {\n        // Boilerplate test setup\n        let initial_connection_id: u16 = rand::random();\n        let (server_addr, client_addr) = (\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n        );\n        let mut socket = iotry!(UtpSocket::bind(server_addr));\n\n        // Establish connection\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(initial_connection_id);\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n        let response = response.unwrap();\n        assert_eq!(response.get_type(), PacketType::State);\n\n        let old_packet = packet;\n        let old_response = response;\n\n        // Now, send a keepalive packet\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::State);\n        packet.set_connection_id(initial_connection_id);\n        packet.set_seq_nr(old_packet.seq_nr() + 1);\n        packet.set_ack_nr(old_response.seq_nr());\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_none());\n\n        // Send a second keepalive packet, identical to the previous one\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_none());\n\n        // Mark socket as closed\n        socket.state = SocketState::Closed;\n    }\n\n    #[test]\n    fn test_response_to_wrong_connection_id() {\n        // Boilerplate test setup\n        let initial_connection_id: u16 = rand::random();\n        let (server_addr, client_addr) = (\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n        );\n        let mut socket = iotry!(UtpSocket::bind(server_addr));\n\n        // Establish connection\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(initial_connection_id);\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n        assert_eq!(response.unwrap().get_type(), PacketType::State);\n\n        // Now, disrupt connection with a packet with an incorrect connection id\n        let new_connection_id = initial_connection_id.wrapping_mul(2);\n\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::State);\n        packet.set_connection_id(new_connection_id);\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n\n        let response = response.unwrap();\n        assert_eq!(response.get_type(), PacketType::Reset);\n        assert_eq!(response.ack_nr(), packet.seq_nr());\n\n        // Mark socket as closed\n        socket.state = SocketState::Closed;\n    }\n\n    #[test]\n    fn test_unordered_packets() {\n        // Boilerplate test setup\n        let initial_connection_id: u16 = rand::random();\n        let (server_addr, client_addr) = (\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n        );\n        let mut socket = iotry!(UtpSocket::bind(server_addr));\n\n        // Establish connection\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(initial_connection_id);\n\n        let response = socket.handle_packet(&packet, client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n        let response = response.unwrap();\n        assert_eq!(response.get_type(), PacketType::State);\n\n        let old_packet = packet;\n        let old_response = response;\n\n        let mut window: Vec<Packet> = Vec::new();\n\n        // Now, send a keepalive packet\n        let mut packet = Packet::with_payload(&[1, 2, 3]);\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_connection_id(initial_connection_id);\n        packet.set_seq_nr(old_packet.seq_nr() + 1);\n        packet.set_ack_nr(old_response.seq_nr());\n        window.push(packet);\n\n        let mut packet = Packet::with_payload(&[4, 5, 6]);\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_connection_id(initial_connection_id);\n        packet.set_seq_nr(old_packet.seq_nr() + 2);\n        packet.set_ack_nr(old_response.seq_nr());\n        window.push(packet);\n\n        // Send packets in reverse order\n        let response = socket.handle_packet(&window[1], client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n        let response = response.unwrap();\n        assert!(response.ack_nr() != window[1].seq_nr());\n\n        let response = socket.handle_packet(&window[0], client_addr);\n        assert!(response.is_ok());\n        let response = response.unwrap();\n        assert!(response.is_some());\n\n        // Mark socket as closed\n        socket.state = SocketState::Closed;\n    }\n\n    #[test]\n    fn test_response_to_triple_ack() {\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        // Fits in a packet\n        const LEN: usize = 1024;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let d = data.clone();\n        assert_eq!(LEN, data.len());\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&d[..]));\n            iotry!(client.close());\n        });\n\n        let mut buf = [0; BUF_SIZE];\n        // Expect SYN\n        iotry!(server.recv(&mut buf));\n\n        // Receive data\n        let data_packet = match server.socket.recv_from(&mut buf) {\n            Ok((read, _src)) => iotry!(Packet::try_from(&buf[..read])),\n            Err(e) => panic!(\"{}\", e),\n        };\n        assert_eq!(data_packet.get_type(), PacketType::Data);\n        assert_eq!(&data_packet.payload(), &data.as_slice());\n        assert_eq!(data_packet.payload().len(), data.len());\n\n        // Send triple ACK\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::State);\n        packet.set_seq_nr(server.seq_nr);\n        packet.set_ack_nr(data_packet.seq_nr() - 1);\n        packet.set_connection_id(server.sender_connection_id);\n\n        for _ in 0..3 {\n            iotry!(server.socket.send_to(packet.as_ref(), server.connected_to));\n        }\n\n        // Receive data again and check that it's the same we reported as missing\n        let client_addr = server.connected_to;\n        match server.socket.recv_from(&mut buf) {\n            Ok((0, _)) => panic!(\"Received 0 bytes from socket\"),\n            Ok((read, _src)) => {\n                let packet = iotry!(Packet::try_from(&buf[..read]));\n                assert_eq!(packet.get_type(), PacketType::Data);\n                assert_eq!(packet.seq_nr(), data_packet.seq_nr());\n                assert_eq!(packet.payload(), data_packet.payload());\n                let response = server.handle_packet(&packet, client_addr);\n                assert!(response.is_ok());\n                let response = response.unwrap();\n                assert!(response.is_some());\n                let response = response.unwrap();\n                iotry!(server\n                    .socket\n                    .send_to(response.as_ref(), server.connected_to));\n            }\n            Err(e) => panic!(\"{}\", e),\n        }\n\n        // Receive close\n        iotry!(server.recv_from(&mut buf));\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_socket_timeout_request() {\n        let (server_addr, client_addr) = (\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n            next_test_ip4().to_socket_addrs().unwrap().next().unwrap(),\n        );\n\n        let client = iotry!(UtpSocket::bind(client_addr));\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        const LEN: usize = 512;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let d = data.clone();\n\n        assert_eq!(server.state, SocketState::New);\n        assert_eq!(client.state, SocketState::New);\n\n        // Check proper difference in client's send connection id and receive connection id\n        assert_eq!(\n            client.sender_connection_id,\n            client.receiver_connection_id + 1\n        );\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n            assert_eq!(client.connected_to, server_addr);\n            iotry!(client.send_to(&d[..]));\n            drop(client);\n        });\n\n        let mut buf = [0u8; BUF_SIZE];\n        server.recv(&mut buf).unwrap();\n        // After establishing a new connection, the server's ids are a mirror of the client's.\n        assert_eq!(\n            server.receiver_connection_id,\n            server.sender_connection_id + 1\n        );\n\n        assert_eq!(server.state, SocketState::Connected);\n\n        // Purposefully read from UDP socket directly and discard it, in order\n        // to behave as if the packet was lost and thus trigger the timeout\n        // handling in the *next* call to `UtpSocket.recv_from`.\n        iotry!(server.socket.recv_from(&mut buf));\n\n        // Set a much smaller than usual timeout, for quicker test completion\n        server.congestion_timeout = 50;\n\n        // Now wait for the previously discarded packet\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _)) => continue,\n                Ok(_) => break,\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n\n        drop(server);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_sorted_buffer_insertion() {\n        let server_addr = next_test_ip4();\n        let mut socket = iotry!(UtpSocket::bind(server_addr));\n\n        let mut packet = Packet::new();\n        packet.set_seq_nr(1);\n\n        assert!(socket.incoming_buffer.is_empty());\n\n        socket.insert_into_buffer(packet.clone());\n        assert_eq!(socket.incoming_buffer.len(), 1);\n\n        packet.set_seq_nr(2);\n        packet.set_timestamp(128.into());\n\n        socket.insert_into_buffer(packet.clone());\n        assert_eq!(socket.incoming_buffer.len(), 2);\n        assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);\n        assert_eq!(socket.incoming_buffer[1].timestamp(), 128.into());\n\n        packet.set_seq_nr(3);\n        packet.set_timestamp(256.into());\n\n        socket.insert_into_buffer(packet.clone());\n        assert_eq!(socket.incoming_buffer.len(), 3);\n        assert_eq!(socket.incoming_buffer[2].seq_nr(), 3);\n        assert_eq!(socket.incoming_buffer[2].timestamp(), 256.into());\n\n        // Replacing a packet with a more recent version doesn't work\n        packet.set_seq_nr(2);\n        packet.set_timestamp(456.into());\n\n        socket.insert_into_buffer(packet.clone());\n        assert_eq!(socket.incoming_buffer.len(), 3);\n        assert_eq!(socket.incoming_buffer[1].seq_nr(), 2);\n        assert_eq!(socket.incoming_buffer[1].timestamp(), 128.into());\n    }\n\n    #[test]\n    fn test_duplicate_packet_handling() {\n        let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());\n\n        let client = iotry!(UtpSocket::bind(client_addr));\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        assert_eq!(server.state, SocketState::New);\n        assert_eq!(client.state, SocketState::New);\n\n        // Check proper difference in client's send connection id and receive connection id\n        assert_eq!(\n            client.sender_connection_id,\n            client.receiver_connection_id + 1\n        );\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            assert_eq!(client.state, SocketState::Connected);\n\n            let mut packet = Packet::with_payload(&[1, 2, 3]);\n            packet.set_wnd_size(BUF_SIZE as u32);\n            packet.set_connection_id(client.sender_connection_id);\n            packet.set_seq_nr(client.seq_nr);\n            packet.set_ack_nr(client.ack_nr);\n\n            // Send two copies of the packet, with different timestamps\n            for _ in 0..2 {\n                packet.set_timestamp(now_microseconds());\n                iotry!(client.socket.send_to(packet.as_ref(), server_addr));\n            }\n            client.seq_nr += 1;\n\n            // Receive one ACK\n            for _ in 0..1 {\n                let mut buf = [0; BUF_SIZE];\n                iotry!(client.socket.recv_from(&mut buf));\n            }\n\n            iotry!(client.close());\n        });\n\n        let mut buf = [0u8; BUF_SIZE];\n        iotry!(server.recv(&mut buf));\n        // After establishing a new connection, the server's ids are a mirror of the client's.\n        assert_eq!(\n            server.receiver_connection_id,\n            server.sender_connection_id + 1\n        );\n\n        assert_eq!(server.state, SocketState::Connected);\n\n        let expected: Vec<u8> = vec![1, 2, 3];\n        let mut received: Vec<u8> = vec![];\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok((len, _src)) => received.extend(buf[..len].to_vec()),\n                Err(e) => panic!(\"{:?}\", e),\n            }\n        }\n        assert_eq!(received.len(), expected.len());\n        assert_eq!(received, expected);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_correct_packet_loss() {\n        let server_addr = next_test_ip4();\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        const LEN: usize = 1024 * 10;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let to_send = data.clone();\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n\n            // Send everything except the odd chunks\n            let chunks = to_send[..].chunks(BUF_SIZE);\n            let dst = client.connected_to;\n            for (index, chunk) in chunks.enumerate() {\n                let mut packet = Packet::with_payload(chunk);\n                packet.set_seq_nr(client.seq_nr);\n                packet.set_ack_nr(client.ack_nr);\n                packet.set_connection_id(client.sender_connection_id);\n                packet.set_timestamp(now_microseconds());\n\n                if index % 2 == 0 {\n                    iotry!(client.socket.send_to(packet.as_ref(), dst));\n                }\n\n                client.curr_window += packet.len() as u32;\n                client.send_window.push(packet);\n                client.seq_nr += 1;\n            }\n\n            iotry!(client.close());\n        });\n\n        let mut buf = [0; BUF_SIZE];\n        let mut received: Vec<u8> = vec![];\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok((len, _src)) => received.extend(buf[..len].to_vec()),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        assert_eq!(received.len(), data.len());\n        assert_eq!(received, data);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_tolerance_to_small_buffers() {\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        const LEN: usize = 1024;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let to_send = data.clone();\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&to_send[..]));\n            iotry!(client.close());\n        });\n\n        let mut read = Vec::new();\n        while server.state != SocketState::Closed {\n            let mut small_buffer = [0; 512];\n            match server.recv_from(&mut small_buffer) {\n                Ok((0, _src)) => break,\n                Ok((len, _src)) => read.extend(small_buffer[..len].to_vec()),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n\n        assert_eq!(read.len(), data.len());\n        assert_eq!(read, data);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_sequence_number_rollover() {\n        let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());\n\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        const LEN: usize = BUF_SIZE * 4;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let to_send = data.clone();\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::bind(client_addr));\n\n            // Advance socket's sequence number\n            client.seq_nr = ::std::u16::MAX - (to_send.len() / (BUF_SIZE * 2)) as u16;\n\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            // Send enough data to rollover\n            iotry!(client.send_to(&to_send[..]));\n            // Check that the sequence number did rollover\n            assert!(client.seq_nr < 50);\n            // Close connection\n            iotry!(client.close());\n        });\n\n        let mut buf = [0; BUF_SIZE];\n        let mut received: Vec<u8> = vec![];\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok((len, _src)) => received.extend(buf[..len].to_vec()),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        assert_eq!(received.len(), data.len());\n        assert_eq!(received, data);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_drop_unused_socket() {\n        let server_addr = next_test_ip4();\n        let server = iotry!(UtpSocket::bind(server_addr));\n\n        // Explicitly dropping socket. This test should not hang.\n        drop(server);\n    }\n\n    #[test]\n    fn test_invalid_packet_on_connect() {\n        use std::net::UdpSocket;\n        let server_addr = next_test_ip4();\n        let server = iotry!(UdpSocket::bind(server_addr));\n\n        let child = thread::spawn(move || {\n            let mut buf = [0; BUF_SIZE];\n            match server.recv_from(&mut buf) {\n                Ok((_len, client_addr)) => {\n                    iotry!(server.send_to(&[], client_addr));\n                }\n                _ => panic!(),\n            }\n        });\n\n        match UtpSocket::connect(server_addr) {\n            Err(ref e) if e.kind() == ErrorKind::Other => (), // OK\n            Err(e) => panic!(\"Expected ErrorKind::Other, got {:?}\", e),\n            Ok(_) => panic!(\"Expected Err, got Ok\"),\n        }\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_receive_unexpected_reply_type_on_connect() {\n        use std::net::UdpSocket;\n        let server_addr = next_test_ip4();\n        let server = iotry!(UdpSocket::bind(server_addr));\n\n        let child = thread::spawn(move || {\n            let mut buf = [0; BUF_SIZE];\n            let mut packet = Packet::new();\n            packet.set_type(PacketType::Data);\n\n            match server.recv_from(&mut buf) {\n                Ok((_len, client_addr)) => {\n                    iotry!(server.send_to(packet.as_ref(), client_addr));\n                }\n                _ => panic!(),\n            }\n        });\n\n        match UtpSocket::connect(server_addr) {\n            Err(ref e) if e.kind() == ErrorKind::ConnectionRefused => (), // OK\n            Err(e) => panic!(\"Expected ErrorKind::ConnectionRefused, got {:?}\", e),\n            Ok(_) => panic!(\"Expected Err, got Ok\"),\n        }\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_receiving_syn_on_established_connection() {\n        // Establish connection\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        let child = thread::spawn(move || {\n            let mut buf = [0; BUF_SIZE];\n            loop {\n                match server.recv_from(&mut buf) {\n                    Ok((0, _src)) => break,\n                    Ok(_) => (),\n                    Err(e) => panic!(\"{:?}\", e),\n                }\n            }\n        });\n\n        let mut client = iotry!(UtpSocket::connect(server_addr));\n        let mut packet = Packet::new();\n        packet.set_wnd_size(BUF_SIZE as u32);\n        packet.set_type(PacketType::Syn);\n        packet.set_connection_id(client.sender_connection_id);\n        packet.set_seq_nr(client.seq_nr);\n        packet.set_ack_nr(client.ack_nr);\n        iotry!(client.socket.send_to(packet.as_ref(), server_addr));\n        let mut buf = [0; BUF_SIZE];\n        match client.socket.recv_from(&mut buf) {\n            Ok((len, _src)) => {\n                let reply = Packet::try_from(&buf[..len]).ok().unwrap();\n                assert_eq!(reply.get_type(), PacketType::Reset);\n            }\n            Err(e) => panic!(\"{:?}\", e),\n        }\n        iotry!(client.close());\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_receiving_reset_on_established_connection() {\n        // Establish connection\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        let child = thread::spawn(move || {\n            let client = iotry!(UtpSocket::connect(server_addr));\n            let mut packet = Packet::new();\n            packet.set_wnd_size(BUF_SIZE as u32);\n            packet.set_type(PacketType::Reset);\n            packet.set_connection_id(client.sender_connection_id);\n            packet.set_seq_nr(client.seq_nr);\n            packet.set_ack_nr(client.ack_nr);\n            iotry!(client.socket.send_to(packet.as_ref(), server_addr));\n            let mut buf = [0; BUF_SIZE];\n            match client.socket.recv_from(&mut buf) {\n                Ok((_len, _src)) => (),\n                Err(e) => panic!(\"{:?}\", e),\n            }\n        });\n\n        let mut buf = [0; BUF_SIZE];\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok(_) => (),\n                Err(ref e) if e.kind() == ErrorKind::ConnectionReset => return,\n                Err(e) => panic!(\"{:?}\", e),\n            }\n        }\n        assert!(child.join().is_ok());\n        panic!(\"Should have received Reset\");\n    }\n\n    #[cfg(not(windows))]\n    #[test]\n    fn test_premature_fin() {\n        let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n\n        const LEN: usize = BUF_SIZE * 4;\n        let data = (0..LEN).map(|idx| idx as u8).collect::<Vec<u8>>();\n        let to_send = data.clone();\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&to_send[..]));\n            iotry!(client.close());\n        });\n\n        let mut buf = [0; BUF_SIZE];\n\n        // Accept connection\n        iotry!(server.recv(&mut buf));\n\n        // Send FIN without acknowledging packets received\n        let mut packet = Packet::new();\n        packet.set_connection_id(server.sender_connection_id);\n        packet.set_seq_nr(server.seq_nr);\n        packet.set_ack_nr(server.ack_nr);\n        packet.set_timestamp(now_microseconds());\n        packet.set_type(PacketType::Fin);\n        iotry!(server.socket.send_to(packet.as_ref(), client_addr));\n\n        // Receive until end\n        let mut received: Vec<u8> = vec![];\n        loop {\n            match server.recv_from(&mut buf) {\n                Ok((0, _src)) => break,\n                Ok((len, _src)) => received.extend(buf[..len].to_vec()),\n                Err(e) => panic!(\"{}\", e),\n            }\n        }\n        assert_eq!(received.len(), data.len());\n        assert_eq!(received, data);\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_base_delay_calculation() {\n        let minute_in_microseconds = 60 * 10i64.pow(6);\n        let samples = vec![\n            (0, 10),\n            (1, 8),\n            (2, 12),\n            (3, 7),\n            (minute_in_microseconds + 1, 11),\n            (minute_in_microseconds + 2, 19),\n            (minute_in_microseconds + 3, 9),\n        ];\n        let addr = next_test_ip4();\n        let mut socket = UtpSocket::bind(addr).unwrap();\n\n        for (timestamp, delay) in samples {\n            socket.update_base_delay(delay.into(), ((timestamp + delay) as u32).into());\n        }\n\n        let expected = vec![7i64, 9i64]\n            .into_iter()\n            .map(Into::into)\n            .collect::<Vec<_>>();\n        let actual = socket.base_delays.iter().cloned().collect::<Vec<_>>();\n        assert_eq!(expected, actual);\n        assert_eq!(\n            socket.min_base_delay(),\n            expected.iter().min().cloned().unwrap_or_default()\n        );\n    }\n\n    #[test]\n    fn test_local_addr() {\n        let addr = next_test_ip4();\n        let addr = addr.to_socket_addrs().unwrap().next().unwrap();\n        let socket = UtpSocket::bind(addr).unwrap();\n\n        assert!(socket.local_addr().is_ok());\n        assert_eq!(socket.local_addr().unwrap(), addr);\n    }\n\n    #[test]\n    fn test_listener_local_addr() {\n        let addr = next_test_ip4();\n        let addr = addr.to_socket_addrs().unwrap().next().unwrap();\n        let listener = UtpListener::bind(addr).unwrap();\n\n        assert!(listener.local_addr().is_ok());\n        assert_eq!(listener.local_addr().unwrap(), addr);\n    }\n\n    #[test]\n    fn test_peer_addr() {\n        use std::sync::mpsc::channel;\n        let addr = next_test_ip4();\n        let server_addr = addr.to_socket_addrs().unwrap().next().unwrap();\n        let mut server = UtpSocket::bind(server_addr).unwrap();\n        let (tx, rx) = channel();\n\n        // `peer_addr` should return an error because the socket isn't connected yet\n        assert!(server.peer_addr().is_err());\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            let mut buf = [0; 1024];\n            iotry!(tx.send(client.local_addr()));\n            iotry!(client.recv_from(&mut buf));\n        });\n\n        // Wait for a connection to be established\n        let mut buf = [0; 1024];\n        iotry!(server.recv(&mut buf));\n\n        // `peer_addr` should succeed and be equal to the client's address\n        assert!(server.peer_addr().is_ok());\n        // The client is expected to be bound to \"0.0.0.0\", so we can only check if the port is\n        // correct\n        let client_addr = rx.recv().unwrap().unwrap();\n        assert_eq!(server.peer_addr().unwrap().port(), client_addr.port());\n\n        // Close the connection\n        iotry!(server.close());\n\n        // `peer_addr` should now return an error because the socket is closed\n        assert!(server.peer_addr().is_err());\n\n        assert!(child.join().is_ok());\n    }\n\n    #[test]\n    fn test_take_address() {\n        // Expected successes\n        assert!(take_address(\"0.0.0.0:0\").is_ok());\n        assert!(take_address(\"[::]:0\").is_ok());\n        assert!(take_address((\"0.0.0.0\", 0)).is_ok());\n        assert!(take_address((\"::\", 0)).is_ok());\n        assert!(take_address((\"1.2.3.4\", 5)).is_ok());\n\n        // Expected failures\n        assert!(take_address(\"999.0.0.0:0\").is_err());\n        assert!(take_address(\"1.2.3.4:70000\").is_err());\n        assert!(take_address(\"\").is_err());\n        assert!(take_address(\"this is not an address\").is_err());\n        assert!(take_address(\"no.dns.resolution.com\").is_err());\n    }\n\n    // Test reaction to connection loss when sending data packets\n    #[test]\n    fn test_connection_loss_data() {\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        // Decrease timeouts for faster tests\n        server.congestion_timeout = 1;\n        let attempts = server.max_retransmission_retries;\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&[0]));\n            // Simulate connection loss by killing the socket.\n            client.state = SocketState::Closed;\n            let socket = client.socket.try_clone().unwrap();\n            let mut buf = [0; BUF_SIZE];\n            iotry!(socket.recv_from(&mut buf));\n            for _ in 0..attempts {\n                match socket.recv_from(&mut buf) {\n                    Ok((len, _src)) => assert_eq!(\n                        Packet::try_from(&buf[..len]).unwrap().get_type(),\n                        PacketType::Data\n                    ),\n                    Err(e) => panic!(\"{}\", e),\n                }\n            }\n        });\n\n        // Drain incoming packets\n        let mut buf = [0; BUF_SIZE];\n        iotry!(server.recv_from(&mut buf));\n\n        iotry!(server.send_to(&[0]));\n\n        // Try to receive ACKs, time out too many times on flush, and fail with `TimedOut`\n        let mut buf = [0; BUF_SIZE];\n        match server.recv(&mut buf) {\n            Err(ref e) if e.kind() == ErrorKind::TimedOut => (),\n            x => panic!(\"Expected Err(TimedOut), got {:?}\", x),\n        }\n\n        assert!(child.join().is_ok());\n    }\n\n    // Test reaction to connection loss when sending FIN\n    #[test]\n    fn test_connection_loss_fin() {\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        // Decrease timeouts for faster tests\n        server.congestion_timeout = 1;\n        let attempts = server.max_retransmission_retries;\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&[0]));\n            // Simulate connection loss by killing the socket.\n            client.state = SocketState::Closed;\n            let socket = client.socket.try_clone().unwrap();\n            let mut buf = [0; BUF_SIZE];\n            iotry!(socket.recv_from(&mut buf));\n            for _ in 0..attempts {\n                match socket.recv_from(&mut buf) {\n                    Ok((len, _src)) => assert_eq!(\n                        Packet::try_from(&buf[..len]).unwrap().get_type(),\n                        PacketType::Fin\n                    ),\n                    Err(e) => panic!(\"{}\", e),\n                }\n            }\n        });\n\n        // Drain incoming packets\n        let mut buf = [0; BUF_SIZE];\n        iotry!(server.recv_from(&mut buf));\n\n        // Send FIN, time out too many times, and fail with `TimedOut`\n        match server.close() {\n            Err(ref e) if e.kind() == ErrorKind::TimedOut => (),\n            x => panic!(\"Expected Err(TimedOut), got {:?}\", x),\n        }\n        assert!(child.join().is_ok());\n    }\n\n    // Test reaction to connection loss when waiting for data packets\n    #[test]\n    fn test_connection_loss_waiting() {\n        let server_addr = next_test_ip4();\n        let mut server = iotry!(UtpSocket::bind(server_addr));\n        // Decrease timeouts for faster tests\n        server.congestion_timeout = 1;\n        let attempts = server.max_retransmission_retries;\n\n        let child = thread::spawn(move || {\n            let mut client = iotry!(UtpSocket::connect(server_addr));\n            iotry!(client.send_to(&[0]));\n            // Simulate connection loss by killing the socket.\n            client.state = SocketState::Closed;\n            let socket = client.socket.try_clone().unwrap();\n            let seq_nr = client.seq_nr;\n            let mut buf = [0; BUF_SIZE];\n            for _ in 0..(3 * attempts) {\n                match socket.recv_from(&mut buf) {\n                    Ok((len, _src)) => {\n                        let packet = iotry!(Packet::try_from(&buf[..len]));\n                        assert_eq!(packet.get_type(), PacketType::State);\n                        assert_eq!(packet.ack_nr(), seq_nr - 1);\n                    }\n                    Err(e) => panic!(\"{}\", e),\n                }\n            }\n        });\n\n        // Drain incoming packets\n        let mut buf = [0; BUF_SIZE];\n        iotry!(server.recv_from(&mut buf));\n\n        // Try to receive data, time out too many times, and fail with `TimedOut`\n        let mut buf = [0; BUF_SIZE];\n        match server.recv_from(&mut buf) {\n            Err(ref e) if e.kind() == ErrorKind::TimedOut => (),\n            x => panic!(\"Expected Err(TimedOut), got {:?}\", x),\n        }\n        assert!(child.join().is_ok());\n    }\n}\n"
  },
  {
    "path": "src/stream.rs",
    "content": "use crate::socket::UtpSocket;\nuse std::io::{Read, Result, Write};\nuse std::net::{SocketAddr, ToSocketAddrs};\n\n/// A structure that represents a uTP (Micro Transport Protocol) stream between a local socket and a\n/// remote socket.\n///\n/// The connection will be closed when the value is dropped (either explicitly or when it goes out\n/// of scope).\n///\n/// The default maximum retransmission retries is 5, which translates to about 16 seconds. It can be\n/// changed by calling `set_max_retransmission_retries`. Notice that the initial congestion timeout\n/// is 500 ms and doubles with each timeout.\n///\n/// # Examples\n///\n/// ```no_run\n/// use utp::UtpStream;\n/// use std::io::{Read, Write};\n///\n/// let mut stream = UtpStream::bind(\"127.0.0.1:1234\").expect(\"Error binding stream\");\n/// let _ = stream.write(&[1]);\n/// let _ = stream.read(&mut [0; 1000]);\n/// ```\npub struct UtpStream {\n    socket: UtpSocket,\n}\n\nimpl UtpStream {\n    /// Creates a uTP stream listening on the given address.\n    ///\n    /// The address type can be any implementer of the `ToSocketAddr` trait. See its documentation\n    /// for concrete examples.\n    ///\n    /// If more than one valid address is specified, only the first will be used.\n    pub fn bind<A: ToSocketAddrs>(addr: A) -> Result<UtpStream> {\n        UtpSocket::bind(addr).map(|s| UtpStream { socket: s })\n    }\n\n    /// Opens a uTP connection to a remote host by hostname or IP address.\n    ///\n    /// The address type can be any implementer of the `ToSocketAddr` trait. See its documentation\n    /// for concrete examples.\n    ///\n    /// If more than one valid address is specified, only the first will be used.\n    pub fn connect<A: ToSocketAddrs>(dst: A) -> Result<UtpStream> {\n        // Port 0 means the operating system gets to choose it\n        UtpSocket::connect(dst).map(|s| UtpStream { socket: s })\n    }\n\n    /// Gracefully closes connection to peer.\n    ///\n    /// This method allows both peers to receive all packets still in\n    /// flight.\n    pub fn close(&mut self) -> Result<()> {\n        self.socket.close()\n    }\n\n    /// Returns the socket address of the local half of this uTP connection.\n    pub fn local_addr(&self) -> Result<SocketAddr> {\n        self.socket.local_addr()\n    }\n\n    /// Changes the maximum number of retransmission retries on the underlying socket.\n    pub fn set_max_retransmission_retries(&mut self, n: u32) {\n        self.socket.max_retransmission_retries = n;\n    }\n}\n\nimpl Read for UtpStream {\n    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {\n        self.socket.recv_from(buf).map(|(read, _src)| read)\n    }\n}\n\nimpl Write for UtpStream {\n    fn write(&mut self, buf: &[u8]) -> Result<usize> {\n        self.socket.send_to(buf)\n    }\n\n    fn flush(&mut self) -> Result<()> {\n        self.socket.flush()\n    }\n}\n\nimpl From<UtpSocket> for UtpStream {\n    fn from(socket: UtpSocket) -> Self {\n        UtpStream { socket }\n    }\n}\n\nimpl AsMut<UtpSocket> for UtpStream {\n    fn as_mut(&mut self) -> &mut UtpSocket {\n        &mut self.socket\n    }\n}\n"
  },
  {
    "path": "src/time.rs",
    "content": "use num_traits::ToPrimitive;\nuse std::fmt;\nuse std::ops::Sub;\nuse std::time;\n\n/// Return current time in microseconds since the UNIX epoch.\npub fn now_microseconds() -> Timestamp {\n    let t = time::SystemTime::now()\n        .duration_since(time::UNIX_EPOCH)\n        .unwrap_or_else(|e| e.duration());\n    (t.as_secs().wrapping_mul(1_000_000) as u32)\n        .wrapping_add(t.subsec_micros())\n        .into()\n}\n\n#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]\npub struct Timestamp(pub u32);\n\nimpl Sub for Timestamp {\n    type Output = Delay;\n\n    fn sub(self, other: Timestamp) -> Delay {\n        Delay(self.0 as i64 - other.0 as i64)\n    }\n}\n\nimpl Default for Timestamp {\n    fn default() -> Timestamp {\n        Timestamp(0)\n    }\n}\n\nimpl From<u32> for Timestamp {\n    fn from(value: u32) -> Timestamp {\n        Timestamp(value)\n    }\n}\n\nimpl From<Timestamp> for u32 {\n    fn from(value: Timestamp) -> u32 {\n        value.0\n    }\n}\n\n#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Ord, Eq)]\npub struct Delay(pub i64);\n\nimpl From<i64> for Delay {\n    fn from(value: i64) -> Delay {\n        Delay(value)\n    }\n}\n\nimpl From<u32> for Delay {\n    fn from(value: u32) -> Delay {\n        Delay(value as i64)\n    }\n}\n\nimpl From<Delay> for u32 {\n    fn from(value: Delay) -> u32 {\n        value.0 as u32\n    }\n}\n\nimpl Default for Delay {\n    fn default() -> Delay {\n        Delay(0)\n    }\n}\n\nimpl Sub for Delay {\n    type Output = Delay;\n\n    fn sub(self, other: Delay) -> Delay {\n        Delay(self.0 - other.0)\n    }\n}\n\nimpl fmt::Display for Delay {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"Delay({})\", self.0)\n    }\n}\n\nimpl ToPrimitive for Delay {\n    fn to_i64(&self) -> Option<i64> {\n        Some(self.0)\n    }\n\n    fn to_u64(&self) -> Option<u64> {\n        Some(self.0 as u64)\n    }\n}\n"
  },
  {
    "path": "src/util.rs",
    "content": "use num_traits::ToPrimitive;\nuse rand::{self, Rng};\nuse std::ops::Sub;\n\n/// Calculate the exponential weighted moving average for a vector of numbers, with a smoothing\n/// factor `alpha` between 0 and 1. A higher `alpha` discounts older observations faster.\npub fn ewma<'a, T, I>(mut samples: I, alpha: f64) -> f64\nwhere\n    T: ToPrimitive + 'a,\n    I: Iterator<Item = &'a T>,\n{\n    let first = samples.next().map_or(0.0, |v| v.to_f64().unwrap());\n    samples\n        .map(|v| v.to_f64().unwrap())\n        .fold(first, |avg, sample| alpha * sample + (1.0 - alpha) * avg)\n}\n\n/// Returns the absolute difference between two values.\npub fn abs_diff<T: PartialOrd + Sub<Output = U>, U>(a: T, b: T) -> U {\n    if a > b {\n        a - b\n    } else {\n        b - a\n    }\n}\n\n/// Safely generates two sequential connection identifiers.\n///\n/// This avoids an overflow when the generated receiver identifier is the largest\n/// representable value in u16 and it is incremented to yield the corresponding sender\n/// identifier.\npub fn generate_sequential_identifiers() -> (u16, u16) {\n    let mut rng = rand::thread_rng();\n    let id = rng.gen::<u16>();\n    if id.checked_add(1).is_some() {\n        (id, id + 1)\n    } else {\n        (id - 1, id)\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use crate::util::*;\n\n    #[test]\n    fn test_ewma_empty_vector() {\n        let empty: Vec<u32> = vec![];\n        let alpha = 1.0 / 3.0;\n        assert_eq!(ewma(empty.iter(), alpha), 0.0);\n    }\n\n    #[test]\n    fn test_ewma_one_element() {\n        let input = vec![1u32];\n        let alpha = 1.0 / 3.0;\n        assert_eq!(ewma(input.iter(), alpha), 1.0);\n    }\n\n    #[test]\n    fn test_exponential_smoothed_moving_average() {\n        let input = (1u32..11).collect::<Vec<u32>>();\n        let alpha = 1.0 / 3.0;\n        let expected = [\n            1.0,\n            4.0 / 3.0,\n            17.0 / 9.0,\n            70.0 / 27.0,\n            275.0 / 81.0,\n            1036.0 / 243.0,\n            3773.0 / 729.0,\n            13378.0 / 2187.0,\n            46439.0 / 6561.0,\n            158488.0 / 19683.0,\n        ];\n        assert_eq!(ewma(input.iter(), alpha), expected[expected.len() - 1]);\n    }\n\n    #[test]\n    fn test_abs_diff() {\n        let a = 10;\n        let b = 5;\n        assert_eq!(abs_diff(a, b), 5);\n        assert_eq!(abs_diff(b, a), 5);\n    }\n}\n"
  },
  {
    "path": "tests/stream.rs",
    "content": "use std::io::{Read, Write};\nuse std::thread;\nuse utp::UtpStream;\n\nmacro_rules! iotry {\n    ($e:expr) => {\n        match $e {\n            Ok(e) => e,\n            Err(e) => panic!(\"{}\", e),\n        }\n    };\n}\n\nfn next_test_port() -> u16 {\n    use std::sync::atomic::{AtomicUsize, Ordering};\n    static NEXT_OFFSET: AtomicUsize = AtomicUsize::new(0);\n    const BASE_PORT: u16 = 9600;\n    BASE_PORT + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16\n}\n\nfn next_test_ip4<'a>() -> (&'a str, u16) {\n    (\"127.0.0.1\", next_test_port())\n}\n\nfn next_test_ip6<'a>() -> (&'a str, u16) {\n    (\"::1\", next_test_port())\n}\n\n#[test]\nfn test_stream_open_and_close() {\n    let server_addr = next_test_ip4();\n    let mut server = iotry!(UtpStream::bind(server_addr));\n\n    let child = thread::spawn(move || {\n        let mut client = iotry!(UtpStream::connect(server_addr));\n        iotry!(client.close());\n        drop(client);\n    });\n\n    let mut received = vec![];\n    iotry!(server.read_to_end(&mut received));\n    iotry!(server.close());\n    assert!(child.join().is_ok());\n}\n\n#[test]\nfn test_stream_open_and_close_ipv6() {\n    let server_addr = next_test_ip6();\n    let mut server = iotry!(UtpStream::bind(server_addr));\n\n    let child = thread::spawn(move || {\n        let mut client = iotry!(UtpStream::connect(server_addr));\n        iotry!(client.close());\n        drop(client);\n    });\n\n    let mut received = vec![];\n    iotry!(server.read_to_end(&mut received));\n    iotry!(server.close());\n    assert!(child.join().is_ok());\n}\n\n#[test]\nfn test_stream_small_data() {\n    // Fits in a packet\n    const LEN: usize = 1024;\n    let data: Vec<u8> = (0..LEN).map(|idx| idx as u8).collect();\n    assert_eq!(LEN, data.len());\n\n    let d = data.clone();\n    let server_addr = next_test_ip4();\n    let mut server = iotry!(UtpStream::bind(server_addr));\n\n    let child = thread::spawn(move || {\n        let mut client = iotry!(UtpStream::connect(server_addr));\n        iotry!(client.write(&d[..]));\n        iotry!(client.close());\n    });\n\n    let mut received = Vec::with_capacity(LEN);\n    iotry!(server.read_to_end(&mut received));\n    assert!(!received.is_empty());\n    assert_eq!(received.len(), data.len());\n    assert_eq!(received, data);\n    assert!(child.join().is_ok());\n}\n\n#[test]\nfn test_stream_large_data() {\n    // Has to be sent over several packets\n    const LEN: usize = 1024 * 1024;\n    let data: Vec<u8> = (0..LEN).map(|idx| idx as u8).collect();\n    assert_eq!(LEN, data.len());\n\n    let d = data.clone();\n    let server_addr = next_test_ip4();\n    let mut server = iotry!(UtpStream::bind(server_addr));\n\n    let child = thread::spawn(move || {\n        let mut client = iotry!(UtpStream::connect(server_addr));\n        iotry!(client.write(&d[..]));\n        iotry!(client.close());\n    });\n\n    let mut received = Vec::with_capacity(LEN);\n    iotry!(server.read_to_end(&mut received));\n    assert!(!received.is_empty());\n    assert_eq!(received.len(), data.len());\n    assert_eq!(received, data);\n    assert!(child.join().is_ok());\n}\n\n#[test]\nfn test_stream_successive_reads() {\n    const LEN: usize = 1024;\n    let data: Vec<u8> = (0..LEN).map(|idx| idx as u8).collect();\n    assert_eq!(LEN, data.len());\n\n    let d = data.clone();\n    let server_addr = next_test_ip4();\n    let mut server = iotry!(UtpStream::bind(server_addr));\n\n    let child = thread::spawn(move || {\n        let mut client = iotry!(UtpStream::connect(server_addr));\n        iotry!(client.write(&d[..]));\n        iotry!(client.close());\n    });\n\n    let mut received = Vec::with_capacity(LEN);\n    iotry!(server.read_to_end(&mut received));\n    assert!(!received.is_empty());\n    assert_eq!(received.len(), data.len());\n    assert_eq!(received, data);\n\n    assert_eq!(server.read(&mut received).unwrap(), 0);\n    assert!(child.join().is_ok());\n}\n\n#[test]\nfn test_local_addr() {\n    use std::net::ToSocketAddrs;\n\n    let addr = next_test_ip4();\n    let addr = addr.to_socket_addrs().unwrap().next().unwrap();\n    let stream = UtpStream::bind(addr).unwrap();\n\n    assert!(stream.local_addr().is_ok());\n    assert_eq!(stream.local_addr().unwrap(), addr);\n}\n"
  }
]