actix-codec-0.5.2/CHANGES.md000064400000000000000000000030031046102023000134010ustar 00000000000000# Changes ## Unreleased ## 0.5.2 - Minimum supported Rust version (MSRV) is now 1.65. ## 0.5.1 - Logs emitted now use the `tracing` crate with `log` compatibility. - Minimum supported Rust version (MSRV) is now 1.49. ## 0.5.0 - Updated `tokio-util` dependency to `0.7.0`. ## 0.4.2 - No significant changes since `0.4.1`. ## 0.4.1 - Added `LinesCodec`. - `Framed::poll_ready` flushes when the buffer is full. ## 0.4.0 - No significant changes since v0.4.0-beta.1. ## 0.4.0-beta.1 - Replace `pin-project` with `pin-project-lite`. - Upgrade `tokio` dependency to `1`. - Upgrade `tokio-util` dependency to `0.6`. - Upgrade `bytes` dependency to `1`. ## 0.3.0 - No changes from beta 2. ## 0.3.0-beta.2 - Remove unused type parameter from `Framed::replace_codec`. ## 0.3.0-beta.1 - Use `.advance()` instead of `.split_to()`. - Upgrade `tokio-util` to `0.3`. - Improve `BytesCodec::encode()` performance. - Simplify `BytesCodec::decode()`. - Rename methods on `Framed` to better describe their use. - Add method on `Framed` to get a pinned reference to the underlying I/O. - Add method on `Framed` check emptiness of read buffer. ## 0.2.0 - Use specific futures dependencies. ## 0.2.0-alpha.4 - Fix buffer remaining capacity calculation. ## 0.2.0-alpha.3 - Use tokio 0.2. - Fix low/high watermark for write/read buffers. ## 0.2.0-alpha.2 - Migrated to `std::future`. ## 0.1.2 - Added `Framed::map_io()` method. ## 0.1.1 - Added `FramedParts::with_read_buffer()` method. ## 0.1.0 - Move codec to separate crate. actix-codec-0.5.2/Cargo.toml0000644000000032000000000000100112140ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "actix-codec" version = "0.5.2" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Codec utilities for working with framed protocols" keywords = [ "network", "framework", "async", "futures", ] categories = [ "network-programming", "asynchronous", ] license = "MIT OR Apache-2.0" repository = "https://github.com/actix/actix-net" [package.metadata.cargo_check_external_types] allowed_external_types = [ "bytes::*", "futures_core::*", "futures_sink::*", "tokio::*", "tokio_util::*", ] [[bench]] name = "lines" harness = false [dependencies.bitflags] version = "2" [dependencies.bytes] version = "1" [dependencies.futures-core] version = "0.3.7" default-features = false [dependencies.futures-sink] version = "0.3.7" default-features = false [dependencies.memchr] version = "2.3" [dependencies.pin-project-lite] version = "0.2" [dependencies.tokio] version = "1.23.1" [dependencies.tokio-util] version = "0.7" features = [ "codec", "io", ] [dependencies.tracing] version = "0.1.30" features = ["log"] default-features = false actix-codec-0.5.2/Cargo.toml.orig0000644000000020110000000000100121520ustar [package] name = "actix-codec" version = "0.5.2" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Codec utilities for working with framed protocols" keywords = ["network", "framework", "async", "futures"] repository = "https://github.com/actix/actix-net" categories = ["network-programming", "asynchronous"] license = "MIT OR Apache-2.0" edition.workspace = true rust-version.workspace = true [package.metadata.cargo_check_external_types] allowed_external_types = [ "bytes::*", "futures_core::*", "futures_sink::*", "tokio::*", "tokio_util::*", ] [dependencies] bitflags = "2" bytes = "1" futures-core = { version = "0.3.7", default-features = false } futures-sink = { version = "0.3.7", default-features = false } memchr = "2.3" pin-project-lite = "0.2" tokio = "1.23.1" tokio-util = { version = "0.7", features = ["codec", "io"] } tracing = { version = "0.1.30", default-features = false, features = ["log"] } [[bench]] name = "lines" harness = false actix-codec-0.5.2/Cargo.toml.orig000064400000000000000000000020111046102023000146740ustar 00000000000000[package] name = "actix-codec" version = "0.5.2" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Codec utilities for working with framed protocols" keywords = ["network", "framework", "async", "futures"] repository = "https://github.com/actix/actix-net" categories = ["network-programming", "asynchronous"] license = "MIT OR Apache-2.0" edition.workspace = true rust-version.workspace = true [package.metadata.cargo_check_external_types] allowed_external_types = [ "bytes::*", "futures_core::*", "futures_sink::*", "tokio::*", "tokio_util::*", ] [dependencies] bitflags = "2" bytes = "1" futures-core = { version = "0.3.7", default-features = false } futures-sink = { version = "0.3.7", default-features = false } memchr = "2.3" pin-project-lite = "0.2" tokio = "1.23.1" tokio-util = { version = "0.7", features = ["codec", "io"] } tracing = { version = "0.1.30", default-features = false, features = ["log"] } [[bench]] name = "lines" harness = false actix-codec-0.5.2/LICENSE-APACHE000064400000000000000000000261201046102023000137400ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017-NOW Actix Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. actix-codec-0.5.2/LICENSE-MIT000064400000000000000000000020421046102023000134450ustar 00000000000000Copyright (c) 2017-NOW Actix Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. actix-codec-0.5.2/src/bcodec.rs000064400000000000000000000013261046102023000143710ustar 00000000000000use std::io; use bytes::{Buf, Bytes, BytesMut}; use super::{Decoder, Encoder}; /// Bytes codec. Reads/writes chunks of bytes from a stream. #[derive(Debug, Copy, Clone)] pub struct BytesCodec; impl Encoder for BytesCodec { type Error = io::Error; #[inline] fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> { dst.extend_from_slice(item.chunk()); Ok(()) } } impl Decoder for BytesCodec { type Item = BytesMut; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { Ok(None) } else { Ok(Some(src.split())) } } } actix-codec-0.5.2/src/framed.rs000064400000000000000000000305721046102023000144150ustar 00000000000000use std::{ fmt, io, pin::Pin, task::{Context, Poll}, }; use bitflags::bitflags; use bytes::{Buf, BytesMut}; use futures_core::{ready, Stream}; use futures_sink::Sink; use pin_project_lite::pin_project; use crate::{AsyncRead, AsyncWrite, Decoder, Encoder}; /// Low-water mark const LW: usize = 1024; /// High-water mark const HW: usize = 8 * 1024; bitflags! { #[derive(Debug, Clone, Copy)] struct Flags: u8 { const EOF = 0b0001; const READABLE = 0b0010; } } pin_project! { /// A unified `Stream` and `Sink` interface to an underlying I/O object, using the `Encoder` and /// `Decoder` traits to encode and decode frames. /// /// Raw I/O objects work with byte sequences, but higher-level code usually wants to batch these /// into meaningful chunks, called "frames". This method layers framing on top of an I/O object, /// by using the `Encoder`/`Decoder` traits to handle encoding and decoding of message frames. /// Note that the incoming and outgoing frame types may be distinct. pub struct Framed { #[pin] io: T, codec: U, flags: Flags, read_buf: BytesMut, write_buf: BytesMut, } } impl Framed where T: AsyncRead + AsyncWrite, U: Decoder, { /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into /// a single object is often useful for layering things like gzip or TLS, which require both /// read and write access to the underlying object. pub fn new(io: T, codec: U) -> Framed { Framed { io, codec, flags: Flags::empty(), read_buf: BytesMut::with_capacity(HW), write_buf: BytesMut::with_capacity(HW), } } } impl Framed { /// Returns a reference to the underlying codec. pub fn codec_ref(&self) -> &U { &self.codec } /// Returns a mutable reference to the underlying codec. pub fn codec_mut(&mut self) -> &mut U { &mut self.codec } /// Returns a reference to the underlying I/O stream wrapped by `Frame`. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn io_ref(&self) -> &T { &self.io } /// Returns a mutable reference to the underlying I/O stream. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn io_mut(&mut self) -> &mut T { &mut self.io } /// Returns a `Pin` of a mutable reference to the underlying I/O stream. pub fn io_pin(self: Pin<&mut Self>) -> Pin<&mut T> { self.project().io } /// Check if read buffer is empty. pub fn is_read_buf_empty(&self) -> bool { self.read_buf.is_empty() } /// Check if write buffer is empty. pub fn is_write_buf_empty(&self) -> bool { self.write_buf.is_empty() } /// Check if write buffer is full. pub fn is_write_buf_full(&self) -> bool { self.write_buf.len() >= HW } /// Check if framed is able to write more data. /// /// `Framed` object considers ready if there is free space in write buffer. pub fn is_write_ready(&self) -> bool { self.write_buf.len() < HW } /// Consume the `Frame`, returning `Frame` with different codec. pub fn replace_codec(self, codec: U2) -> Framed { Framed { codec, io: self.io, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } /// Consume the `Frame`, returning `Frame` with different io. pub fn into_map_io(self, f: F) -> Framed where F: Fn(T) -> T2, { Framed { io: f(self.io), codec: self.codec, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } /// Consume the `Frame`, returning `Frame` with different codec. pub fn into_map_codec(self, f: F) -> Framed where F: Fn(U) -> U2, { Framed { io: self.io, codec: f(self.codec), flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } } impl Framed { /// Serialize item and write to the inner buffer pub fn write(mut self: Pin<&mut Self>, item: I) -> Result<(), >::Error> where T: AsyncWrite, U: Encoder, { let this = self.as_mut().project(); let remaining = this.write_buf.capacity() - this.write_buf.len(); if remaining < LW { this.write_buf.reserve(HW - remaining); } this.codec.encode(item, this.write_buf)?; Ok(()) } /// Try to read underlying I/O stream and decode item. pub fn next_item( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll::Item, U::Error>>> where T: AsyncRead, U: Decoder, { loop { let this = self.as_mut().project(); // Repeatedly call `decode` or `decode_eof` as long as it is "readable". Readable is // defined as not having returned `None`. If the upstream has returned EOF, and the // decoder is no longer readable, it can be assumed that the decoder will never become // readable again, at which point the stream is terminated. if this.flags.contains(Flags::READABLE) { if this.flags.contains(Flags::EOF) { match this.codec.decode_eof(this.read_buf) { Ok(Some(frame)) => return Poll::Ready(Some(Ok(frame))), Ok(None) => return Poll::Ready(None), Err(err) => return Poll::Ready(Some(Err(err))), } } tracing::trace!("attempting to decode a frame"); match this.codec.decode(this.read_buf) { Ok(Some(frame)) => { tracing::trace!("frame decoded from buffer"); return Poll::Ready(Some(Ok(frame))); } Err(err) => return Poll::Ready(Some(Err(err))), _ => (), // Need more data } this.flags.remove(Flags::READABLE); } debug_assert!(!this.flags.contains(Flags::EOF)); // Otherwise, try to read more data and try again. Make sure we've got room. let remaining = this.read_buf.capacity() - this.read_buf.len(); if remaining < LW { this.read_buf.reserve(HW - remaining) } let cnt = match tokio_util::io::poll_read_buf(this.io, cx, this.read_buf) { Poll::Pending => return Poll::Pending, Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err.into()))), Poll::Ready(Ok(cnt)) => cnt, }; if cnt == 0 { this.flags.insert(Flags::EOF); } this.flags.insert(Flags::READABLE); } } /// Flush write buffer to underlying I/O stream. pub fn flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> where T: AsyncWrite, U: Encoder, { let mut this = self.as_mut().project(); tracing::trace!("flushing framed transport"); while !this.write_buf.is_empty() { tracing::trace!("writing; remaining={}", this.write_buf.len()); let n = ready!(this.io.as_mut().poll_write(cx, this.write_buf))?; if n == 0 { return Poll::Ready(Err(io::Error::new( io::ErrorKind::WriteZero, "failed to write frame to transport", ) .into())); } // remove written data this.write_buf.advance(n); } // Try flushing the underlying IO ready!(this.io.poll_flush(cx))?; tracing::trace!("framed transport flushed"); Poll::Ready(Ok(())) } /// Flush write buffer and shutdown underlying I/O stream. pub fn close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> where T: AsyncWrite, U: Encoder, { let mut this = self.as_mut().project(); ready!(this.io.as_mut().poll_flush(cx))?; ready!(this.io.as_mut().poll_shutdown(cx))?; Poll::Ready(Ok(())) } } impl Stream for Framed where T: AsyncRead, U: Decoder, { type Item = Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.next_item(cx) } } impl Sink for Framed where T: AsyncWrite, U: Encoder, U::Error: From, { type Error = U::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.is_write_ready() { Poll::Ready(Ok(())) } else { self.flush(cx) } } fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { self.write(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.close(cx) } } impl fmt::Debug for Framed where T: fmt::Debug, U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Framed") .field("io", &self.io) .field("codec", &self.codec) .finish() } } impl Framed { /// This function returns a *single* object that is both `Stream` and `Sink`; grouping this into /// a single object is often useful for layering things like gzip or TLS, which require both /// read and write access to the underlying object. /// /// These objects take a stream, a read buffer and a write buffer. These fields can be obtained /// from an existing `Framed` with the `into_parts` method. pub fn from_parts(parts: FramedParts) -> Framed { Framed { io: parts.io, codec: parts.codec, flags: parts.flags, write_buf: parts.write_buf, read_buf: parts.read_buf, } } /// Consumes the `Frame`, returning its underlying I/O stream, the buffer with unprocessed data, /// and the codec. /// /// Note that care should be taken to not tamper with the underlying stream of data coming in as /// it may corrupt the stream of frames otherwise being worked with. pub fn into_parts(self) -> FramedParts { FramedParts { io: self.io, codec: self.codec, flags: self.flags, read_buf: self.read_buf, write_buf: self.write_buf, } } } /// `FramedParts` contains an export of the data of a Framed transport. /// /// It can be used to construct a new `Framed` with a different codec. It contains all current /// buffers and the inner transport. #[derive(Debug)] pub struct FramedParts { /// The inner transport used to read bytes to and write bytes to. pub io: T, /// The codec object. pub codec: U, /// The buffer with read but unprocessed data. pub read_buf: BytesMut, /// A buffer with unprocessed data which are not written yet. pub write_buf: BytesMut, flags: Flags, } impl FramedParts { /// Creates a new default `FramedParts`. pub fn new(io: T, codec: U) -> FramedParts { FramedParts { io, codec, flags: Flags::empty(), read_buf: BytesMut::new(), write_buf: BytesMut::new(), } } /// Creates a new `FramedParts` with read buffer. pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts { FramedParts { io, codec, read_buf, flags: Flags::empty(), write_buf: BytesMut::new(), } } } actix-codec-0.5.2/src/lib.rs000064400000000000000000000014431046102023000137200ustar 00000000000000//! Codec utilities for working with framed protocols. //! //! Contains adapters to go from streams of bytes, [`AsyncRead`] and [`AsyncWrite`], to framed //! streams implementing [`Sink`] and [`Stream`]. Framed streams are also known as `transports`. //! //! [`Sink`]: futures_sink::Sink //! [`Stream`]: futures_core::Stream #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible, missing_docs)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] pub use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; pub use tokio_util::{ codec::{Decoder, Encoder}, io::poll_read_buf, }; mod bcodec; mod framed; mod lines; pub use self::{ bcodec::BytesCodec, framed::{Framed, FramedParts}, lines::LinesCodec, }; actix-codec-0.5.2/src/lines.rs000064400000000000000000000110071046102023000142610ustar 00000000000000use std::io; use bytes::{Buf, BufMut, Bytes, BytesMut}; use memchr::memchr; use super::{Decoder, Encoder}; /// Lines codec. Reads/writes line delimited strings. /// /// Will split input up by LF or CRLF delimiters. Carriage return characters at the end of lines are /// not preserved. #[derive(Debug, Copy, Clone, Default)] #[non_exhaustive] pub struct LinesCodec; impl> Encoder for LinesCodec { type Error = io::Error; #[inline] fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> { let item = item.as_ref(); dst.reserve(item.len() + 1); dst.put_slice(item.as_bytes()); dst.put_u8(b'\n'); Ok(()) } } impl Decoder for LinesCodec { type Item = String; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { return Ok(None); } let len = match memchr(b'\n', src) { Some(n) => n, None => { return Ok(None); } }; // split up to new line char let mut buf = src.split_to(len); debug_assert_eq!(len, buf.len()); // remove new line char from source src.advance(1); match buf.last() { // remove carriage returns at the end of buf Some(b'\r') => buf.truncate(len - 1), // line is empty None => return Ok(Some(String::new())), _ => {} } try_into_utf8(buf.freeze()) } fn decode_eof(&mut self, src: &mut BytesMut) -> Result, Self::Error> { match self.decode(src)? { Some(frame) => Ok(Some(frame)), None if src.is_empty() => Ok(None), None => { let buf = match src.last() { // if last line ends in a CR then take everything up to it Some(b'\r') => src.split_to(src.len() - 1), // take all bytes from source _ => src.split(), }; if buf.is_empty() { return Ok(None); } try_into_utf8(buf.freeze()) } } } } // Attempts to convert bytes into a `String`. fn try_into_utf8(buf: Bytes) -> io::Result> { String::from_utf8(buf.to_vec()) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) .map(Some) } #[cfg(test)] mod tests { use bytes::BufMut as _; use super::*; #[test] fn lines_decoder() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::from("\nline 1\nline 2\r\nline 3\n\r\n\r"); assert_eq!("", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 1", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 2", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("line 3", codec.decode(&mut buf).unwrap().unwrap()); assert_eq!("", codec.decode(&mut buf).unwrap().unwrap()); assert!(codec.decode(&mut buf).unwrap().is_none()); assert!(codec.decode_eof(&mut buf).unwrap().is_none()); buf.put_slice(b"k"); assert!(codec.decode(&mut buf).unwrap().is_none()); assert_eq!("\rk", codec.decode_eof(&mut buf).unwrap().unwrap()); assert!(codec.decode(&mut buf).unwrap().is_none()); assert!(codec.decode_eof(&mut buf).unwrap().is_none()); } #[test] fn lines_encoder() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::new(); codec.encode("", &mut buf).unwrap(); assert_eq!(&buf[..], b"\n"); codec.encode("test", &mut buf).unwrap(); assert_eq!(&buf[..], b"\ntest\n"); codec.encode("a\nb", &mut buf).unwrap(); assert_eq!(&buf[..], b"\ntest\na\nb\n"); } #[test] fn lines_encoder_no_overflow() { let mut codec = LinesCodec::default(); let mut buf = BytesMut::new(); codec.encode("1234567", &mut buf).unwrap(); assert_eq!(&buf[..], b"1234567\n"); let mut buf = BytesMut::new(); codec.encode("12345678", &mut buf).unwrap(); assert_eq!(&buf[..], b"12345678\n"); let mut buf = BytesMut::new(); codec.encode("123456789111213", &mut buf).unwrap(); assert_eq!(&buf[..], b"123456789111213\n"); let mut buf = BytesMut::new(); codec.encode("1234567891112131", &mut buf).unwrap(); assert_eq!(&buf[..], b"1234567891112131\n"); } } actix-codec-0.5.2/tests/test_framed_sink.rs000064400000000000000000000140421046102023000170450ustar 00000000000000use std::{ collections::VecDeque, io::{self, Write}, pin::Pin, task::{ Context, Poll::{self, Pending, Ready}, }, }; use actix_codec::*; use bytes::{Buf as _, BufMut as _, BytesMut}; use futures_sink::Sink; use tokio_test::{assert_ready, task}; macro_rules! bilateral { ($($x:expr,)*) => {{ let mut v = VecDeque::new(); v.extend(vec![$($x),*]); Bilateral { calls: v } }}; } macro_rules! assert_ready { ($e:expr) => {{ use core::task::Poll::*; match $e { Ready(v) => v, Pending => panic!("pending"), } }}; ($e:expr, $($msg:tt),+) => {{ use core::task::Poll::*; match $e { Ready(v) => v, Pending => { let msg = format_args!($($msg),+); panic!("pending; {}", msg) } } }}; } #[derive(Debug)] pub struct Bilateral { pub calls: VecDeque>>, } impl Write for Bilateral { fn write(&mut self, src: &[u8]) -> io::Result { match self.calls.pop_front() { Some(Ok(data)) => { assert!(src.len() >= data.len()); assert_eq!(&data[..], &src[..data.len()]); Ok(data.len()) } Some(Err(err)) => Err(err), None => panic!("unexpected write; {:?}", src), } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncWrite for Bilateral { fn poll_write( self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { match Pin::get_mut(self).write(buf) { Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending, other => Ready(other), } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { match Pin::get_mut(self).flush() { Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Pending, other => Ready(other), } } fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { unimplemented!() } } impl AsyncRead for Bilateral { fn poll_read( mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { use io::ErrorKind::WouldBlock; match self.calls.pop_front() { Some(Ok(data)) => { debug_assert!(buf.remaining() >= data.len()); buf.put_slice(&data); Ready(Ok(())) } Some(Err(ref err)) if err.kind() == WouldBlock => Pending, Some(Err(err)) => Ready(Err(err)), None => Ready(Ok(())), } } } pub struct U32; impl Encoder for U32 { type Error = io::Error; fn encode(&mut self, item: u32, dst: &mut BytesMut) -> io::Result<()> { // Reserve space dst.reserve(4); dst.put_u32(item); Ok(()) } } impl Decoder for U32 { type Item = u32; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> io::Result> { if buf.len() < 4 { return Ok(None); } let n = buf.split_to(4).get_u32(); Ok(Some(n)) } } #[test] fn test_write_hits_highwater_mark() { // see here for what this test is based on: // https://github.com/tokio-rs/tokio/blob/75c07770bfbfea4e5fd914af819c741ed9c3fc36/tokio-util/tests/framed_write.rs#L69 const ITER: usize = 2 * 1024; let mut bi = bilateral! { Err(io::Error::new(io::ErrorKind::WouldBlock, "not ready")), Ok(b"".to_vec()), }; for i in 0..=ITER { let mut b = BytesMut::with_capacity(4); b.put_u32(i as u32); // Append to the end match bi.calls.back_mut().unwrap() { Ok(ref mut data) => { // Write in 2kb chunks if data.len() < ITER { data.extend_from_slice(&b[..]); continue; } // else fall through and create a new buffer } _ => unreachable!(), } // Push a new new chunk bi.calls.push_back(Ok(b[..].to_vec())); } assert_eq!(bi.calls.len(), 6); let mut framed = Framed::new(bi, U32); // Send 8KB. This fills up FramedWrite2 buffer let mut task = task::spawn(()); task.enter(|cx, _| { // Send 8KB. This fills up Framed buffer for i in 0..ITER { { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); assert!(assert_ready!(framed.poll_ready(cx)).is_ok()); } #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // write the buffer assert!(framed.start_send(i as u32).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Now we poll_ready which forces a flush. The bilateral pops the front message // and decides to block. assert!(framed.poll_ready(cx).is_pending()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // We poll again, forcing another flush, which this time succeeds // The whole 8KB buffer is flushed assert!(assert_ready!(framed.poll_ready(cx)).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Send more data. This matches the final message expected by the bilateral assert!(framed.start_send(ITER as u32).is_ok()); } { #[allow(unused_mut)] let mut framed = Pin::new(&mut framed); // Flush the rest of the buffer assert!(assert_ready!(framed.poll_flush(cx)).is_ok()); } // Ensure the mock is empty assert_eq!(0, Pin::new(&framed).get_ref().io_ref().calls.len()); }); }