*: Format with rustfmt (#2188)

Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
This commit is contained in:
Max Inden
2021-08-11 13:12:12 +02:00
committed by GitHub
parent 008561283e
commit f701b24ec0
171 changed files with 10051 additions and 7193 deletions

View File

@ -18,8 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeError};
use crate::{ConnectedPoint, Negotiated};
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeError, ProtocolName};
use futures::{future::Either, prelude::*};
use log::debug;
use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture};
@ -28,8 +28,12 @@ use std::{iter, mem, pin::Pin, task::Context, task::Poll};
pub use multistream_select::Version;
/// Applies an upgrade to the inbound and outbound direction of a connection or substream.
pub fn apply<C, U>(conn: C, up: U, cp: ConnectedPoint, v: Version)
-> Either<InboundUpgradeApply<C, U>, OutboundUpgradeApply<C, U>>
pub fn apply<C, U>(
conn: C,
up: U,
cp: ConnectedPoint,
v: Version,
) -> Either<InboundUpgradeApply<C, U>, OutboundUpgradeApply<C, U>>
where
C: AsyncRead + AsyncWrite + Unpin,
U: InboundUpgrade<Negotiated<C>> + OutboundUpgrade<Negotiated<C>>,
@ -47,10 +51,16 @@ where
C: AsyncRead + AsyncWrite + Unpin,
U: InboundUpgrade<Negotiated<C>>,
{
let iter = up.protocol_info().into_iter().map(NameWrap as fn(_) -> NameWrap<_>);
let iter = up
.protocol_info()
.into_iter()
.map(NameWrap as fn(_) -> NameWrap<_>);
let future = multistream_select::listener_select_proto(conn, iter);
InboundUpgradeApply {
inner: InboundUpgradeApplyState::Init { future, upgrade: up }
inner: InboundUpgradeApplyState::Init {
future,
upgrade: up,
},
}
}
@ -58,12 +68,18 @@ where
pub fn apply_outbound<C, U>(conn: C, up: U, v: Version) -> OutboundUpgradeApply<C, U>
where
C: AsyncRead + AsyncWrite + Unpin,
U: OutboundUpgrade<Negotiated<C>>
U: OutboundUpgrade<Negotiated<C>>,
{
let iter = up.protocol_info().into_iter().map(NameWrap as fn(_) -> NameWrap<_>);
let iter = up
.protocol_info()
.into_iter()
.map(NameWrap as fn(_) -> NameWrap<_>);
let future = multistream_select::dialer_select_proto(conn, iter, v);
OutboundUpgradeApply {
inner: OutboundUpgradeApplyState::Init { future, upgrade: up }
inner: OutboundUpgradeApplyState::Init {
future,
upgrade: up,
},
}
}
@ -71,9 +87,9 @@ where
pub struct InboundUpgradeApply<C, U>
where
C: AsyncRead + AsyncWrite + Unpin,
U: InboundUpgrade<Negotiated<C>>
U: InboundUpgrade<Negotiated<C>>,
{
inner: InboundUpgradeApplyState<C, U>
inner: InboundUpgradeApplyState<C, U>,
}
enum InboundUpgradeApplyState<C, U>
@ -86,9 +102,9 @@ where
upgrade: U,
},
Upgrade {
future: Pin<Box<U::Future>>
future: Pin<Box<U::Future>>,
},
Undefined
Undefined,
}
impl<C, U> Unpin for InboundUpgradeApply<C, U>
@ -108,36 +124,40 @@ where
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) {
InboundUpgradeApplyState::Init { mut future, upgrade } => {
InboundUpgradeApplyState::Init {
mut future,
upgrade,
} => {
let (info, io) = match Future::poll(Pin::new(&mut future), cx)? {
Poll::Ready(x) => x,
Poll::Pending => {
self.inner = InboundUpgradeApplyState::Init { future, upgrade };
return Poll::Pending
return Poll::Pending;
}
};
self.inner = InboundUpgradeApplyState::Upgrade {
future: Box::pin(upgrade.upgrade_inbound(io, info.0))
future: Box::pin(upgrade.upgrade_inbound(io, info.0)),
};
}
InboundUpgradeApplyState::Upgrade { mut future } => {
match Future::poll(Pin::new(&mut future), cx) {
Poll::Pending => {
self.inner = InboundUpgradeApplyState::Upgrade { future };
return Poll::Pending
return Poll::Pending;
}
Poll::Ready(Ok(x)) => {
debug!("Successfully applied negotiated protocol");
return Poll::Ready(Ok(x))
return Poll::Ready(Ok(x));
}
Poll::Ready(Err(e)) => {
debug!("Failed to apply negotiated protocol");
return Poll::Ready(Err(UpgradeError::Apply(e)))
return Poll::Ready(Err(UpgradeError::Apply(e)));
}
}
}
InboundUpgradeApplyState::Undefined =>
InboundUpgradeApplyState::Undefined => {
panic!("InboundUpgradeApplyState::poll called after completion")
}
}
}
}
@ -147,24 +167,24 @@ where
pub struct OutboundUpgradeApply<C, U>
where
C: AsyncRead + AsyncWrite + Unpin,
U: OutboundUpgrade<Negotiated<C>>
U: OutboundUpgrade<Negotiated<C>>,
{
inner: OutboundUpgradeApplyState<C, U>
inner: OutboundUpgradeApplyState<C, U>,
}
enum OutboundUpgradeApplyState<C, U>
where
C: AsyncRead + AsyncWrite + Unpin,
U: OutboundUpgrade<Negotiated<C>>
U: OutboundUpgrade<Negotiated<C>>,
{
Init {
future: DialerSelectFuture<C, NameWrapIter<<U::InfoIter as IntoIterator>::IntoIter>>,
upgrade: U
upgrade: U,
},
Upgrade {
future: Pin<Box<U::Future>>
future: Pin<Box<U::Future>>,
},
Undefined
Undefined,
}
impl<C, U> Unpin for OutboundUpgradeApply<C, U>
@ -184,27 +204,30 @@ where
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) {
OutboundUpgradeApplyState::Init { mut future, upgrade } => {
OutboundUpgradeApplyState::Init {
mut future,
upgrade,
} => {
let (info, connection) = match Future::poll(Pin::new(&mut future), cx)? {
Poll::Ready(x) => x,
Poll::Pending => {
self.inner = OutboundUpgradeApplyState::Init { future, upgrade };
return Poll::Pending
return Poll::Pending;
}
};
self.inner = OutboundUpgradeApplyState::Upgrade {
future: Box::pin(upgrade.upgrade_outbound(connection, info.0))
future: Box::pin(upgrade.upgrade_outbound(connection, info.0)),
};
}
OutboundUpgradeApplyState::Upgrade { mut future } => {
match Future::poll(Pin::new(&mut future), cx) {
Poll::Pending => {
self.inner = OutboundUpgradeApplyState::Upgrade { future };
return Poll::Pending
return Poll::Pending;
}
Poll::Ready(Ok(x)) => {
debug!("Successfully applied negotiated protocol");
return Poll::Ready(Ok(x))
return Poll::Ready(Ok(x));
}
Poll::Ready(Err(e)) => {
debug!("Failed to apply negotiated protocol");
@ -212,8 +235,9 @@ where
}
}
}
OutboundUpgradeApplyState::Undefined =>
OutboundUpgradeApplyState::Undefined => {
panic!("OutboundUpgradeApplyState::poll called after completion")
}
}
}
}
@ -230,4 +254,3 @@ impl<N: ProtocolName> AsRef<[u8]> for NameWrap<N> {
self.0.protocol_name()
}
}

View File

@ -19,29 +19,32 @@
// DEALINGS IN THE SOFTWARE.
use crate::{
either::{EitherOutput, EitherError, EitherFuture2, EitherName},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
either::{EitherError, EitherFuture2, EitherName, EitherOutput},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo},
};
/// A type to represent two possible upgrade types (inbound or outbound).
#[derive(Debug, Clone)]
pub enum EitherUpgrade<A, B> { A(A), B(B) }
pub enum EitherUpgrade<A, B> {
A(A),
B(B),
}
impl<A, B> UpgradeInfo for EitherUpgrade<A, B>
where
A: UpgradeInfo,
B: UpgradeInfo
B: UpgradeInfo,
{
type Info = EitherName<A::Info, B::Info>;
type InfoIter = EitherIter<
<A::InfoIter as IntoIterator>::IntoIter,
<B::InfoIter as IntoIterator>::IntoIter
<B::InfoIter as IntoIterator>::IntoIter,
>;
fn protocol_info(&self) -> Self::InfoIter {
match self {
EitherUpgrade::A(a) => EitherIter::A(a.protocol_info().into_iter()),
EitherUpgrade::B(b) => EitherIter::B(b.protocol_info().into_iter())
EitherUpgrade::B(b) => EitherIter::B(b.protocol_info().into_iter()),
}
}
}
@ -57,9 +60,13 @@ where
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
match (self, info) {
(EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_inbound(sock, info)),
(EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_inbound(sock, info)),
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound")
(EitherUpgrade::A(a), EitherName::A(info)) => {
EitherFuture2::A(a.upgrade_inbound(sock, info))
}
(EitherUpgrade::B(b), EitherName::B(info)) => {
EitherFuture2::B(b.upgrade_inbound(sock, info))
}
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound"),
}
}
}
@ -75,36 +82,42 @@ where
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
match (self, info) {
(EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_outbound(sock, info)),
(EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_outbound(sock, info)),
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound")
(EitherUpgrade::A(a), EitherName::A(info)) => {
EitherFuture2::A(a.upgrade_outbound(sock, info))
}
(EitherUpgrade::B(b), EitherName::B(info)) => {
EitherFuture2::B(b.upgrade_outbound(sock, info))
}
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound"),
}
}
}
/// A type to represent two possible `Iterator` types.
#[derive(Debug, Clone)]
pub enum EitherIter<A, B> { A(A), B(B) }
pub enum EitherIter<A, B> {
A(A),
B(B),
}
impl<A, B> Iterator for EitherIter<A, B>
where
A: Iterator,
B: Iterator
B: Iterator,
{
type Item = EitherName<A::Item, B::Item>;
fn next(&mut self) -> Option<Self::Item> {
match self {
EitherIter::A(a) => a.next().map(EitherName::A),
EitherIter::B(b) => b.next().map(EitherName::B)
EitherIter::B(b) => b.next().map(EitherName::B),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
EitherIter::A(a) => a.size_hint(),
EitherIter::B(b) => b.size_hint()
EitherIter::B(b) => b.size_hint(),
}
}
}

View File

@ -33,7 +33,7 @@ pub enum UpgradeError<E> {
impl<E> UpgradeError<E> {
pub fn map_err<F, T>(self, f: F) -> UpgradeError<T>
where
F: FnOnce(E) -> T
F: FnOnce(E) -> T,
{
match self {
UpgradeError::Select(e) => UpgradeError::Select(e),
@ -43,7 +43,7 @@ impl<E> UpgradeError<E> {
pub fn into_err<T>(self) -> UpgradeError<T>
where
T: From<E>
T: From<E>,
{
self.map_err(Into::into)
}
@ -51,7 +51,7 @@ impl<E> UpgradeError<E> {
impl<E> fmt::Display for UpgradeError<E>
where
E: fmt::Display
E: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@ -63,7 +63,7 @@ where
impl<E> std::error::Error for UpgradeError<E>
where
E: std::error::Error + 'static
E: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
@ -78,4 +78,3 @@ impl<E> From<NegotiationError> for UpgradeError<E> {
UpgradeError::Select(e)
}
}

View File

@ -18,7 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::{Endpoint, upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeInfo}};
use crate::{
upgrade::{InboundUpgrade, OutboundUpgrade, ProtocolName, UpgradeInfo},
Endpoint,
};
use futures::prelude::*;
use std::iter;

View File

@ -24,7 +24,10 @@ use std::{pin::Pin, task::Context, task::Poll};
/// Wraps around an upgrade and applies a closure to the output.
#[derive(Debug, Clone)]
pub struct MapInboundUpgrade<U, F> { upgrade: U, fun: F }
pub struct MapInboundUpgrade<U, F> {
upgrade: U,
fun: F,
}
impl<U, F> MapInboundUpgrade<U, F> {
pub fn new(upgrade: U, fun: F) -> Self {
@ -34,7 +37,7 @@ impl<U, F> MapInboundUpgrade<U, F> {
impl<U, F> UpgradeInfo for MapInboundUpgrade<U, F>
where
U: UpgradeInfo
U: UpgradeInfo,
{
type Info = U::Info;
type InfoIter = U::InfoIter;
@ -47,7 +50,7 @@ where
impl<C, U, F, T> InboundUpgrade<C> for MapInboundUpgrade<U, F>
where
U: InboundUpgrade<C>,
F: FnOnce(U::Output) -> T
F: FnOnce(U::Output) -> T,
{
type Output = T;
type Error = U::Error;
@ -56,7 +59,7 @@ where
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
MapFuture {
inner: self.upgrade.upgrade_inbound(sock, info),
map: Some(self.fun)
map: Some(self.fun),
}
}
}
@ -76,7 +79,10 @@ where
/// Wraps around an upgrade and applies a closure to the output.
#[derive(Debug, Clone)]
pub struct MapOutboundUpgrade<U, F> { upgrade: U, fun: F }
pub struct MapOutboundUpgrade<U, F> {
upgrade: U,
fun: F,
}
impl<U, F> MapOutboundUpgrade<U, F> {
pub fn new(upgrade: U, fun: F) -> Self {
@ -86,7 +92,7 @@ impl<U, F> MapOutboundUpgrade<U, F> {
impl<U, F> UpgradeInfo for MapOutboundUpgrade<U, F>
where
U: UpgradeInfo
U: UpgradeInfo,
{
type Info = U::Info;
type InfoIter = U::InfoIter;
@ -112,7 +118,7 @@ where
impl<C, U, F, T> OutboundUpgrade<C> for MapOutboundUpgrade<U, F>
where
U: OutboundUpgrade<C>,
F: FnOnce(U::Output) -> T
F: FnOnce(U::Output) -> T,
{
type Output = T;
type Error = U::Error;
@ -121,14 +127,17 @@ where
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
MapFuture {
inner: self.upgrade.upgrade_outbound(sock, info),
map: Some(self.fun)
map: Some(self.fun),
}
}
}
/// Wraps around an upgrade and applies a closure to the error.
#[derive(Debug, Clone)]
pub struct MapInboundUpgradeErr<U, F> { upgrade: U, fun: F }
pub struct MapInboundUpgradeErr<U, F> {
upgrade: U,
fun: F,
}
impl<U, F> MapInboundUpgradeErr<U, F> {
pub fn new(upgrade: U, fun: F) -> Self {
@ -138,7 +147,7 @@ impl<U, F> MapInboundUpgradeErr<U, F> {
impl<U, F> UpgradeInfo for MapInboundUpgradeErr<U, F>
where
U: UpgradeInfo
U: UpgradeInfo,
{
type Info = U::Info;
type InfoIter = U::InfoIter;
@ -151,7 +160,7 @@ where
impl<C, U, F, T> InboundUpgrade<C> for MapInboundUpgradeErr<U, F>
where
U: InboundUpgrade<C>,
F: FnOnce(U::Error) -> T
F: FnOnce(U::Error) -> T,
{
type Output = U::Output;
type Error = T;
@ -160,7 +169,7 @@ where
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
MapErrFuture {
fut: self.upgrade.upgrade_inbound(sock, info),
fun: Some(self.fun)
fun: Some(self.fun),
}
}
}
@ -180,7 +189,10 @@ where
/// Wraps around an upgrade and applies a closure to the error.
#[derive(Debug, Clone)]
pub struct MapOutboundUpgradeErr<U, F> { upgrade: U, fun: F }
pub struct MapOutboundUpgradeErr<U, F> {
upgrade: U,
fun: F,
}
impl<U, F> MapOutboundUpgradeErr<U, F> {
pub fn new(upgrade: U, fun: F) -> Self {
@ -190,7 +202,7 @@ impl<U, F> MapOutboundUpgradeErr<U, F> {
impl<U, F> UpgradeInfo for MapOutboundUpgradeErr<U, F>
where
U: UpgradeInfo
U: UpgradeInfo,
{
type Info = U::Info;
type InfoIter = U::InfoIter;
@ -203,7 +215,7 @@ where
impl<C, U, F, T> OutboundUpgrade<C> for MapOutboundUpgradeErr<U, F>
where
U: OutboundUpgrade<C>,
F: FnOnce(U::Error) -> T
F: FnOnce(U::Error) -> T,
{
type Output = U::Output;
type Error = T;
@ -212,14 +224,14 @@ where
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
MapErrFuture {
fut: self.upgrade.upgrade_outbound(sock, info),
fun: Some(self.fun)
fun: Some(self.fun),
}
}
}
impl<C, U, F> InboundUpgrade<C> for MapOutboundUpgradeErr<U, F>
where
U: InboundUpgrade<C>
U: InboundUpgrade<C>,
{
type Output = U::Output;
type Error = U::Error;
@ -283,4 +295,3 @@ where
}
}
}

View File

@ -112,8 +112,4 @@ where
}
}
impl<T> ExactSizeIterator for Iter<T>
where
T: ExactSizeIterator
{
}
impl<T> ExactSizeIterator for Iter<T> where T: ExactSizeIterator {}

View File

@ -19,8 +19,8 @@
// DEALINGS IN THE SOFTWARE.
use crate::{
either::{EitherOutput, EitherError, EitherFuture2, EitherName},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
either::{EitherError, EitherFuture2, EitherName, EitherOutput},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo},
};
/// Upgrade that combines two upgrades into one. Supports all the protocols supported by either
@ -42,16 +42,19 @@ impl<A, B> SelectUpgrade<A, B> {
impl<A, B> UpgradeInfo for SelectUpgrade<A, B>
where
A: UpgradeInfo,
B: UpgradeInfo
B: UpgradeInfo,
{
type Info = EitherName<A::Info, B::Info>;
type InfoIter = InfoIterChain<
<A::InfoIter as IntoIterator>::IntoIter,
<B::InfoIter as IntoIterator>::IntoIter
<B::InfoIter as IntoIterator>::IntoIter,
>;
fn protocol_info(&self) -> Self::InfoIter {
InfoIterChain(self.0.protocol_info().into_iter(), self.1.protocol_info().into_iter())
InfoIterChain(
self.0.protocol_info().into_iter(),
self.1.protocol_info().into_iter(),
)
}
}
@ -67,7 +70,7 @@ where
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
match info {
EitherName::A(info) => EitherFuture2::A(self.0.upgrade_inbound(sock, info)),
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_inbound(sock, info))
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_inbound(sock, info)),
}
}
}
@ -84,7 +87,7 @@ where
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
match info {
EitherName::A(info) => EitherFuture2::A(self.0.upgrade_outbound(sock, info)),
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_outbound(sock, info))
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_outbound(sock, info)),
}
}
}
@ -96,16 +99,16 @@ pub struct InfoIterChain<A, B>(A, B);
impl<A, B> Iterator for InfoIterChain<A, B>
where
A: Iterator,
B: Iterator
B: Iterator,
{
type Item = EitherName<A::Item, B::Item>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(info) = self.0.next() {
return Some(EitherName::A(info))
return Some(EitherName::A(info));
}
if let Some(info) = self.1.next() {
return Some(EitherName::B(info))
return Some(EitherName::B(info));
}
None
}
@ -117,4 +120,3 @@ where
(min1.saturating_add(min2), max)
}
}

View File

@ -29,9 +29,10 @@ use std::{error, fmt, io};
///
/// > **Note**: Prepends a variable-length prefix indicate the length of the message. This is
/// > compatible with what [`read_length_prefixed`] expects.
pub async fn write_length_prefixed(socket: &mut (impl AsyncWrite + Unpin), data: impl AsRef<[u8]>)
-> Result<(), io::Error>
{
pub async fn write_length_prefixed(
socket: &mut (impl AsyncWrite + Unpin),
data: impl AsRef<[u8]>,
) -> Result<(), io::Error> {
write_varint(socket, data.as_ref().len()).await?;
socket.write_all(data.as_ref()).await?;
socket.flush().await?;
@ -44,11 +45,15 @@ pub async fn write_length_prefixed(socket: &mut (impl AsyncWrite + Unpin), data:
/// > **Note**: Prepends a variable-length prefix indicate the length of the message. This is
/// > compatible with what `read_one` expects.
///
#[deprecated(since = "0.29.0", note = "Use `write_length_prefixed` instead. You will need to manually close the stream using `socket.close().await`.")]
#[deprecated(
since = "0.29.0",
note = "Use `write_length_prefixed` instead. You will need to manually close the stream using `socket.close().await`."
)]
#[allow(dead_code)]
pub async fn write_one(socket: &mut (impl AsyncWrite + Unpin), data: impl AsRef<[u8]>)
-> Result<(), io::Error>
{
pub async fn write_one(
socket: &mut (impl AsyncWrite + Unpin),
data: impl AsRef<[u8]>,
) -> Result<(), io::Error> {
write_varint(socket, data.as_ref().len()).await?;
socket.write_all(data.as_ref()).await?;
socket.close().await?;
@ -61,9 +66,10 @@ pub async fn write_one(socket: &mut (impl AsyncWrite + Unpin), data: impl AsRef<
/// > compatible with what `read_one` expects.
#[deprecated(since = "0.29.0", note = "Use `write_length_prefixed` instead.")]
#[allow(dead_code)]
pub async fn write_with_len_prefix(socket: &mut (impl AsyncWrite + Unpin), data: impl AsRef<[u8]>)
-> Result<(), io::Error>
{
pub async fn write_with_len_prefix(
socket: &mut (impl AsyncWrite + Unpin),
data: impl AsRef<[u8]>,
) -> Result<(), io::Error> {
write_varint(socket, data.as_ref().len()).await?;
socket.write_all(data.as_ref()).await?;
socket.flush().await?;
@ -73,9 +79,10 @@ pub async fn write_with_len_prefix(socket: &mut (impl AsyncWrite + Unpin), data:
/// Writes a variable-length integer to the `socket`.
///
/// > **Note**: Does **NOT** flush the socket.
pub async fn write_varint(socket: &mut (impl AsyncWrite + Unpin), len: usize)
-> Result<(), io::Error>
{
pub async fn write_varint(
socket: &mut (impl AsyncWrite + Unpin),
len: usize,
) -> Result<(), io::Error> {
let mut len_data = unsigned_varint::encode::usize_buffer();
let encoded_len = unsigned_varint::encode::usize(len, &mut len_data).len();
socket.write_all(&len_data[..encoded_len]).await?;
@ -95,7 +102,7 @@ pub async fn read_varint(socket: &mut (impl AsyncRead + Unpin)) -> Result<usize,
let mut buffer_len = 0;
loop {
match socket.read(&mut buffer[buffer_len..buffer_len+1]).await? {
match socket.read(&mut buffer[buffer_len..buffer_len + 1]).await? {
0 => {
// Reaching EOF before finishing to read the length is an error, unless the EOF is
// at the very beginning of the substream, in which case we assume that the data is
@ -116,7 +123,7 @@ pub async fn read_varint(socket: &mut (impl AsyncRead + Unpin)) -> Result<usize,
Err(unsigned_varint::decode::Error::Overflow) => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"overflow in variable-length integer"
"overflow in variable-length integer",
));
}
// TODO: why do we have a `__Nonexhaustive` variant in the error? I don't know how to process it
@ -134,11 +141,19 @@ pub async fn read_varint(socket: &mut (impl AsyncRead + Unpin)) -> Result<usize,
///
/// > **Note**: Assumes that a variable-length prefix indicates the length of the message. This is
/// > compatible with what [`write_length_prefixed`] does.
pub async fn read_length_prefixed(socket: &mut (impl AsyncRead + Unpin), max_size: usize) -> io::Result<Vec<u8>>
{
pub async fn read_length_prefixed(
socket: &mut (impl AsyncRead + Unpin),
max_size: usize,
) -> io::Result<Vec<u8>> {
let len = read_varint(socket).await?;
if len > max_size {
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("Received data size ({} bytes) exceeds maximum ({} bytes)", len, max_size)))
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Received data size ({} bytes) exceeds maximum ({} bytes)",
len, max_size
),
));
}
let mut buf = vec![0; len];
@ -157,9 +172,10 @@ pub async fn read_length_prefixed(socket: &mut (impl AsyncRead + Unpin), max_siz
/// > compatible with what `write_one` does.
#[deprecated(since = "0.29.0", note = "Use `read_length_prefixed` instead.")]
#[allow(dead_code, deprecated)]
pub async fn read_one(socket: &mut (impl AsyncRead + Unpin), max_size: usize)
-> Result<Vec<u8>, ReadOneError>
{
pub async fn read_one(
socket: &mut (impl AsyncRead + Unpin),
max_size: usize,
) -> Result<Vec<u8>, ReadOneError> {
let len = read_varint(socket).await?;
if len > max_size {
return Err(ReadOneError::TooLarge {
@ -175,7 +191,10 @@ pub async fn read_one(socket: &mut (impl AsyncRead + Unpin), max_size: usize)
/// Error while reading one message.
#[derive(Debug)]
#[deprecated(since = "0.29.0", note = "Use `read_length_prefixed` instead of `read_one` to avoid depending on this type.")]
#[deprecated(
since = "0.29.0",
note = "Use `read_length_prefixed` instead of `read_one` to avoid depending on this type."
)]
pub enum ReadOneError {
/// Error on the socket.
Io(std::io::Error),
@ -239,7 +258,7 @@ mod tests {
}
// TODO: rewrite these tests
/*
/*
#[test]
fn read_one_works() {
let original_data = (0..rand::random::<usize>() % 10_000)