From 4c997ddbbcc731e2adffed0bfcffd181c1d4835e Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 00:01:36 -0500 Subject: [PATCH 1/7] break a lot of stuff to try and see what needs to be done for no_std --- src/agent.rs | 6 ++---- src/body/brotli.rs | 2 -- src/body/build.rs | 6 +++--- src/body/charset.rs | 2 -- src/body/gzip.rs | 31 ++++++++++++++++++++++-------- src/body/limit.rs | 2 -- src/body/lossy.rs | 4 ++-- src/body/mod.rs | 11 ++++++----- src/config.rs | 7 +++---- src/cookies.rs | 4 ---- src/error.rs | 2 +- src/lib.rs | 12 ++++++++---- src/middleware.rs | 5 +++-- src/pool.rs | 7 +++---- src/proxy.rs | 5 +---- src/query.rs | 21 +++++++++----------- src/request.rs | 16 +++++++-------- src/run.rs | 5 +---- src/send_body.rs | 7 +++---- src/timings.rs | 2 -- src/tls/cert.rs | 3 --- src/tls/mod.rs | 4 +--- src/tls/native_tls.rs | 5 ----- src/tls/rustls.rs | 10 +++++----- src/unversioned/resolver.rs | 8 +++----- src/unversioned/transport/buf.rs | 4 +++- src/unversioned/transport/chain.rs | 2 ++ src/unversioned/transport/io.rs | 2 -- src/unversioned/transport/mod.rs | 2 +- src/unversioned/transport/socks.rs | 5 ----- src/unversioned/transport/tcp.rs | 4 ---- src/unversioned/transport/test.rs | 7 ------- src/unversioned/transport/time.rs | 4 ---- src/util.rs | 7 ++----- 34 files changed, 93 insertions(+), 131 deletions(-) diff --git a/src/agent.rs b/src/agent.rs index 99968c66..d99d32c4 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1,8 +1,6 @@ -use std::convert::TryFrom; -use std::fmt::Debug; -use std::sync::Arc; - +use alloc::sync::Arc; use http::{Method, Request, Response, Uri}; +use core::convert::TryFrom; use crate::body::Body; use crate::config::typestate::{AgentScope, HttpCrateScope}; diff --git a/src/body/brotli.rs b/src/body/brotli.rs index 8379619f..71063233 100644 --- a/src/body/brotli.rs +++ b/src/body/brotli.rs @@ -1,5 +1,3 @@ -use std::io; - use brotli_decompressor::Decompressor; use crate::Error; diff --git a/src/body/build.rs b/src/body/build.rs index 6dbd8807..9f49debc 100644 --- a/src/body/build.rs +++ b/src/body/build.rs @@ -1,5 +1,4 @@ -use std::io::{self, Cursor}; -use std::sync::Arc; +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use ureq_proto::BodyMode; @@ -112,7 +111,8 @@ impl BodyBuilder { let len = self.limit.unwrap_or(data.len() as u64); self.info.body_mode = BodyMode::LengthDelimited(len); - self.reader(Cursor::new(data)) + //self.reader(Cursor::new(data)) + todo!() } /// Creates a body from a streaming reader. diff --git a/src/body/charset.rs b/src/body/charset.rs index bf92ad20..2ad1de9d 100644 --- a/src/body/charset.rs +++ b/src/body/charset.rs @@ -1,6 +1,4 @@ use encoding_rs::{Decoder, Encoder, Encoding}; -use std::fmt; -use std::io::{self, BufRead, BufReader}; use crate::util::ConsumeBuf; diff --git a/src/body/gzip.rs b/src/body/gzip.rs index 0cf0511b..b646de9a 100644 --- a/src/body/gzip.rs +++ b/src/body/gzip.rs @@ -1,22 +1,37 @@ -use std::io; - use flate2::read::MultiGzDecoder; use crate::Error; +#[cfg(not(feature = "std"))] +use core::result; +#[cfg(not(feature = "std"))] +use core::convert::From; +#[cfg(feature = "std")] +use std::io; + +// Replace io::Read with a custom trait for no_std +pub trait Read { + fn read(&mut self, buf: &mut [u8]) -> result::Result; +} + +#[cfg(feature = "std")] +impl Read for R { + fn read(&mut self, buf: &mut [u8]) -> result::Result { + io::Read::read(self, buf).map_err(|e| Error::Decompress("gzip", e)) + } +} + pub(crate) struct GzipDecoder(MultiGzDecoder); -impl GzipDecoder { +impl GzipDecoder { pub fn new(reader: R) -> Self { GzipDecoder(MultiGzDecoder::new(reader)) } } -impl io::Read for GzipDecoder { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0 - .read(buf) - .map_err(|e| Error::Decompress("gzip", e).into_io()) +impl Read for GzipDecoder { + fn read(&mut self, buf: &mut [u8]) -> result::Result { + self.0.read(buf) } } diff --git a/src/body/limit.rs b/src/body/limit.rs index f7b18fff..b875c535 100644 --- a/src/body/limit.rs +++ b/src/body/limit.rs @@ -1,5 +1,3 @@ -use std::io; - use crate::Error; pub(crate) struct LimitReader { diff --git a/src/body/lossy.rs b/src/body/lossy.rs index 7bdd1bd3..a2abf3a5 100644 --- a/src/body/lossy.rs +++ b/src/body/lossy.rs @@ -1,5 +1,3 @@ -use std::io; - use utf8::DecodeError; use crate::util::ConsumeBuf; @@ -101,6 +99,8 @@ impl io::Read for LossyUtf8Reader { mod test { use std::io::Read; + use alloc::string::String; + use super::*; fn do_reader<'a>(bytes: &'a mut [&'a [u8]]) -> String { diff --git a/src/body/mod.rs b/src/body/mod.rs index b1008f96..79fb6aa1 100644 --- a/src/body/mod.rs +++ b/src/body/mod.rs @@ -1,7 +1,10 @@ -use std::fmt; -use std::io; -use std::sync::Arc; +use core::fmt; +use alloc::boxed::Box; +use alloc::string::String; +use alloc::sync::Arc; + +use alloc::vec::Vec; pub use build::BodyBuilder; use ureq_proto::BodyMode; @@ -392,7 +395,6 @@ impl<'a> BodyWithConfig<'a> { /// Read into string. pub fn read_to_string(self) -> Result { - use std::io::Read; let mut reader = self.do_build(); let mut buf = String::new(); reader.read_to_string(&mut buf)?; @@ -401,7 +403,6 @@ impl<'a> BodyWithConfig<'a> { /// Read into vector. pub fn read_to_vec(self) -> Result, Error> { - use std::io::Read; let mut reader = self.do_build(); let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; diff --git a/src/config.rs b/src/config.rs index 414833fd..1359990b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,10 +1,9 @@ //! Agent configuration -use std::fmt; -use std::net::SocketAddr; -use std::sync::Arc; -use std::time::Duration; +use core::time::Duration; +use alloc::string::String; +use alloc::sync::Arc; use http::Uri; use crate::http; diff --git a/src/cookies.rs b/src/cookies.rs index 0e0a7a9c..0864d6c6 100644 --- a/src/cookies.rs +++ b/src/cookies.rs @@ -1,7 +1,3 @@ -use std::borrow::Cow; -use std::fmt; -use std::sync::{Mutex, MutexGuard}; - use cookie_store::CookieStore; use http::Uri; diff --git a/src/error.rs b/src/error.rs index a6c5d82d..932ad1b0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,4 @@ -use std::{fmt, io}; +use alloc::string::String; use crate::http; use crate::Timeout; diff --git a/src/lib.rs b/src/lib.rs index 099dca14..1ad327da 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -439,16 +439,22 @@ //! [rustls-platform-verifier]: https://crates.io/crates/rustls-platform-verifier //! [webpki-roots]: https://crates.io/crates/webpki-roots +#![no_std] #![forbid(unsafe_code)] #![warn(clippy::all)] #![deny(missing_docs)] // I don't think elided lifetimes help in understanding the code. #![allow(clippy::needless_lifetimes)] +extern crate alloc; + +#[cfg(feature = "std")] +extern crate std; + #[macro_use] extern crate log; -use std::convert::TryFrom; +use core::convert::TryFrom; /// Re-exported http-crate. pub use ureq_proto::http; @@ -544,8 +550,6 @@ mk_method!(trace, TRACE, WithoutBody); #[cfg(test)] pub(crate) mod test { - use std::io; - use assert_no_alloc::AllocDisabler; use config::Config; use once_cell::sync::Lazy; @@ -833,7 +837,7 @@ pub(crate) mod test { is_send(get("https://example.test")); is_sync(get("https://example.test")); - let data = vec![0_u8, 1, 2, 3, 4]; + let data = alloc::vec![0_u8, 1, 2, 3, 4]; // Response via ResponseBuilder is_send(post("https://example.test").send(&data)); diff --git a/src/middleware.rs b/src/middleware.rs index 70da345e..358495f1 100644 --- a/src/middleware.rs +++ b/src/middleware.rs @@ -1,7 +1,8 @@ //! Chained interception to modify the request or response. -use std::fmt; -use std::sync::Arc; +use alloc::boxed::Box; +use alloc::sync::Arc; +use alloc::vec::Vec; use crate::http; use crate::run::run; diff --git a/src/pool.rs b/src/pool.rs index 518a3957..5f1dc5fa 100644 --- a/src/pool.rs +++ b/src/pool.rs @@ -1,7 +1,6 @@ -use std::collections::VecDeque; -use std::fmt; -use std::sync::{Arc, Mutex, Weak}; - +use alloc::boxed::Box; +use alloc::collections::vec_deque::VecDeque; +use alloc::sync::Arc; use http::uri::{Authority, Scheme}; use http::Uri; diff --git a/src/proxy.rs b/src/proxy.rs index 1f8effb0..ca497bc6 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -1,9 +1,6 @@ +use alloc::boxed::Box; use base64::prelude::BASE64_STANDARD; use base64::Engine; -use std::convert::{TryFrom, TryInto}; -use std::fmt; -use std::io::Write; -use std::sync::Arc; use ureq_proto::parser::try_parse_response; use http::{StatusCode, Uri}; diff --git a/src/query.rs b/src/query.rs index 9c48b9d2..b691aae1 100644 --- a/src/query.rs +++ b/src/query.rs @@ -1,9 +1,4 @@ -use std::borrow::Cow; -use std::fmt; -use std::iter::Enumerate; -use std::ops::Deref; -use std::str::Chars; - +use alloc::{borrow::Cow, string::String}; use percent_encoding::utf8_percent_encode; #[derive(Clone)] @@ -108,6 +103,8 @@ impl<'a> PartialEq for QueryParam<'a> { #[cfg(test)] mod test { + use alloc::vec::Vec; + use super::*; use crate::http::Uri; @@ -137,11 +134,11 @@ mod test { #[test] fn parse_query_string() { assert_eq!(parse_query_params("").next(), None); - assert_eq!(p("&"), vec![""]); - assert_eq!(p("="), vec!["="]); - assert_eq!(p("&="), vec!["", "="]); - assert_eq!(p("foo=bar"), vec!["foo=bar"]); - assert_eq!(p("foo=bar&"), vec!["foo=bar"]); - assert_eq!(p("foo=bar&foo2=bar2"), vec!["foo=bar", "foo2=bar2"]); + assert_eq!(p("&"), alloc::vec![""]); + assert_eq!(p("="), alloc::vec!["="]); + assert_eq!(p("&="), alloc::vec!["", "="]); + assert_eq!(p("foo=bar"), alloc::vec!["foo=bar"]); + assert_eq!(p("foo=bar&"), alloc::vec!["foo=bar"]); + assert_eq!(p("foo=bar&foo2=bar2"), alloc::vec!["foo=bar", "foo2=bar2"]); } } diff --git a/src/request.rs b/src/request.rs index 285bee7e..c8f82fd0 100644 --- a/src/request.rs +++ b/src/request.rs @@ -1,8 +1,8 @@ -use std::convert::TryFrom; -use std::fmt; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; +use core::convert::TryFrom; +use core::marker::PhantomData; +use alloc::boxed::Box; +use alloc::vec::Vec; use http::{HeaderName, HeaderValue, Method, Request, Response, Uri, Version}; use crate::body::Body; @@ -222,7 +222,7 @@ impl RequestBuilder { Self { agent, builder: Request::builder().method(method).uri(uri), - query_extra: vec![], + query_extra: alloc::vec![], dummy_config: None, _ph: PhantomData, } @@ -284,7 +284,7 @@ impl RequestBuilder { Self { agent, builder: Request::builder().method(method).uri(uri), - query_extra: vec![], + query_extra: alloc::vec![], dummy_config: None, _ph: PhantomData, } @@ -569,7 +569,7 @@ mod test { let amended = amend_request_query( request, - vec![ + alloc::vec![ QueryParam::new_key_value("x", "z"), QueryParam::new_key_value("ab", "cde"), ] @@ -588,7 +588,7 @@ mod test { let amended = amend_request_query( request, - vec![QueryParam::new_key_value("ab", "cde")].into_iter(), + alloc::vec![QueryParam::new_key_value("ab", "cde")].into_iter(), ); assert_eq!(amended.uri(), "https://foo.bar/path?x=z&ab=cde"); diff --git a/src/run.rs b/src/run.rs index bf9d29c1..aac5047c 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,6 +1,3 @@ -use std::sync::Arc; -use std::{io, mem}; - use http::uri::Scheme; use http::{header, HeaderValue, Request, Response, Uri}; use once_cell::sync::Lazy; @@ -642,7 +639,7 @@ impl BodyHandler { } fn consume_redirect_body(&mut self) -> Result, Error> { - let mut buf = vec![0; 1024]; + let mut buf = alloc::vec![0; 1024]; loop { let amount = self.do_read(&mut buf)?; if amount == 0 { diff --git a/src/send_body.rs b/src/send_body.rs index 7749c987..695b90e0 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -1,7 +1,3 @@ -use std::fs::File; -use std::io::{self, Read, Stdin}; -use std::net::TcpStream; - use crate::body::{Body, BodyReader}; use crate::http; use crate::util::private::Private; @@ -76,6 +72,9 @@ impl<'a> SendBody<'a> { } } +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; use http::Response; use ureq_proto::BodyMode; diff --git a/src/timings.rs b/src/timings.rs index d21c0f24..63d94c71 100644 --- a/src/timings.rs +++ b/src/timings.rs @@ -1,5 +1,3 @@ -use std::fmt; -use std::sync::Arc; use ureq_proto::ArrayVec; use crate::config::Timeouts; diff --git a/src/tls/cert.rs b/src/tls/cert.rs index 75b5671a..ee56fc01 100644 --- a/src/tls/cert.rs +++ b/src/tls/cert.rs @@ -1,6 +1,3 @@ -use std::borrow::Cow; -use std::fmt; - use crate::Error; /// An X509 certificate for a server or a client. diff --git a/src/tls/mod.rs b/src/tls/mod.rs index dd21cb18..6b59b57e 100644 --- a/src/tls/mod.rs +++ b/src/tls/mod.rs @@ -1,9 +1,7 @@ //! TLS for handling `https`. -use std::fmt; -use std::sync::Arc; - mod cert; +use alloc::{sync::Arc, vec::Vec}; pub use cert::{parse_pem, Certificate, PemItem, PrivateKey}; #[cfg(feature = "rustls")] diff --git a/src/tls/native_tls.rs b/src/tls/native_tls.rs index ff340349..1ecb6420 100644 --- a/src/tls/native_tls.rs +++ b/src/tls/native_tls.rs @@ -1,8 +1,3 @@ -use std::convert::TryFrom; -use std::fmt; -use std::io::{Read, Write}; -use std::sync::Arc; - use crate::tls::{RootCerts, TlsProvider}; use crate::{transport::*, Error}; use der::pem::LineEnding; diff --git a/src/tls/rustls.rs b/src/tls/rustls.rs index 0b89635b..78557d0a 100644 --- a/src/tls/rustls.rs +++ b/src/tls/rustls.rs @@ -1,8 +1,8 @@ -use std::convert::TryInto; -use std::fmt; -use std::io::{Read, Write}; -use std::sync::Arc; +use core::fmt; +use alloc::boxed::Box; +use alloc::sync::Arc; +use alloc::vec::Vec; use once_cell::sync::OnceCell; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned, ALL_VERSIONS}; @@ -242,7 +242,7 @@ impl ServerCertVerifier for DisabledVerifier { } fn supported_verify_schemes(&self) -> Vec { - vec![ + alloc::vec![ rustls::SignatureScheme::RSA_PKCS1_SHA1, rustls::SignatureScheme::RSA_PKCS1_SHA256, rustls::SignatureScheme::RSA_PKCS1_SHA384, diff --git a/src/unversioned/resolver.rs b/src/unversioned/resolver.rs index 77f77534..47a74258 100644 --- a/src/unversioned/resolver.rs +++ b/src/unversioned/resolver.rs @@ -10,12 +10,10 @@ //! //! In some situations it might be desirable to not do this lookup, or to use another system //! than DNS for it. -use std::fmt::{self, Debug}; -use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs}; -use std::sync::mpsc::{self, RecvTimeoutError}; -use std::thread::{self}; -use std::vec::IntoIter; +use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4}; + +use alloc::string::String; use http::uri::{Authority, Scheme}; use http::Uri; diff --git a/src/unversioned/transport/buf.rs b/src/unversioned/transport/buf.rs index d25035db..38308ab9 100644 --- a/src/unversioned/transport/buf.rs +++ b/src/unversioned/transport/buf.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + use crate::util::ConsumeBuf; /// Abstraction over input/output buffers. @@ -85,7 +87,7 @@ impl LazyBuffers { // Vectors don't allocate until they get a size. input: ConsumeBuf::new(0), - output: vec![], + output: alloc::vec![], progress: false, } diff --git a/src/unversioned/transport/chain.rs b/src/unversioned/transport/chain.rs index 54309d16..3ff829f6 100644 --- a/src/unversioned/transport/chain.rs +++ b/src/unversioned/transport/chain.rs @@ -1,3 +1,5 @@ +use alloc::{boxed::Box, vec::Vec}; + use crate::Error; use super::{ConnectionDetails, Connector, Transport}; diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index 5129b207..f4aac2b1 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -1,5 +1,3 @@ -use std::io; - use crate::Timeout; use super::time::Duration; diff --git a/src/unversioned/transport/mod.rs b/src/unversioned/transport/mod.rs index 0b761680..1988368a 100644 --- a/src/unversioned/transport/mod.rs +++ b/src/unversioned/transport/mod.rs @@ -23,7 +23,7 @@ //! using these schemes. See [`ChainedConnector`] for a helper connector that aids setting //! up a chain of concrete connectors. -use std::fmt::Debug; +use alloc::fmt::Debug; use http::uri::Scheme; use http::Uri; diff --git a/src/unversioned/transport/socks.rs b/src/unversioned/transport/socks.rs index 783c6a67..9e5f6880 100644 --- a/src/unversioned/transport/socks.rs +++ b/src/unversioned/transport/socks.rs @@ -1,8 +1,3 @@ -use std::fmt; -use std::net::{SocketAddr, TcpStream}; -use std::sync::mpsc::{self, RecvTimeoutError}; -use std::{io, thread}; - use socks::{Socks4Stream, Socks5Stream}; use crate::proxy::{Proto, Proxy}; diff --git a/src/unversioned/transport/tcp.rs b/src/unversioned/transport/tcp.rs index 92d593b7..47e5a3b9 100644 --- a/src/unversioned/transport/tcp.rs +++ b/src/unversioned/transport/tcp.rs @@ -1,7 +1,3 @@ -use std::io::{Read, Write}; -use std::net::{SocketAddr, TcpStream}; -use std::{fmt, io, time}; - use crate::config::Config; use crate::util::IoResultExt; use crate::Error; diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 039a3df3..4ab98016 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -1,12 +1,5 @@ #![allow(clippy::type_complexity)] -use std::cell::RefCell; -use std::io::Write; -use std::io::{BufRead, BufReader}; -use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; -use std::sync::{Arc, Mutex}; -use std::{fmt, io, thread}; - use http::{Method, Request, Uri}; use crate::http; diff --git a/src/unversioned/transport/time.rs b/src/unversioned/transport/time.rs index 21705fa8..d2bfd0e1 100644 --- a/src/unversioned/transport/time.rs +++ b/src/unversioned/transport/time.rs @@ -1,9 +1,5 @@ //! Internal time wrappers -use std::cmp::Ordering; -use std::ops::{Add, Deref}; -use std::time; - /// Wrapper for [`std::time::Instant`] that provides additional time points in the past or future #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Instant { diff --git a/src/util.rs b/src/util.rs index 33891181..c0412e44 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,7 +1,4 @@ -use std::convert::TryFrom; -use std::fmt; -use std::io::{self, ErrorKind}; - +use alloc::vec::Vec; use http::header::{ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING}; use http::header::{CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE}; use http::header::{DATE, HOST, LOCATION, SERVER, TRANSFER_ENCODING, USER_AGENT}; @@ -87,7 +84,7 @@ pub(crate) struct ConsumeBuf { impl ConsumeBuf { pub fn new(size: usize) -> Self { ConsumeBuf { - buf: vec![0; size], + buf: alloc::vec![0; size], filled: 0, consumed: 0, } From 88a3b6fcb5c00a077a824cf10d976c5d73ff9267 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 00:17:29 -0500 Subject: [PATCH 2/7] spin lock mutex? --- Cargo.lock | 20 ++++++++++++++++++++ Cargo.toml | 1 + src/config.rs | 2 ++ src/error.rs | 4 +++- src/middleware.rs | 1 + src/pool.rs | 2 ++ src/proxy.rs | 8 ++++++-- src/query.rs | 6 ++++-- src/request.rs | 9 ++++++--- src/run.rs | 1 + src/timings.rs | 1 + src/tls/cert.rs | 2 ++ src/tls/mod.rs | 4 ++-- src/unversioned/resolver.rs | 5 +++-- src/unversioned/transport/io.rs | 2 ++ src/unversioned/transport/mod.rs | 6 +++++- src/unversioned/transport/tcp.rs | 3 +++ src/unversioned/transport/test.rs | 2 +- src/unversioned/transport/time.rs | 6 ++++-- src/util.rs | 9 +++++---- 20 files changed, 74 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index da403be9..1b1d2154 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -622,6 +622,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ce301924b7887e9d637144fdade93f9dfff9b60981d4ac161db09720d39aa5" +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + [[package]] name = "log" version = "0.4.22" @@ -979,6 +989,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "security-framework" version = "2.11.1" @@ -1063,6 +1079,9 @@ name = "spin" version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] [[package]] name = "stable_deref_trait" @@ -1226,6 +1245,7 @@ dependencies = [ "serde", "serde_json", "socks", + "spin", "ureq-proto", "url", "utf-8", diff --git a/Cargo.toml b/Cargo.toml index 875446b5..5345097f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,6 +74,7 @@ encoding_rs = { version = "0.8.34", optional = true } serde = { version = "1.0.204", optional = true, default-features = false, features = ["std"] } serde_json = { version = "1.0.120", optional = true, default-features = false, features = ["std"] } +spin = "0.9.8" [build-dependencies] cc = "1.0.106" diff --git a/src/config.rs b/src/config.rs index 1359990b..22bdcf72 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,9 @@ //! Agent configuration +use core::net::SocketAddr; use core::time::Duration; +use alloc::fmt; use alloc::string::String; use alloc::sync::Arc; use http::Uri; diff --git a/src/error.rs b/src/error.rs index 932ad1b0..b5feaf19 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,3 +1,4 @@ +use alloc::fmt; use alloc::string::String; use crate::http; @@ -139,6 +140,7 @@ pub enum Error { BodyStalled, } +#[cfg(feature = "std")] impl std::error::Error for Error {} impl Error { @@ -309,7 +311,7 @@ mod test { #[test] fn ensure_error_size() { // This is platform dependent, so we can't be too strict or precise. - let size = std::mem::size_of::(); + let size = core::mem::size_of::(); assert!(size < 100); // 40 on Macbook M1 } } diff --git a/src/middleware.rs b/src/middleware.rs index 358495f1..69e382e9 100644 --- a/src/middleware.rs +++ b/src/middleware.rs @@ -1,6 +1,7 @@ //! Chained interception to modify the request or response. use alloc::boxed::Box; +use alloc::fmt; use alloc::sync::Arc; use alloc::vec::Vec; diff --git a/src/pool.rs b/src/pool.rs index 5f1dc5fa..ae45674e 100644 --- a/src/pool.rs +++ b/src/pool.rs @@ -1,8 +1,10 @@ use alloc::boxed::Box; use alloc::collections::vec_deque::VecDeque; +use alloc::fmt; use alloc::sync::Arc; use http::uri::{Authority, Scheme}; use http::Uri; +use spin::Mutex; use crate::config::Config; use crate::http; diff --git a/src/proxy.rs b/src/proxy.rs index ca497bc6..c1a199c7 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -1,4 +1,8 @@ +use core::convert::TryFrom; + use alloc::boxed::Box; +use alloc::fmt; +use alloc::sync::Arc; use base64::prelude::BASE64_STANDARD; use base64::Engine; use ureq_proto::parser::try_parse_response; @@ -224,7 +228,7 @@ impl Connector for ConnectProxyConnector { if use_creds { let user = proxy.username().unwrap_or_default(); let pass = proxy.password().unwrap_or_default(); - let creds = BASE64_STANDARD.encode(format!("{}:{}", user, pass)); + let creds = BASE64_STANDARD.encode(alloc::format!("{}:{}", user, pass)); write!(w, "Proxy-Authorization: basic {}\r\n", creds)?; } @@ -253,7 +257,7 @@ impl Connector for ConnectProxyConnector { trace!("CONNECT proxy connected"); } x => { - let reason = format!("proxy server responded {}/{}", x.as_u16(), x.as_str()); + let reason = alloc::format!("proxy server responded {}/{}", x.as_u16(), x.as_str()); return Err(Error::ConnectProxyFailed(reason)); } } diff --git a/src/query.rs b/src/query.rs index b691aae1..e8487893 100644 --- a/src/query.rs +++ b/src/query.rs @@ -1,4 +1,6 @@ -use alloc::{borrow::Cow, string::String}; +use core::{iter::Enumerate, ops::Deref, str::Chars}; + +use alloc::{borrow::Cow, fmt, string::String}; use percent_encoding::utf8_percent_encode; #[derive(Clone)] @@ -18,7 +20,7 @@ pub fn url_enc(i: &str) -> Cow { impl<'a> QueryParam<'a> { pub fn new_key_value(param: &str, value: &str) -> QueryParam<'static> { - let s = format!("{}={}", url_enc(param), url_enc(value)); + let s = alloc::format!("{}={}", url_enc(param), url_enc(value)); QueryParam { source: Source::Owned(s), } diff --git a/src/request.rs b/src/request.rs index c8f82fd0..b9daed55 100644 --- a/src/request.rs +++ b/src/request.rs @@ -1,7 +1,10 @@ use core::convert::TryFrom; use core::marker::PhantomData; +use core::ops::{Deref, DerefMut}; use alloc::boxed::Box; +use alloc::fmt; +use alloc::string::String; use alloc::vec::Vec; use http::{HeaderName, HeaderValue, Method, Request, Response, Uri, Version}; @@ -519,7 +522,7 @@ impl fmt::Debug for RequestBuilder { #[cfg(test)] mod test { - use std::time::Duration; + use core::time::Duration; use crate::get; use crate::test::init_test_log; @@ -537,7 +540,7 @@ mod test { fn debug_print_without_body() { let call = crate::get("https://foo/bar"); assert_eq!( - format!("{:?}", call), + alloc::format!("{:?}", call), "RequestBuilder { method: GET, uri: https://foo/bar }" ); } @@ -546,7 +549,7 @@ mod test { fn debug_print_with_body() { let call = crate::post("https://foo/bar"); assert_eq!( - format!("{:?}", call), + alloc::format!("{:?}", call), "RequestBuilder { method: POST, uri: https://foo/bar }" ); } diff --git a/src/run.rs b/src/run.rs index aac5047c..6e50b619 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,3 +1,4 @@ +use alloc::sync::Arc; use http::uri::Scheme; use http::{header, HeaderValue, Request, Response, Uri}; use once_cell::sync::Lazy; diff --git a/src/timings.rs b/src/timings.rs index 63d94c71..984a767f 100644 --- a/src/timings.rs +++ b/src/timings.rs @@ -1,3 +1,4 @@ +use alloc::sync::Arc; use ureq_proto::ArrayVec; use crate::config::Timeouts; diff --git a/src/tls/cert.rs b/src/tls/cert.rs index ee56fc01..036d8028 100644 --- a/src/tls/cert.rs +++ b/src/tls/cert.rs @@ -1,3 +1,5 @@ +use alloc::{fmt, vec::Vec}; + use crate::Error; /// An X509 certificate for a server or a client. diff --git a/src/tls/mod.rs b/src/tls/mod.rs index 6b59b57e..4505e40c 100644 --- a/src/tls/mod.rs +++ b/src/tls/mod.rs @@ -1,7 +1,7 @@ //! TLS for handling `https`. mod cert; -use alloc::{sync::Arc, vec::Vec}; +use alloc::{fmt, sync::Arc, vec::Vec}; pub use cert::{parse_pem, Certificate, PemItem, PrivateKey}; #[cfg(feature = "rustls")] @@ -253,7 +253,7 @@ impl Default for TlsProvider { } impl fmt::Debug for TlsConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsConfig") .field("provider", &self.provider) .field("client_cert", &self.client_cert) diff --git a/src/unversioned/resolver.rs b/src/unversioned/resolver.rs index 47a74258..cbf43bd0 100644 --- a/src/unversioned/resolver.rs +++ b/src/unversioned/resolver.rs @@ -13,6 +13,7 @@ use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4}; +use alloc::fmt; use alloc::string::String; use http::uri::{Authority, Scheme}; use http::Uri; @@ -24,7 +25,7 @@ use crate::util::{SchemeExt, UriExt}; use crate::Error; /// Trait for name resolvers. -pub trait Resolver: Debug + Send + Sync + 'static { +pub trait Resolver: fmt::Debug + Send + Sync + 'static { /// Resolve the URI to a socket address. /// /// The implementation should resolve within the given _timeout_. @@ -61,7 +62,7 @@ impl DefaultResolver { pub fn host_and_port(scheme: &Scheme, authority: &Authority) -> Option { let port = authority.port_u16().or_else(|| scheme.default_port())?; - Some(format!("{}:{}", authority.host(), port)) + Some(alloc::format!("{}:{}", authority.host(), port)) } } diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index f4aac2b1..a0192b38 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -1,3 +1,5 @@ +use alloc::boxed::Box; + use crate::Timeout; use super::time::Duration; diff --git a/src/unversioned/transport/mod.rs b/src/unversioned/transport/mod.rs index 1988368a..3c3521c6 100644 --- a/src/unversioned/transport/mod.rs +++ b/src/unversioned/transport/mod.rs @@ -23,7 +23,7 @@ //! using these schemes. See [`ChainedConnector`] for a helper connector that aids setting //! up a chain of concrete connectors. -use alloc::fmt::Debug; +use alloc::{boxed::Box, fmt::Debug}; use http::uri::Scheme; use http::Uri; @@ -297,6 +297,8 @@ impl Connector for DefaultConnector { #[cfg(not(feature = "socks-proxy"))] mod no_proxy { + use alloc::boxed::Box; + use super::{ConnectionDetails, Connector, Debug, Error, Transport}; #[derive(Debug)] @@ -334,6 +336,8 @@ mod no_proxy { #[cfg(feature = "_tls")] mod no_tls { + use alloc::boxed::Box; + use crate::tls::TlsProvider; use super::{ConnectionDetails, Connector, Debug, Error, Transport}; diff --git a/src/unversioned/transport/tcp.rs b/src/unversioned/transport/tcp.rs index 47e5a3b9..453d68f8 100644 --- a/src/unversioned/transport/tcp.rs +++ b/src/unversioned/transport/tcp.rs @@ -1,3 +1,6 @@ +use alloc::boxed::Box; +use alloc::fmt; + use crate::config::Config; use crate::util::IoResultExt; use crate::Error; diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 4ab98016..25268065 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -68,7 +68,7 @@ pub fn set_handler(pattern: &'static str, status: u16, headers: &[(&str, &str)], // Convert headers to a big string let mut headers_s = String::new(); for (k, v) in headers { - headers_s.push_str(&format!("{}: {}\r\n", k, v)); + headers_s.push_str(&alloc::format!("{}: {}\r\n", k, v)); } // Convert body to an owned vec diff --git a/src/unversioned/transport/time.rs b/src/unversioned/transport/time.rs index d2bfd0e1..70c06cff 100644 --- a/src/unversioned/transport/time.rs +++ b/src/unversioned/transport/time.rs @@ -1,5 +1,7 @@ //! Internal time wrappers +use core::{cmp::Ordering, ops::Deref, time}; + /// Wrapper for [`std::time::Instant`] that provides additional time points in the past or future #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Instant { @@ -124,8 +126,8 @@ impl Ord for Duration { } } -impl From for Duration { - fn from(value: std::time::Duration) -> Self { +impl From for Duration { + fn from(value: time::Duration) -> Self { Self::Exact(value) } } diff --git a/src/util.rs b/src/util.rs index c0412e44..d129f76d 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,3 +1,4 @@ +use alloc::fmt; use alloc::vec::Vec; use http::header::{ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING}; use http::header::{CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE}; @@ -215,7 +216,7 @@ impl<'a> fmt::Debug for DebugHeaders<'a> { if redact_count > 0 { debug.entry( &"", - &format!("{} HEADERS ARE REDACTED", redact_count), + &alloc::format!("{} HEADERS ARE REDACTED", redact_count), ); } @@ -287,14 +288,14 @@ impl UriExt for Uri { fn ensure_valid_url(&self) -> Result<(), Error> { let scheme = self .scheme() - .ok_or_else(|| Error::BadUri(format!("{} is missing scheme", self)))?; + .ok_or_else(|| Error::BadUri(alloc::format!("{} is missing scheme", self)))?; scheme .default_port() - .ok_or_else(|| Error::BadUri(format!("unknown scheme: {}", scheme)))?; + .ok_or_else(|| Error::BadUri(alloc::format!("unknown scheme: {}", scheme)))?; self.authority() - .ok_or_else(|| Error::BadUri(format!("{} is missing host", self)))?; + .ok_or_else(|| Error::BadUri(alloc::format!("{} is missing host", self)))?; Ok(()) } From a72aa069f58453588ebf9721eacc9d76984b9115 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 00:24:45 -0500 Subject: [PATCH 3/7] core::result --- Cargo.lock | 82 +++++++++++++++++++++++++++++++ Cargo.toml | 1 + src/body/brotli.rs | 2 +- src/body/charset.rs | 2 +- src/body/limit.rs | 2 +- src/body/lossy.rs | 4 +- src/body/mod.rs | 10 ++-- src/pool.rs | 4 +- src/run.rs | 2 +- src/send_body.rs | 2 +- src/tls/cert.rs | 2 +- src/unversioned/resolver.rs | 1 + src/unversioned/transport/io.rs | 6 +-- src/unversioned/transport/tcp.rs | 6 ++- src/unversioned/transport/test.rs | 10 ++-- src/unversioned/transport/time.rs | 6 +-- src/util.rs | 2 +- 17 files changed, 115 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1b1d2154..8e7b6bec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -141,6 +141,12 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + [[package]] name = "byteorder" version = "1.5.0" @@ -598,6 +604,16 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +[[package]] +name = "js-sys" +version = "0.3.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.164" @@ -1249,6 +1265,7 @@ dependencies = [ "ureq-proto", "url", "utf-8", + "web-time", "webpki-root-certs", "webpki-roots", ] @@ -1327,6 +1344,71 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasm-bindgen" +version = "0.2.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c" +dependencies = [ + "cfg-if", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2 1.0.92", + "quote 1.0.37", + "syn 2.0.89", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051" +dependencies = [ + "quote 1.0.37", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d" +dependencies = [ + "proc-macro2 1.0.92", + "quote 1.0.37", + "syn 2.0.89", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.97" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "0.26.7" diff --git a/Cargo.toml b/Cargo.toml index 5345097f..b94cb303 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,6 +75,7 @@ encoding_rs = { version = "0.8.34", optional = true } serde = { version = "1.0.204", optional = true, default-features = false, features = ["std"] } serde_json = { version = "1.0.120", optional = true, default-features = false, features = ["std"] } spin = "0.9.8" +web-time = "1.1.0" [build-dependencies] cc = "1.0.106" diff --git a/src/body/brotli.rs b/src/body/brotli.rs index 71063233..3bb12da2 100644 --- a/src/body/brotli.rs +++ b/src/body/brotli.rs @@ -11,7 +11,7 @@ impl BrotliDecoder { } impl io::Read for BrotliDecoder { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { self.0 .read(buf) .map_err(|e| Error::Decompress("brotli", e).into_io()) diff --git a/src/body/charset.rs b/src/body/charset.rs index 2ad1de9d..eb83a80d 100644 --- a/src/body/charset.rs +++ b/src/body/charset.rs @@ -33,7 +33,7 @@ where } impl io::Read for CharCodec { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { if self.reached_end && self.buf.unconsumed().is_empty() { return Ok(0); } diff --git a/src/body/limit.rs b/src/body/limit.rs index b875c535..0526450a 100644 --- a/src/body/limit.rs +++ b/src/body/limit.rs @@ -17,7 +17,7 @@ impl LimitReader { } impl io::Read for LimitReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { if self.left == 0 { return Err(Error::BodyExceedsLimit(self.limit).into_io()); } diff --git a/src/body/lossy.rs b/src/body/lossy.rs index a2abf3a5..2019f6b4 100644 --- a/src/body/lossy.rs +++ b/src/body/lossy.rs @@ -21,7 +21,7 @@ impl LossyUtf8Reader { } impl io::Read for LossyUtf8Reader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { // Match the input buffer size if !self.ended { let total_len = self.input.unconsumed().len() + self.input.free_mut().len(); @@ -153,7 +153,7 @@ mod test { struct TestReader<'a>(&'a mut [&'a [u8]]); impl<'a> io::Read for TestReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { if self.0.iter().all(|c| c.is_empty()) { return Ok(0); } diff --git a/src/body/mod.rs b/src/body/mod.rs index 79fb6aa1..431271b3 100644 --- a/src/body/mod.rs +++ b/src/body/mod.rs @@ -620,7 +620,7 @@ enum MaybeLossyDecoder { } impl io::Read for MaybeLossyDecoder { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { match self { MaybeLossyDecoder::Lossy(r) => r.read(buf), MaybeLossyDecoder::PassThrough(r) => r.read(buf), @@ -629,7 +629,7 @@ impl io::Read for MaybeLossyDecoder { } impl<'a> io::Read for BodyReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { self.reader.read(buf) } } @@ -641,7 +641,7 @@ enum CharsetDecoder { } impl io::Read for CharsetDecoder { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { match self { #[cfg(feature = "charset")] CharsetDecoder::Decoder(v) => v.read(buf), @@ -659,7 +659,7 @@ enum ContentDecoder { } impl io::Read for ContentDecoder { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { match self { #[cfg(feature = "gzip")] ContentDecoder::Gzip(v) => v.read(buf), @@ -714,7 +714,7 @@ pub(crate) enum BodySourceRef<'a> { } impl<'a> io::Read for BodySourceRef<'a> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { match self { BodySourceRef::HandlerShared(v) => v.read(buf), BodySourceRef::HandlerOwned(v) => v.read(buf), diff --git a/src/pool.rs b/src/pool.rs index ae45674e..d7de04fc 100644 --- a/src/pool.rs +++ b/src/pool.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use alloc::collections::vec_deque::VecDeque; use alloc::fmt; -use alloc::sync::Arc; +use alloc::sync::{Arc, Weak}; use http::uri::{Authority, Scheme}; use http::Uri; use spin::Mutex; @@ -72,7 +72,7 @@ pub(crate) struct Connection { transport: Box, key: PoolKey, last_use: Instant, - pool: Weak>, + pool: Weak>, // TODO: not alloc::rc::Weak? /// Used to prune max_idle_connections_by_host. /// diff --git a/src/run.rs b/src/run.rs index 6e50b619..47110544 100644 --- a/src/run.rs +++ b/src/run.rs @@ -656,7 +656,7 @@ impl BodyHandler { } impl io::Read for BodyHandler { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { self.do_read(buf).map_err(|e| e.into_io()) } } diff --git a/src/send_body.rs b/src/send_body.rs index 695b90e0..b57fc8de 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -42,7 +42,7 @@ impl<'a> SendBody<'a> { Ok(Self::from_owned_reader(io::Cursor::new(json))) } - pub(crate) fn read(&mut self, buf: &mut [u8]) -> io::Result { + pub(crate) fn read(&mut self, buf: &mut [u8]) -> core::result::Result { let n = match &mut self.inner { BodyInner::None => { return Ok(0); diff --git a/src/tls/cert.rs b/src/tls/cert.rs index 036d8028..93c15c96 100644 --- a/src/tls/cert.rs +++ b/src/tls/cert.rs @@ -1,4 +1,4 @@ -use alloc::{fmt, vec::Vec}; +use alloc::{borrow::Cow, fmt, vec::Vec}; use crate::Error; diff --git a/src/unversioned/resolver.rs b/src/unversioned/resolver.rs index cbf43bd0..88e51ad8 100644 --- a/src/unversioned/resolver.rs +++ b/src/unversioned/resolver.rs @@ -130,6 +130,7 @@ impl Resolver for DefaultResolver { } } +// TODO: very no_std unfriendly function? fn resolve_async(addr: String, timeout: NextTimeout) -> Result, Error> { // TODO(martin): On Linux we have getaddrinfo_a which is a libc async way of // doing host lookup. We should make a subcrate that uses a native async method diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index a0192b38..298993d9 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -54,7 +54,7 @@ impl TransportAdapter { } impl io::Read for TransportAdapter { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { self.transport .await_input(self.timeout) .map_err(|e| e.into_io())?; @@ -69,7 +69,7 @@ impl io::Read for TransportAdapter { } impl io::Write for TransportAdapter { - fn write(&mut self, buf: &[u8]) -> io::Result { + fn write(&mut self, buf: &[u8]) -> core::result::Result { let output = self.transport.buffers().output(); let max = buf.len().min(output.len()); @@ -81,7 +81,7 @@ impl io::Write for TransportAdapter { Ok(max) } - fn flush(&mut self) -> io::Result<()> { + fn flush(&mut self) -> core::result::Result<()> { Ok(()) } } diff --git a/src/unversioned/transport/tcp.rs b/src/unversioned/transport/tcp.rs index 453d68f8..51db8360 100644 --- a/src/unversioned/transport/tcp.rs +++ b/src/unversioned/transport/tcp.rs @@ -1,3 +1,5 @@ +use core::net::SocketAddr; + use alloc::boxed::Box; use alloc::fmt; @@ -117,8 +119,8 @@ fn maybe_update_timeout( timeout: NextTimeout, previous: &mut Option, stream: &TcpStream, - f: impl Fn(&TcpStream, Option) -> io::Result<()>, -) -> io::Result<()> { + f: impl Fn(&TcpStream, Option) -> core::result::Result<()>, +) -> core::result::Result<()> { let maybe_timeout = timeout.not_zero(); if maybe_timeout != *previous { diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 25268065..96a0f620 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -52,7 +52,7 @@ impl Connector for TestConnector { impl TestHandler { fn new( pattern: &'static str, - handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> io::Result<()> + Send + Sync + 'static, + handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> core::result::Result<()> + Send + Sync + 'static, ) -> Self { TestHandler { pattern, @@ -91,7 +91,7 @@ pub fn set_handler(pattern: &'static str, status: u16, headers: &[(&str, &str)], #[derive(Clone)] struct TestHandler { pattern: &'static str, - handler: Arc, &mut dyn Write) -> io::Result<()> + Sync + Send>, + handler: Arc, &mut dyn Write) -> core::result::Result<()> + Sync + Send>, } fn test_run( @@ -395,7 +395,7 @@ const HTTPBIN_JSON: &str = r#" struct RxRead(Receiver>); impl io::Read for RxRead { - fn read(&mut self, buf: &mut [u8]) -> io::Result { + fn read(&mut self, buf: &mut [u8]) -> core::result::Result { let v = match self.0.recv() { Ok(v) => v, Err(_) => return Ok(0), // remote side is gone @@ -410,14 +410,14 @@ impl io::Read for RxRead { struct TxWrite(mpsc::SyncSender>); impl io::Write for TxWrite { - fn write(&mut self, buf: &[u8]) -> io::Result { + fn write(&mut self, buf: &[u8]) -> core::result::Result { self.0 .send(buf.to_vec()) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; Ok(buf.len()) } - fn flush(&mut self) -> io::Result<()> { + fn flush(&mut self) -> core::result::Result<()> { Ok(()) } } diff --git a/src/unversioned/transport/time.rs b/src/unversioned/transport/time.rs index 70c06cff..07346e1d 100644 --- a/src/unversioned/transport/time.rs +++ b/src/unversioned/transport/time.rs @@ -1,6 +1,6 @@ //! Internal time wrappers -use core::{cmp::Ordering, ops::Deref, time}; +use core::{cmp::Ordering, ops::{Add, Deref}, time}; /// Wrapper for [`std::time::Instant`] that provides additional time points in the past or future #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -8,7 +8,7 @@ pub enum Instant { /// A time in the past that already happened. AlreadyHappened, /// An exact instant. - Exact(time::Instant), + Exact(web_time::Instant), /// A time in the future that will never happen. NotHappening, } @@ -52,7 +52,7 @@ impl Deref for Duration { impl Instant { /// Current time. pub fn now() -> Self { - Instant::Exact(time::Instant::now()) + Instant::Exact(web_time::Instant::now()) } pub(crate) fn duration_since(&self, earlier: Instant) -> Duration { diff --git a/src/util.rs b/src/util.rs index d129f76d..8a9c182e 100644 --- a/src/util.rs +++ b/src/util.rs @@ -64,7 +64,7 @@ pub(crate) trait IoResultExt { fn normalize_would_block(self) -> Self; } -impl IoResultExt for io::Result { +impl IoResultExt for core::result::Result { fn normalize_would_block(self) -> Self { match self { Ok(v) => Ok(v), From d672b36d2022cded003a2e3f95eb22df2c981de2 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 00:31:40 -0500 Subject: [PATCH 4/7] anyhow --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/body/brotli.rs | 2 +- src/body/charset.rs | 2 +- src/body/limit.rs | 4 +++- src/body/lossy.rs | 4 ++-- src/body/mod.rs | 10 +++++----- src/lib.rs | 1 + src/proxy.rs | 2 +- src/run.rs | 7 ++++--- src/send_body.rs | 2 +- src/timings.rs | 1 + src/unversioned/transport/io.rs | 6 +++--- src/unversioned/transport/tcp.rs | 4 ++-- src/unversioned/transport/test.rs | 10 +++++----- src/util.rs | 2 +- 16 files changed, 39 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e7b6bec..7414a111 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -81,6 +81,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "anyhow" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" + [[package]] name = "assert_no_alloc" version = "1.1.2" @@ -1240,6 +1246,7 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" name = "ureq" version = "3.0.0-rc3" dependencies = [ + "anyhow", "assert_no_alloc", "auto-args", "base64", diff --git a/Cargo.toml b/Cargo.toml index b94cb303..93204b24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,6 +76,7 @@ serde = { version = "1.0.204", optional = true, default-features = false, featur serde_json = { version = "1.0.120", optional = true, default-features = false, features = ["std"] } spin = "0.9.8" web-time = "1.1.0" +anyhow = "1.0.93" [build-dependencies] cc = "1.0.106" diff --git a/src/body/brotli.rs b/src/body/brotli.rs index 3bb12da2..90bb6afa 100644 --- a/src/body/brotli.rs +++ b/src/body/brotli.rs @@ -11,7 +11,7 @@ impl BrotliDecoder { } impl io::Read for BrotliDecoder { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { self.0 .read(buf) .map_err(|e| Error::Decompress("brotli", e).into_io()) diff --git a/src/body/charset.rs b/src/body/charset.rs index eb83a80d..e0641bd1 100644 --- a/src/body/charset.rs +++ b/src/body/charset.rs @@ -33,7 +33,7 @@ where } impl io::Read for CharCodec { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { if self.reached_end && self.buf.unconsumed().is_empty() { return Ok(0); } diff --git a/src/body/limit.rs b/src/body/limit.rs index 0526450a..6e8c1dcf 100644 --- a/src/body/limit.rs +++ b/src/body/limit.rs @@ -1,3 +1,5 @@ +use core::io; + use crate::Error; pub(crate) struct LimitReader { @@ -17,7 +19,7 @@ impl LimitReader { } impl io::Read for LimitReader { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { if self.left == 0 { return Err(Error::BodyExceedsLimit(self.limit).into_io()); } diff --git a/src/body/lossy.rs b/src/body/lossy.rs index 2019f6b4..f61906dd 100644 --- a/src/body/lossy.rs +++ b/src/body/lossy.rs @@ -21,7 +21,7 @@ impl LossyUtf8Reader { } impl io::Read for LossyUtf8Reader { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { // Match the input buffer size if !self.ended { let total_len = self.input.unconsumed().len() + self.input.free_mut().len(); @@ -153,7 +153,7 @@ mod test { struct TestReader<'a>(&'a mut [&'a [u8]]); impl<'a> io::Read for TestReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { if self.0.iter().all(|c| c.is_empty()) { return Ok(0); } diff --git a/src/body/mod.rs b/src/body/mod.rs index 431271b3..2198865f 100644 --- a/src/body/mod.rs +++ b/src/body/mod.rs @@ -620,7 +620,7 @@ enum MaybeLossyDecoder { } impl io::Read for MaybeLossyDecoder { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { match self { MaybeLossyDecoder::Lossy(r) => r.read(buf), MaybeLossyDecoder::PassThrough(r) => r.read(buf), @@ -629,7 +629,7 @@ impl io::Read for MaybeLossyDecoder { } impl<'a> io::Read for BodyReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { self.reader.read(buf) } } @@ -641,7 +641,7 @@ enum CharsetDecoder { } impl io::Read for CharsetDecoder { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { match self { #[cfg(feature = "charset")] CharsetDecoder::Decoder(v) => v.read(buf), @@ -659,7 +659,7 @@ enum ContentDecoder { } impl io::Read for ContentDecoder { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { match self { #[cfg(feature = "gzip")] ContentDecoder::Gzip(v) => v.read(buf), @@ -714,7 +714,7 @@ pub(crate) enum BodySourceRef<'a> { } impl<'a> io::Read for BodySourceRef<'a> { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { match self { BodySourceRef::HandlerShared(v) => v.read(buf), BodySourceRef::HandlerOwned(v) => v.read(buf), diff --git a/src/lib.rs b/src/lib.rs index 1ad327da..a1636214 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -440,6 +440,7 @@ //! [webpki-roots]: https://crates.io/crates/webpki-roots #![no_std] +//#![feature(core_io_borrowed_buf)] // TODO: requires nightly? #![forbid(unsafe_code)] #![warn(clippy::all)] #![deny(missing_docs)] diff --git a/src/proxy.rs b/src/proxy.rs index c1a199c7..fa310574 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -119,7 +119,7 @@ impl Proxy { macro_rules! try_env { ($($env:literal),+) => { $( - if let Ok(env) = std::env::var($env) { + if let Ok(env) = std::env::var($env) { // TODO: no_std? if let Ok(proxy) = Self::new_with_flag(&env, true) { return Some(proxy); } diff --git a/src/run.rs b/src/run.rs index 47110544..5a636f6b 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,3 +1,4 @@ +use alloc::string::String; use alloc::sync::Arc; use http::uri::Scheme; use http::{header, HeaderValue, Request, Response, Uri}; @@ -168,7 +169,7 @@ fn flow_run( let ret = match response_result { RecvResponseResult::RecvBody(flow) => { - let timings = mem::take(timings); + let timings = core::mem::take(timings); let mut handler = BodyHandler { flow: Some(flow), connection: Some(connection), @@ -190,7 +191,7 @@ fn flow_run( if redirect_count >= config.max_redirects() { FlowResult::Response(response, BodyHandler::default()) } else { - FlowResult::Redirect(flow, mem::take(timings)) + FlowResult::Redirect(flow, core::mem::take(timings)) } } RecvResponseResult::Cleanup(flow) => { @@ -656,7 +657,7 @@ impl BodyHandler { } impl io::Read for BodyHandler { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { self.do_read(buf).map_err(|e| e.into_io()) } } diff --git a/src/send_body.rs b/src/send_body.rs index b57fc8de..59dbf8e3 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -42,7 +42,7 @@ impl<'a> SendBody<'a> { Ok(Self::from_owned_reader(io::Cursor::new(json))) } - pub(crate) fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + pub(crate) fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { let n = match &mut self.inner { BodyInner::None => { return Ok(0); diff --git a/src/timings.rs b/src/timings.rs index 984a767f..d1d5048d 100644 --- a/src/timings.rs +++ b/src/timings.rs @@ -1,3 +1,4 @@ +use alloc::fmt; use alloc::sync::Arc; use ureq_proto::ArrayVec; diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index 298993d9..322b2948 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -54,7 +54,7 @@ impl TransportAdapter { } impl io::Read for TransportAdapter { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { self.transport .await_input(self.timeout) .map_err(|e| e.into_io())?; @@ -69,7 +69,7 @@ impl io::Read for TransportAdapter { } impl io::Write for TransportAdapter { - fn write(&mut self, buf: &[u8]) -> core::result::Result { + fn write(&mut self, buf: &[u8]) -> anyhow::Result { let output = self.transport.buffers().output(); let max = buf.len().min(output.len()); @@ -81,7 +81,7 @@ impl io::Write for TransportAdapter { Ok(max) } - fn flush(&mut self) -> core::result::Result<()> { + fn flush(&mut self) -> anyhow::Result<()> { Ok(()) } } diff --git a/src/unversioned/transport/tcp.rs b/src/unversioned/transport/tcp.rs index 51db8360..f7c7d4d8 100644 --- a/src/unversioned/transport/tcp.rs +++ b/src/unversioned/transport/tcp.rs @@ -119,8 +119,8 @@ fn maybe_update_timeout( timeout: NextTimeout, previous: &mut Option, stream: &TcpStream, - f: impl Fn(&TcpStream, Option) -> core::result::Result<()>, -) -> core::result::Result<()> { + f: impl Fn(&TcpStream, Option) -> anyhow::Result<()>, +) -> anyhow::Result<()> { let maybe_timeout = timeout.not_zero(); if maybe_timeout != *previous { diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 96a0f620..48738f2c 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -52,7 +52,7 @@ impl Connector for TestConnector { impl TestHandler { fn new( pattern: &'static str, - handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> core::result::Result<()> + Send + Sync + 'static, + handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> anyhow::Result<()> + Send + Sync + 'static, ) -> Self { TestHandler { pattern, @@ -91,7 +91,7 @@ pub fn set_handler(pattern: &'static str, status: u16, headers: &[(&str, &str)], #[derive(Clone)] struct TestHandler { pattern: &'static str, - handler: Arc, &mut dyn Write) -> core::result::Result<()> + Sync + Send>, + handler: Arc, &mut dyn Write) -> anyhow::Result<()> + Sync + Send>, } fn test_run( @@ -395,7 +395,7 @@ const HTTPBIN_JSON: &str = r#" struct RxRead(Receiver>); impl io::Read for RxRead { - fn read(&mut self, buf: &mut [u8]) -> core::result::Result { + fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { let v = match self.0.recv() { Ok(v) => v, Err(_) => return Ok(0), // remote side is gone @@ -410,14 +410,14 @@ impl io::Read for RxRead { struct TxWrite(mpsc::SyncSender>); impl io::Write for TxWrite { - fn write(&mut self, buf: &[u8]) -> core::result::Result { + fn write(&mut self, buf: &[u8]) -> anyhow::Result { self.0 .send(buf.to_vec()) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; Ok(buf.len()) } - fn flush(&mut self) -> core::result::Result<()> { + fn flush(&mut self) -> anyhow::Result<()> { Ok(()) } } diff --git a/src/util.rs b/src/util.rs index 8a9c182e..dc859f96 100644 --- a/src/util.rs +++ b/src/util.rs @@ -64,7 +64,7 @@ pub(crate) trait IoResultExt { fn normalize_would_block(self) -> Self; } -impl IoResultExt for core::result::Result { +impl IoResultExt for anyhow::Result { fn normalize_would_block(self) -> Self { match self { Ok(v) => Ok(v), From 5af003689fe550988c2110d3e214ca1f80b66a73 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 00:47:27 -0500 Subject: [PATCH 5/7] no_std_io? --- Cargo.lock | 12 +++++++++++- Cargo.toml | 7 ++++--- src/body/build.rs | 2 +- src/body/limit.rs | 2 +- src/body/lossy.rs | 4 +++- src/body/mod.rs | 3 ++- src/cookies.rs | 1 + src/error.rs | 1 + src/lib.rs | 4 ++-- src/proxy.rs | 1 + src/query.rs | 2 +- src/request.rs | 2 +- src/run.rs | 4 +++- src/send_body.rs | 9 +++++---- src/unversioned/resolver.rs | 2 ++ src/unversioned/transport/io.rs | 1 + src/unversioned/transport/test.rs | 2 ++ 17 files changed, 42 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7414a111..90e2d0e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -692,6 +692,15 @@ dependencies = [ "tempfile", ] +[[package]] +name = "no_std_io" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fa5f306a6f2c01b4fd172f29bb46195b1764061bf926c75e96ff55df3178208" +dependencies = [ + "memchr", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -1259,6 +1268,7 @@ dependencies = [ "flate2", "log", "native-tls", + "no_std_io", "once_cell", "percent-encoding", "rustls", diff --git a/Cargo.toml b/Cargo.toml index 93204b24..43ffef17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,9 +11,8 @@ categories = ["web-programming::http-client"] edition = "2018" exclude = ["/cargo_deny.sh", "/deny.toml", "/test.sh"] - # MSRV -rust-version = "1.71.1" +rust-version = "1.83.0" [package.metadata.docs.rs] features = ["rustls", "platform-verifier", "native-tls", "socks-proxy", "cookies", "gzip", "brotli", "charset", "json", "_test"] @@ -74,9 +73,12 @@ encoding_rs = { version = "0.8.34", optional = true } serde = { version = "1.0.204", optional = true, default-features = false, features = ["std"] } serde_json = { version = "1.0.120", optional = true, default-features = false, features = ["std"] } + +# TODO: no_std? spin = "0.9.8" web-time = "1.1.0" anyhow = "1.0.93" +no_std_io = "0.6.0" [build-dependencies] cc = "1.0.106" @@ -87,7 +89,6 @@ auto-args = "0.3.0" serde = { version = "1.0.204", features = ["std", "derive"] } assert_no_alloc = "1.1.2" - [[example]] name = "cureq" required-features = ["rustls", "native-tls", "socks-proxy", "cookies", "gzip", "brotli", "charset"] diff --git a/src/body/build.rs b/src/body/build.rs index 9f49debc..006dc75b 100644 --- a/src/body/build.rs +++ b/src/body/build.rs @@ -119,7 +119,7 @@ impl BodyBuilder { /// /// The reader can be limited by using `.limit()` or that the reader /// reaches the end. - pub fn reader(self, data: impl io::Read + Send + Sync + 'static) -> Body { + pub fn reader(self, data: impl no_std_io::io::Read + Send + Sync + 'static) -> Body { Body { source: BodyDataSource::Reader(Box::new(data)), info: Arc::new(self.info), diff --git a/src/body/limit.rs b/src/body/limit.rs index 6e8c1dcf..9888f4a3 100644 --- a/src/body/limit.rs +++ b/src/body/limit.rs @@ -1,4 +1,4 @@ -use core::io; +use no_std_io::io; use crate::Error; diff --git a/src/body/lossy.rs b/src/body/lossy.rs index f61906dd..e39e0c26 100644 --- a/src/body/lossy.rs +++ b/src/body/lossy.rs @@ -1,3 +1,5 @@ +use no_std_io::io; + use utf8::DecodeError; use crate::util::ConsumeBuf; @@ -97,7 +99,7 @@ impl io::Read for LossyUtf8Reader { #[cfg(test)] mod test { - use std::io::Read; + use no_std_io::io; use alloc::string::String; diff --git a/src/body/mod.rs b/src/body/mod.rs index 2198865f..9f3a3038 100644 --- a/src/body/mod.rs +++ b/src/body/mod.rs @@ -1,7 +1,8 @@ +use no_std_io::io; use core::fmt; use alloc::boxed::Box; -use alloc::string::String; +use alloc::string::{String, ToString}; use alloc::sync::Arc; use alloc::vec::Vec; diff --git a/src/cookies.rs b/src/cookies.rs index 0864d6c6..b7138cdc 100644 --- a/src/cookies.rs +++ b/src/cookies.rs @@ -1,3 +1,4 @@ +use no_std_io::io; use cookie_store::CookieStore; use http::Uri; diff --git a/src/error.rs b/src/error.rs index b5feaf19..b9ab9f96 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,6 @@ use alloc::fmt; use alloc::string::String; +use no_std_io::io; use crate::http; use crate::Timeout; diff --git a/src/lib.rs b/src/lib.rs index a1636214..a92270d8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -440,7 +440,6 @@ //! [webpki-roots]: https://crates.io/crates/webpki-roots #![no_std] -//#![feature(core_io_borrowed_buf)] // TODO: requires nightly? #![forbid(unsafe_code)] #![warn(clippy::all)] #![deny(missing_docs)] @@ -553,6 +552,7 @@ mk_method!(trace, TRACE, WithoutBody); pub(crate) mod test { use assert_no_alloc::AllocDisabler; use config::Config; + use no_std_io::io; use once_cell::sync::Lazy; use super::*; @@ -779,7 +779,7 @@ pub(crate) mod test { #[test] fn post_big_body_chunked() { // https://github.com/algesten/ureq/issues/879 - let mut data = io::Cursor::new(vec![42; 153_600]); + let mut data = io::Cursor::new(alloc::vec![42; 153_600]); post("http://httpbin.org/post") .content_type("application/octet-stream") .send(SendBody::from_reader(&mut data)) diff --git a/src/proxy.rs b/src/proxy.rs index fa310574..3b68c2f8 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -2,6 +2,7 @@ use core::convert::TryFrom; use alloc::boxed::Box; use alloc::fmt; +use alloc::string::ToString; use alloc::sync::Arc; use base64::prelude::BASE64_STANDARD; use base64::Engine; diff --git a/src/query.rs b/src/query.rs index e8487893..d5f91ef4 100644 --- a/src/query.rs +++ b/src/query.rs @@ -105,7 +105,7 @@ impl<'a> PartialEq for QueryParam<'a> { #[cfg(test)] mod test { - use alloc::vec::Vec; + use alloc::{string::ToString, vec::Vec}; use super::*; diff --git a/src/request.rs b/src/request.rs index b9daed55..a9995087 100644 --- a/src/request.rs +++ b/src/request.rs @@ -606,7 +606,7 @@ mod test { let amended = amend_request_query( request, - vec![QueryParam::new_key_value("å ", "i åa ä e ö")].into_iter(), + alloc::vec![QueryParam::new_key_value("å ", "i åa ä e ö")].into_iter(), ); assert_eq!( diff --git a/src/run.rs b/src/run.rs index 5a636f6b..80ab10f8 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,4 +1,6 @@ -use alloc::string::String; +use no_std_io::io; + +use alloc::string::{String, ToString}; use alloc::sync::Arc; use http::uri::Scheme; use http::{header, HeaderValue, Request, Response, Uri}; diff --git a/src/send_body.rs b/src/send_body.rs index 59dbf8e3..06f6fc5b 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -1,3 +1,4 @@ +use no_std_io::io; use crate::body::{Body, BodyReader}; use crate::http; use crate::util::private::Private; @@ -24,12 +25,12 @@ impl<'a> SendBody<'a> { } /// Creates a body from a shared [`Read`] impl. - pub fn from_reader(reader: &'a mut dyn Read) -> SendBody<'a> { + pub fn from_reader(reader: &'a mut dyn io::Read) -> SendBody<'a> { BodyInner::Reader(reader).into() } /// Creates a body from an owned [`Read]` impl. - pub fn from_owned_reader(reader: impl Read + 'static) -> SendBody<'static> { + pub fn from_owned_reader(reader: impl io::Read + 'static) -> SendBody<'static> { BodyInner::OwnedReader(Box::new(reader)).into() } @@ -152,8 +153,8 @@ pub(crate) enum BodyInner<'a> { None, ByteSlice(&'a [u8]), Body(BodyReader<'a>), - Reader(&'a mut dyn Read), - OwnedReader(Box), + Reader(&'a mut dyn io::Read), + OwnedReader(Box), } impl<'a> BodyInner<'a> { diff --git a/src/unversioned/resolver.rs b/src/unversioned/resolver.rs index 88e51ad8..85c121dc 100644 --- a/src/unversioned/resolver.rs +++ b/src/unversioned/resolver.rs @@ -157,6 +157,8 @@ impl fmt::Debug for DefaultResolver { #[cfg(test)] mod test { + use alloc::string::ToString; + use crate::transport::time::Duration; use super::*; diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index 322b2948..288bbf0c 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -1,3 +1,4 @@ +use no_std_io::io; use alloc::boxed::Box; use crate::Timeout; diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 48738f2c..0b8d62fa 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -1,5 +1,7 @@ #![allow(clippy::type_complexity)] +use no_std_io::io; + use http::{Method, Request, Uri}; use crate::http; From 9c0b3aae59ba58612d49208748e635f6f0eb4d84 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 01:00:51 -0500 Subject: [PATCH 6/7] no-std-io --- Cargo.lock | 7 ------- Cargo.toml | 3 +-- src/body/brotli.rs | 2 +- src/body/charset.rs | 2 +- src/body/gzip.rs | 33 +++++++++---------------------- src/body/limit.rs | 2 +- src/body/lossy.rs | 4 ++-- src/body/mod.rs | 10 +++++----- src/proxy.rs | 9 ++++++++- src/request.rs | 4 +++- src/run.rs | 2 +- src/send_body.rs | 3 ++- src/tls/rustls.rs | 1 + src/unversioned/resolver.rs | 10 ++++++++-- src/unversioned/transport/io.rs | 6 +++--- src/unversioned/transport/tcp.rs | 5 +++-- src/unversioned/transport/test.rs | 10 +++++----- src/util.rs | 9 ++++++--- 18 files changed, 60 insertions(+), 62 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 90e2d0e3..4e29d844 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -81,12 +81,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "anyhow" -version = "1.0.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" - [[package]] name = "assert_no_alloc" version = "1.1.2" @@ -1255,7 +1249,6 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" name = "ureq" version = "3.0.0-rc3" dependencies = [ - "anyhow", "assert_no_alloc", "auto-args", "base64", diff --git a/Cargo.toml b/Cargo.toml index 43ffef17..1cdb6ea2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ features = ["rustls", "platform-verifier", "native-tls", "socks-proxy", "cookies [features] #default = ["rustls", "gzip", "json", "std"] -default = ["rustls", "gzip", "json"] +default = ["rustls", "json"] rustls = ["dep:rustls", "_tls", "dep:webpki-roots"] platform-verifier = ["dep:rustls-platform-verifier"] native-tls = ["dep:native-tls", "dep:der", "_tls", "dep:webpki-root-certs"] @@ -77,7 +77,6 @@ serde_json = { version = "1.0.120", optional = true, default-features = false, f # TODO: no_std? spin = "0.9.8" web-time = "1.1.0" -anyhow = "1.0.93" no_std_io = "0.6.0" [build-dependencies] diff --git a/src/body/brotli.rs b/src/body/brotli.rs index 90bb6afa..71063233 100644 --- a/src/body/brotli.rs +++ b/src/body/brotli.rs @@ -11,7 +11,7 @@ impl BrotliDecoder { } impl io::Read for BrotliDecoder { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0 .read(buf) .map_err(|e| Error::Decompress("brotli", e).into_io()) diff --git a/src/body/charset.rs b/src/body/charset.rs index e0641bd1..2ad1de9d 100644 --- a/src/body/charset.rs +++ b/src/body/charset.rs @@ -33,7 +33,7 @@ where } impl io::Read for CharCodec { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.reached_end && self.buf.unconsumed().is_empty() { return Ok(0); } diff --git a/src/body/gzip.rs b/src/body/gzip.rs index b646de9a..77a40cc1 100644 --- a/src/body/gzip.rs +++ b/src/body/gzip.rs @@ -1,37 +1,22 @@ +use no_std_io::io; + use flate2::read::MultiGzDecoder; use crate::Error; -#[cfg(not(feature = "std"))] -use core::result; -#[cfg(not(feature = "std"))] -use core::convert::From; -#[cfg(feature = "std")] -use std::io; - -// Replace io::Read with a custom trait for no_std -pub trait Read { - fn read(&mut self, buf: &mut [u8]) -> result::Result; -} - -#[cfg(feature = "std")] -impl Read for R { - fn read(&mut self, buf: &mut [u8]) -> result::Result { - io::Read::read(self, buf).map_err(|e| Error::Decompress("gzip", e)) - } -} - pub(crate) struct GzipDecoder(MultiGzDecoder); -impl GzipDecoder { +impl GzipDecoder { pub fn new(reader: R) -> Self { GzipDecoder(MultiGzDecoder::new(reader)) } } -impl Read for GzipDecoder { - fn read(&mut self, buf: &mut [u8]) -> result::Result { - self.0.read(buf) +impl io::Read for GzipDecoder { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0 + .read(buf) + .map_err(|e| Error::Decompress("gzip", e).into_io()) } } @@ -81,4 +66,4 @@ mod test { assert_eq!(agent.pool_count(), 1); } -} +} \ No newline at end of file diff --git a/src/body/limit.rs b/src/body/limit.rs index 9888f4a3..c1bb3744 100644 --- a/src/body/limit.rs +++ b/src/body/limit.rs @@ -19,7 +19,7 @@ impl LimitReader { } impl io::Read for LimitReader { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.left == 0 { return Err(Error::BodyExceedsLimit(self.limit).into_io()); } diff --git a/src/body/lossy.rs b/src/body/lossy.rs index e39e0c26..bac869ba 100644 --- a/src/body/lossy.rs +++ b/src/body/lossy.rs @@ -23,7 +23,7 @@ impl LossyUtf8Reader { } impl io::Read for LossyUtf8Reader { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { // Match the input buffer size if !self.ended { let total_len = self.input.unconsumed().len() + self.input.free_mut().len(); @@ -155,7 +155,7 @@ mod test { struct TestReader<'a>(&'a mut [&'a [u8]]); impl<'a> io::Read for TestReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { if self.0.iter().all(|c| c.is_empty()) { return Ok(0); } diff --git a/src/body/mod.rs b/src/body/mod.rs index 9f3a3038..671c6a79 100644 --- a/src/body/mod.rs +++ b/src/body/mod.rs @@ -621,7 +621,7 @@ enum MaybeLossyDecoder { } impl io::Read for MaybeLossyDecoder { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { match self { MaybeLossyDecoder::Lossy(r) => r.read(buf), MaybeLossyDecoder::PassThrough(r) => r.read(buf), @@ -630,7 +630,7 @@ impl io::Read for MaybeLossyDecoder { } impl<'a> io::Read for BodyReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.reader.read(buf) } } @@ -642,7 +642,7 @@ enum CharsetDecoder { } impl io::Read for CharsetDecoder { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { match self { #[cfg(feature = "charset")] CharsetDecoder::Decoder(v) => v.read(buf), @@ -660,7 +660,7 @@ enum ContentDecoder { } impl io::Read for ContentDecoder { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { match self { #[cfg(feature = "gzip")] ContentDecoder::Gzip(v) => v.read(buf), @@ -715,7 +715,7 @@ pub(crate) enum BodySourceRef<'a> { } impl<'a> io::Read for BodySourceRef<'a> { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { match self { BodySourceRef::HandlerShared(v) => v.read(buf), BodySourceRef::HandlerOwned(v) => v.read(buf), diff --git a/src/proxy.rs b/src/proxy.rs index 3b68c2f8..7f0b4a6f 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -1,4 +1,4 @@ -use core::convert::TryFrom; +use core::convert::{TryFrom, TryInto}; use alloc::boxed::Box; use alloc::fmt; @@ -6,6 +6,7 @@ use alloc::string::ToString; use alloc::sync::Arc; use base64::prelude::BASE64_STANDARD; use base64::Engine; +use no_std_io::io::Write as _; use ureq_proto::parser::try_parse_response; use http::{StatusCode, Uri}; @@ -116,6 +117,7 @@ impl Proxy { /// * `HTTP_PROXY` /// /// Returns `None` if no environment variable is set or the URI is invalid. + #[cfg(feature = "std")] pub fn try_from_env() -> Option { macro_rules! try_env { ($($env:literal),+) => { @@ -140,6 +142,11 @@ impl Proxy { None } + #[cfg(not(feature = "std"))] + pub fn try_from_env() -> Option { + None + } + pub(crate) fn proto(&self) -> Proto { self.inner.proto } diff --git a/src/request.rs b/src/request.rs index a9995087..9f484962 100644 --- a/src/request.rs +++ b/src/request.rs @@ -4,7 +4,7 @@ use core::ops::{Deref, DerefMut}; use alloc::boxed::Box; use alloc::fmt; -use alloc::string::String; +use alloc::string::{String, ToString}; use alloc::vec::Vec; use http::{HeaderName, HeaderValue, Method, Request, Response, Uri, Version}; @@ -524,6 +524,8 @@ impl fmt::Debug for RequestBuilder { mod test { use core::time::Duration; + use alloc::string::ToString; + use crate::get; use crate::test::init_test_log; diff --git a/src/run.rs b/src/run.rs index 80ab10f8..9767198a 100644 --- a/src/run.rs +++ b/src/run.rs @@ -659,7 +659,7 @@ impl BodyHandler { } impl io::Read for BodyHandler { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.do_read(buf).map_err(|e| e.into_io()) } } diff --git a/src/send_body.rs b/src/send_body.rs index 06f6fc5b..50293d32 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -1,4 +1,5 @@ use no_std_io::io; +use no_std_io::io::Read as _; use crate::body::{Body, BodyReader}; use crate::http; use crate::util::private::Private; @@ -43,7 +44,7 @@ impl<'a> SendBody<'a> { Ok(Self::from_owned_reader(io::Cursor::new(json))) } - pub(crate) fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + pub(crate) fn read(&mut self, buf: &mut [u8]) -> io::Result { let n = match &mut self.inner { BodyInner::None => { return Ok(0); diff --git a/src/tls/rustls.rs b/src/tls/rustls.rs index 78557d0a..f5cb215d 100644 --- a/src/tls/rustls.rs +++ b/src/tls/rustls.rs @@ -1,3 +1,4 @@ +use core::convert::TryInto; use core::fmt; use alloc::boxed::Box; diff --git a/src/unversioned/resolver.rs b/src/unversioned/resolver.rs index 85c121dc..2d41219b 100644 --- a/src/unversioned/resolver.rs +++ b/src/unversioned/resolver.rs @@ -14,6 +14,7 @@ use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4}; use alloc::fmt; +use alloc::vec::IntoIter; use alloc::string::String; use http::uri::{Authority, Scheme}; use http::Uri; @@ -102,7 +103,7 @@ impl Resolver for DefaultResolver { let iter = if use_sync { trace!("Resolve: {}", addr); // When timeout is not set, we do not spawn any threads. - addr.to_socket_addrs()? + addr.to_socket_addrs()? // TODO: no_std? } else { trace!("Resolve with timeout ({:?}): {} ", timeout, addr); resolve_async(addr, timeout)? @@ -130,7 +131,12 @@ impl Resolver for DefaultResolver { } } -// TODO: very no_std unfriendly function? +#[cfg(not(feature = "std"))] +fn resolve_async(addr: String, timeout: NextTimeout) -> Result, Error> { + unimplemented!() +} + +#[cfg(feature = "std")] fn resolve_async(addr: String, timeout: NextTimeout) -> Result, Error> { // TODO(martin): On Linux we have getaddrinfo_a which is a libc async way of // doing host lookup. We should make a subcrate that uses a native async method diff --git a/src/unversioned/transport/io.rs b/src/unversioned/transport/io.rs index 288bbf0c..1ca32e7a 100644 --- a/src/unversioned/transport/io.rs +++ b/src/unversioned/transport/io.rs @@ -55,7 +55,7 @@ impl TransportAdapter { } impl io::Read for TransportAdapter { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.transport .await_input(self.timeout) .map_err(|e| e.into_io())?; @@ -70,7 +70,7 @@ impl io::Read for TransportAdapter { } impl io::Write for TransportAdapter { - fn write(&mut self, buf: &[u8]) -> anyhow::Result { + fn write(&mut self, buf: &[u8]) -> io::Result { let output = self.transport.buffers().output(); let max = buf.len().min(output.len()); @@ -82,7 +82,7 @@ impl io::Write for TransportAdapter { Ok(max) } - fn flush(&mut self) -> anyhow::Result<()> { + fn flush(&mut self) -> io::Result<()> { Ok(()) } } diff --git a/src/unversioned/transport/tcp.rs b/src/unversioned/transport/tcp.rs index f7c7d4d8..de546e65 100644 --- a/src/unversioned/transport/tcp.rs +++ b/src/unversioned/transport/tcp.rs @@ -2,6 +2,7 @@ use core::net::SocketAddr; use alloc::boxed::Box; use alloc::fmt; +use no_std_io::io; use crate::config::Config; use crate::util::IoResultExt; @@ -119,8 +120,8 @@ fn maybe_update_timeout( timeout: NextTimeout, previous: &mut Option, stream: &TcpStream, - f: impl Fn(&TcpStream, Option) -> anyhow::Result<()>, -) -> anyhow::Result<()> { + f: impl Fn(&TcpStream, Option) -> io::Result<()>, +) -> io::Result<()> { let maybe_timeout = timeout.not_zero(); if maybe_timeout != *previous { diff --git a/src/unversioned/transport/test.rs b/src/unversioned/transport/test.rs index 0b8d62fa..d4526add 100644 --- a/src/unversioned/transport/test.rs +++ b/src/unversioned/transport/test.rs @@ -54,7 +54,7 @@ impl Connector for TestConnector { impl TestHandler { fn new( pattern: &'static str, - handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> anyhow::Result<()> + Send + Sync + 'static, + handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> io::Result<()> + Send + Sync + 'static, ) -> Self { TestHandler { pattern, @@ -93,7 +93,7 @@ pub fn set_handler(pattern: &'static str, status: u16, headers: &[(&str, &str)], #[derive(Clone)] struct TestHandler { pattern: &'static str, - handler: Arc, &mut dyn Write) -> anyhow::Result<()> + Sync + Send>, + handler: Arc, &mut dyn Write) -> io::Result<()> + Sync + Send>, } fn test_run( @@ -397,7 +397,7 @@ const HTTPBIN_JSON: &str = r#" struct RxRead(Receiver>); impl io::Read for RxRead { - fn read(&mut self, buf: &mut [u8]) -> anyhow::Result { + fn read(&mut self, buf: &mut [u8]) -> io::Result { let v = match self.0.recv() { Ok(v) => v, Err(_) => return Ok(0), // remote side is gone @@ -412,14 +412,14 @@ impl io::Read for RxRead { struct TxWrite(mpsc::SyncSender>); impl io::Write for TxWrite { - fn write(&mut self, buf: &[u8]) -> anyhow::Result { + fn write(&mut self, buf: &[u8]) -> io::Result { self.0 .send(buf.to_vec()) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; Ok(buf.len()) } - fn flush(&mut self) -> anyhow::Result<()> { + fn flush(&mut self) -> io::Result<()> { Ok(()) } } diff --git a/src/util.rs b/src/util.rs index dc859f96..db47d40f 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,3 +1,5 @@ +use core::convert::TryFrom; + use alloc::fmt; use alloc::vec::Vec; use http::header::{ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING}; @@ -5,6 +7,7 @@ use http::header::{CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE}; use http::header::{DATE, HOST, LOCATION, SERVER, TRANSFER_ENCODING, USER_AGENT}; use http::uri::{Authority, Scheme}; use http::{HeaderMap, HeaderName, HeaderValue, Method, Response, Uri, Version}; +use no_std_io::io; use crate::http; use crate::proxy::Proto; @@ -64,12 +67,12 @@ pub(crate) trait IoResultExt { fn normalize_would_block(self) -> Self; } -impl IoResultExt for anyhow::Result { +impl IoResultExt for io::Result { fn normalize_would_block(self) -> Self { match self { Ok(v) => Ok(v), - Err(e) if e.kind() == ErrorKind::WouldBlock => { - Err(io::Error::new(ErrorKind::TimedOut, e)) + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + Err(io::Error::new(io::ErrorKind::TimedOut, e)) } Err(e) => Err(e), } From 161fdec031ebd5a4619994dba7e50690535e46c0 Mon Sep 17 00:00:00 2001 From: Brandon Ros Date: Sun, 1 Dec 2024 01:04:47 -0500 Subject: [PATCH 7/7] no_std_transport --- src/lib.rs | 5 +++++ src/send_body.rs | 4 +--- src/unversioned/mod.rs | 5 +++++ src/unversioned/no_std_transport/mod.rs | 0 4 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 src/unversioned/no_std_transport/mod.rs diff --git a/src/lib.rs b/src/lib.rs index a92270d8..ff718439 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -484,8 +484,13 @@ mod util; pub mod unversioned; use unversioned::resolver; + +#[cfg(feature = "std")] use unversioned::transport; +#[cfg(not(feature = "std"))] +use unversioned::no_std_transport as transport; + pub mod middleware; #[cfg(feature = "_tls")] diff --git a/src/send_body.rs b/src/send_body.rs index 50293d32..caddba7a 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -204,9 +204,7 @@ impl_into_body!(&TcpStream, Reader); impl_into_body!(File, Reader); impl_into_body!(TcpStream, Reader); impl_into_body!(Stdin, Reader); - -// MSRV 1.78 -// impl_into_body!(&Stdin, Reader); +impl_into_body!(&Stdin, Reader); #[cfg(target_family = "unix")] use std::os::unix::net::UnixStream; diff --git a/src/unversioned/mod.rs b/src/unversioned/mod.rs index e145846d..9577bd17 100644 --- a/src/unversioned/mod.rs +++ b/src/unversioned/mod.rs @@ -10,4 +10,9 @@ //! is no set timeline for this. pub mod resolver; + +#[cfg(feature = "std")] pub mod transport; + +#[cfg(not(feature = "std"))] +pub mod no_std_transport; diff --git a/src/unversioned/no_std_transport/mod.rs b/src/unversioned/no_std_transport/mod.rs new file mode 100644 index 00000000..e69de29b