mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-14 06:30:32 +02:00
Compare commits
11 Commits
utils-v1.0
...
service-v1
Author | SHA1 | Date | |
---|---|---|---|
|
5940731ef0 | ||
|
aed5fecc8a | ||
|
a751899aad | ||
|
fa800aeba3 | ||
|
2f89483635 | ||
|
3048073919 | ||
|
4bbba803c1 | ||
|
4dcdeb6795 | ||
|
3b4f222242 | ||
|
7c5fa25b23 | ||
|
3551d6674d |
@@ -10,6 +10,7 @@ members = [
|
||||
"actix-testing",
|
||||
"actix-threadpool",
|
||||
"actix-tls",
|
||||
"actix-tracing",
|
||||
"actix-utils",
|
||||
"router",
|
||||
"string",
|
||||
|
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.2] - 2020-01-15
|
||||
|
||||
* Fix actix-service 1.0.3 compatibility
|
||||
|
||||
## [1.0.1] - 2019-12-15
|
||||
|
||||
* Fix trust-dns-resolver compilation
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-connect"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix connect - tcp connector service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -10,7 +10,6 @@ documentation = "https://docs.rs/actix-connect/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["openssl", "rustls", "uri"]
|
||||
@@ -32,12 +31,12 @@ rustls = ["rust-tls", "tokio-rustls", "webpki"]
|
||||
uri = ["http"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "1.0.0"
|
||||
actix-service = "1.0.3"
|
||||
actix-codec = "0.2.0"
|
||||
actix-utils = "1.0.3"
|
||||
actix-utils = "1.0.6"
|
||||
actix-rt = "1.0.0"
|
||||
derive_more = "0.99.2"
|
||||
either = "1.5.2"
|
||||
either = "1.5.3"
|
||||
futures = "0.3.1"
|
||||
http = { version = "0.2.0", optional = true }
|
||||
log = "0.4"
|
||||
|
@@ -72,7 +72,7 @@ pub fn start_default_resolver() -> AsyncResolver {
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn new_connector<T: Address>(
|
||||
pub fn new_connector<T: Address + 'static>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
@@ -80,7 +80,7 @@ pub fn new_connector<T: Address>(
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn new_connector_factory<T: Address>(
|
||||
pub fn new_connector_factory<T: Address + 'static>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl ServiceFactory<
|
||||
Config = (),
|
||||
@@ -93,14 +93,14 @@ pub fn new_connector_factory<T: Address>(
|
||||
}
|
||||
|
||||
/// Create connector service with default parameters
|
||||
pub fn default_connector<T: Address>(
|
||||
pub fn default_connector<T: Address + 'static>(
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
pipeline(Resolver::default()).and_then(TcpConnector::new())
|
||||
}
|
||||
|
||||
/// Create connector service factory with default parameters
|
||||
pub fn default_connector_factory<T: Address>() -> impl ServiceFactory<
|
||||
pub fn default_connector_factory<T: Address + 'static>() -> impl ServiceFactory<
|
||||
Config = (),
|
||||
Request = Connect<T>,
|
||||
Response = Connection<T, TcpStream>,
|
||||
|
@@ -42,8 +42,8 @@ impl fmt::Debug for ArbiterCommand {
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Arbiters provide an asynchronous execution environment for actors, functions
|
||||
/// and futures. When an Arbiter is created, they spawn a new OS thread, and
|
||||
/// host an event loop. Some Arbiter functions execute on the current thread.
|
||||
/// and futures. When an Arbiter is created, it spawns a new OS thread, and
|
||||
/// hosts an event loop. Some Arbiter functions execute on the current thread.
|
||||
pub struct Arbiter {
|
||||
sender: UnboundedSender<ArbiterCommand>,
|
||||
thread_handle: Option<thread::JoinHandle<()>>,
|
||||
|
@@ -1,5 +1,18 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.3] - 2020-01-15
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fixed unsoundness in `AndThenService` impl
|
||||
|
||||
## [1.0.2] - 2020-01-08
|
||||
|
||||
### Added
|
||||
|
||||
* Add `into_service` helper function
|
||||
|
||||
|
||||
## [1.0.1] - 2019-12-22
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "1.0.1"
|
||||
version = "1.0.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -10,7 +10,6 @@ documentation = "https://docs.rs/actix-service/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
||||
|
@@ -57,7 +57,7 @@ pub use self::transform::{apply, Transform};
|
||||
///
|
||||
/// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... }
|
||||
///
|
||||
/// fn call(&mut self) -> Self::Future { ... }
|
||||
/// fn call(&mut self, req: Self::Request) -> Self::Future { ... }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -82,7 +82,7 @@ pub trait Service {
|
||||
|
||||
/// Returns `Ready` when the service is able to process requests.
|
||||
///
|
||||
/// If the service is at capacity, then `NotReady` is returned and the task
|
||||
/// If the service is at capacity, then `Pending` is returned and the task
|
||||
/// is notified when the service becomes ready again. This function is
|
||||
/// expected to be called while on a task.
|
||||
///
|
||||
@@ -351,6 +351,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert object of type `T` to a service `S`
|
||||
pub fn into_service<T, S>(tp: T) -> S
|
||||
where
|
||||
S: Service,
|
||||
T: IntoService<S>,
|
||||
{
|
||||
tp.into_service()
|
||||
}
|
||||
|
||||
pub mod dev {
|
||||
pub use crate::and_then::{AndThenService, AndThenServiceFactory};
|
||||
pub use crate::and_then_apply_fn::{AndThenApplyFn, AndThenApplyFnFactory};
|
||||
|
@@ -50,7 +50,7 @@ impl<T: Service> Pipeline<T> {
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoService<U>,
|
||||
U: Service<Request = T::Response, Error = T::Error>,
|
||||
U: Service<Request = T::Response, Error = T::Error> + 'static,
|
||||
{
|
||||
Pipeline {
|
||||
service: AndThenService::new(self.service, service.into_service()),
|
||||
@@ -69,7 +69,7 @@ impl<T: Service> Pipeline<T> {
|
||||
where
|
||||
Self: Sized,
|
||||
I: IntoService<U>,
|
||||
U: Service,
|
||||
U: Service + 'static,
|
||||
F: FnMut(T::Response, &mut U) -> Fut,
|
||||
Fut: Future<Output = Result<Res, Err>>,
|
||||
Err: From<T::Error> + From<U::Error>,
|
||||
@@ -88,7 +88,7 @@ impl<T: Service> Pipeline<T> {
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoService<U>,
|
||||
U: Service<Request = Result<T::Response, T::Error>, Error = T::Error>,
|
||||
U: Service<Request = Result<T::Response, T::Error>, Error = T::Error> + 'static,
|
||||
{
|
||||
Pipeline {
|
||||
service: ThenService::new(self.service, service.into_service()),
|
||||
@@ -179,6 +179,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
|
||||
Error = T::Error,
|
||||
InitError = T::InitError,
|
||||
>,
|
||||
U::Service: 'static,
|
||||
{
|
||||
PipelineFactory {
|
||||
factory: AndThenServiceFactory::new(self.factory, factory.into_factory()),
|
||||
@@ -199,6 +200,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
|
||||
T::Config: Clone,
|
||||
I: IntoServiceFactory<U>,
|
||||
U: ServiceFactory<Config = T::Config, InitError = T::InitError>,
|
||||
U::Service: 'static,
|
||||
F: FnMut(T::Response, &mut U::Service) -> Fut + Clone,
|
||||
Fut: Future<Output = Result<Res, Err>>,
|
||||
Err: From<T::Error> + From<U::Error>,
|
||||
@@ -225,6 +227,7 @@ impl<T: ServiceFactory> PipelineFactory<T> {
|
||||
Error = T::Error,
|
||||
InitError = T::InitError,
|
||||
>,
|
||||
U::Service: 'static,
|
||||
{
|
||||
PipelineFactory {
|
||||
factory: ThenServiceFactory::new(self.factory, factory.into_factory()),
|
||||
|
27
actix-tracing/Cargo.toml
Normal file
27
actix-tracing/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "actix-tracing"
|
||||
version = "0.1.0"
|
||||
authors = ["Rajasekharan Vengalil <avranju@gmail.com>"]
|
||||
description = "Support for tokio tracing with Actix services"
|
||||
keywords = ["network", "framework", "tracing"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-tracing/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_tracing"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "1.0"
|
||||
futures-util = "0.3"
|
||||
tracing = "0.1"
|
||||
tracing-futures = "0.2"
|
||||
|
||||
[dev_dependencies]
|
||||
actix-rt = "1.0"
|
||||
slab = "0.4"
|
261
actix-tracing/src/lib.rs
Normal file
261
actix-tracing/src/lib.rs
Normal file
@@ -0,0 +1,261 @@
|
||||
//! Actix tracing - support for tokio tracing with Actix services.
|
||||
#![deny(rust_2018_idioms, warnings)]
|
||||
|
||||
use std::marker::PhantomData;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_service::{
|
||||
apply, dev::ApplyTransform, IntoServiceFactory, Service, ServiceFactory, Transform,
|
||||
};
|
||||
use futures_util::future::{ok, Either, Ready};
|
||||
use tracing_futures::{Instrument, Instrumented};
|
||||
|
||||
/// A `Service` implementation that automatically enters/exits tracing spans
|
||||
/// for the wrapped inner service.
|
||||
#[derive(Clone)]
|
||||
pub struct TracingService<S, F> {
|
||||
inner: S,
|
||||
make_span: F,
|
||||
}
|
||||
|
||||
impl<S, F> TracingService<S, F> {
|
||||
pub fn new(inner: S, make_span: F) -> Self {
|
||||
TracingService { inner, make_span }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F> Service for TracingService<S, F>
|
||||
where
|
||||
S: Service,
|
||||
F: Fn(&S::Request) -> Option<tracing::Span>,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = Either<S::Future, Instrumented<S::Future>>;
|
||||
|
||||
fn poll_ready(&mut self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.inner.poll_ready(ctx)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let span = (self.make_span)(&req);
|
||||
let _enter = span.as_ref().map(|s| s.enter());
|
||||
|
||||
let fut = self.inner.call(req);
|
||||
|
||||
// make a child span to track the future's execution
|
||||
if let Some(span) = span
|
||||
.clone()
|
||||
.map(|span| tracing::span!(parent: &span, tracing::Level::INFO, "future"))
|
||||
{
|
||||
Either::Right(fut.instrument(span))
|
||||
} else {
|
||||
Either::Left(fut)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Transform` implementation that wraps services with a [`TracingService`].
|
||||
///
|
||||
/// [`TracingService`]: struct.TracingService.html
|
||||
pub struct TracingTransform<S, U, F> {
|
||||
make_span: F,
|
||||
_p: PhantomData<fn(S, U)>,
|
||||
}
|
||||
|
||||
impl<S, U, F> TracingTransform<S, U, F> {
|
||||
pub fn new(make_span: F) -> Self {
|
||||
TracingTransform {
|
||||
make_span,
|
||||
_p: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, U, F> Transform<S> for TracingTransform<S, U, F>
|
||||
where
|
||||
S: Service,
|
||||
U: ServiceFactory<
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = S::Error,
|
||||
Service = S,
|
||||
>,
|
||||
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Transform = TracingService<S, F>;
|
||||
type InitError = U::InitError;
|
||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(TracingService::new(service, self.make_span.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps the provided service factory with a transform that automatically
|
||||
/// enters/exits the given span.
|
||||
///
|
||||
/// The span to be entered/exited can be provided via a closure. The closure
|
||||
/// is passed in a reference to the request being handled by the service.
|
||||
///
|
||||
/// For example:
|
||||
/// ```rust,ignore
|
||||
/// let traced_service = trace(
|
||||
/// web_service,
|
||||
/// |req: &Request| Some(span!(Level::INFO, "request", req.id))
|
||||
/// );
|
||||
/// ```
|
||||
pub fn trace<S, U, F>(
|
||||
service_factory: U,
|
||||
make_span: F,
|
||||
) -> ApplyTransform<TracingTransform<S::Service, S, F>, S>
|
||||
where
|
||||
S: ServiceFactory,
|
||||
F: Fn(&S::Request) -> Option<tracing::Span> + Clone,
|
||||
U: IntoServiceFactory<S>,
|
||||
{
|
||||
apply(
|
||||
TracingTransform::new(make_span),
|
||||
service_factory.into_factory(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use actix_service::{fn_factory, fn_service};
|
||||
use slab::Slab;
|
||||
use tracing::{span, Event, Level, Metadata, Subscriber};
|
||||
|
||||
thread_local! {
|
||||
static SPAN: RefCell<Vec<span::Id>> = RefCell::new(Vec::new());
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Stats {
|
||||
entered_spans: BTreeSet<u64>,
|
||||
exited_spans: BTreeSet<u64>,
|
||||
events_count: BTreeMap<u64, usize>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Inner {
|
||||
spans: Slab<&'static Metadata<'static>>,
|
||||
stats: Stats,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct TestSubscriber {
|
||||
inner: Arc<RwLock<Inner>>,
|
||||
}
|
||||
|
||||
impl Subscriber for TestSubscriber {
|
||||
fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn new_span(&self, span: &span::Attributes<'_>) -> span::Id {
|
||||
let id = self.inner.write().unwrap().spans.insert(span.metadata());
|
||||
span::Id::from_u64(id as u64 + 1)
|
||||
}
|
||||
|
||||
fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}
|
||||
|
||||
fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}
|
||||
|
||||
fn event(&self, event: &Event<'_>) {
|
||||
let id = event
|
||||
.parent()
|
||||
.cloned()
|
||||
.or_else(|| SPAN.with(|current_span| current_span.borrow().last().cloned()))
|
||||
.unwrap();
|
||||
|
||||
*self
|
||||
.inner
|
||||
.write()
|
||||
.unwrap()
|
||||
.stats
|
||||
.events_count
|
||||
.entry(id.into_u64())
|
||||
.or_insert(0) += 1;
|
||||
}
|
||||
|
||||
fn enter(&self, span: &span::Id) {
|
||||
self.inner
|
||||
.write()
|
||||
.unwrap()
|
||||
.stats
|
||||
.entered_spans
|
||||
.insert(span.into_u64());
|
||||
|
||||
SPAN.with(|current_span| {
|
||||
current_span.borrow_mut().push(span.clone());
|
||||
});
|
||||
}
|
||||
|
||||
fn exit(&self, span: &span::Id) {
|
||||
self.inner
|
||||
.write()
|
||||
.unwrap()
|
||||
.stats
|
||||
.exited_spans
|
||||
.insert(span.into_u64());
|
||||
|
||||
// we are guaranteed that on any given thread, spans are exited in reverse order
|
||||
SPAN.with(|current_span| {
|
||||
let leaving = current_span
|
||||
.borrow_mut()
|
||||
.pop()
|
||||
.expect("told to exit span when not in span");
|
||||
assert_eq!(
|
||||
&leaving, span,
|
||||
"told to exit span that was not most recently entered"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn service_call() {
|
||||
let service_factory = fn_factory(|| {
|
||||
ok::<_, ()>(fn_service(|req: &'static str| {
|
||||
tracing::event!(Level::TRACE, "It's happening - {}!", req);
|
||||
ok::<_, ()>(())
|
||||
}))
|
||||
});
|
||||
|
||||
let subscriber = TestSubscriber::default();
|
||||
let _guard = tracing::subscriber::set_default(subscriber.clone());
|
||||
|
||||
let span_svc = span!(Level::TRACE, "span_svc");
|
||||
let trace_service_factory = trace(service_factory, |_: &&str| Some(span_svc.clone()));
|
||||
let mut service = trace_service_factory.new_service(()).await.unwrap();
|
||||
service.call("boo").await.unwrap();
|
||||
|
||||
let id = span_svc.id().unwrap().into_u64();
|
||||
assert!(subscriber
|
||||
.inner
|
||||
.read()
|
||||
.unwrap()
|
||||
.stats
|
||||
.entered_spans
|
||||
.contains(&id));
|
||||
assert!(subscriber
|
||||
.inner
|
||||
.read()
|
||||
.unwrap()
|
||||
.stats
|
||||
.exited_spans
|
||||
.contains(&id));
|
||||
assert_eq!(subscriber.inner.read().unwrap().stats.events_count[&id], 1);
|
||||
}
|
||||
}
|
@@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.6] - 2020-01-08
|
||||
|
||||
* Add `Clone` impl for `condition::Waiter`
|
||||
|
||||
## [1.0.5] - 2020-01-08
|
||||
|
||||
* Add `Condition` type.
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "1.0.5"
|
||||
version = "1.0.6"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
|
@@ -14,6 +14,12 @@ struct Inner {
|
||||
data: Slab<Option<LocalWaker>>,
|
||||
}
|
||||
|
||||
impl Default for Condition {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Condition {
|
||||
pub fn new() -> Condition {
|
||||
Condition(Cell::new(Inner { data: Slab::new() }))
|
||||
@@ -51,6 +57,16 @@ pub struct Waiter {
|
||||
inner: Cell<Inner>,
|
||||
}
|
||||
|
||||
impl Clone for Waiter {
|
||||
fn clone(&self) -> Self {
|
||||
let token = unsafe { self.inner.get_mut_unsafe() }.data.insert(None);
|
||||
Waiter {
|
||||
token,
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for Waiter {
|
||||
type Output = ();
|
||||
|
||||
@@ -98,7 +114,14 @@ mod tests {
|
||||
lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
|
||||
Poll::Pending
|
||||
);
|
||||
let mut waiter2 = waiter.clone();
|
||||
assert_eq!(
|
||||
lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
|
||||
Poll::Pending
|
||||
);
|
||||
|
||||
drop(cond);
|
||||
assert_eq!(waiter.await, ());
|
||||
assert_eq!(waiter2.await, ());
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,13 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.4] - 2020-01-14
|
||||
|
||||
* Fix `AsRef<str>` impl
|
||||
|
||||
## [0.1.3] - 2020-01-13
|
||||
|
||||
* Add `PartialEq<T: AsRef<str>>`, `AsRef<[u8]>` impls
|
||||
|
||||
## [0.1.2] - 2019-12-22
|
||||
|
||||
* Fix `new()` method
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "bytestring"
|
||||
version = "0.1.2"
|
||||
version = "0.1.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "A UTF-8 encoded string with Bytes as a storage"
|
||||
keywords = ["actix"]
|
||||
|
@@ -7,7 +7,7 @@ use bytes::Bytes;
|
||||
/// A utf-8 encoded string with [`Bytes`] as a storage.
|
||||
///
|
||||
/// [`Bytes`]: https://docs.rs/bytes/0.5.3/bytes/struct.Bytes.html
|
||||
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
|
||||
#[derive(Clone, Eq, Ord, PartialOrd, Default)]
|
||||
pub struct ByteString(Bytes);
|
||||
|
||||
impl ByteString {
|
||||
@@ -43,6 +43,24 @@ impl PartialEq<str> for ByteString {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<str>> PartialEq<T> for ByteString {
|
||||
fn eq(&self, other: &T) -> bool {
|
||||
&self[..] == other.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for ByteString {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for ByteString {
|
||||
fn as_ref(&self) -> &str {
|
||||
&*self
|
||||
}
|
||||
}
|
||||
|
||||
impl hash::Hash for ByteString {
|
||||
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||
(**self).hash(state);
|
||||
@@ -147,6 +165,14 @@ mod test {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[test]
|
||||
fn test_partial_eq() {
|
||||
let s: ByteString = ByteString::from_static("test");
|
||||
assert_eq!(s, "test");
|
||||
assert_eq!(s, *"test");
|
||||
assert_eq!(s, "test".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new() {
|
||||
let _: ByteString = ByteString::new();
|
||||
@@ -167,6 +193,8 @@ mod test {
|
||||
fn test_from_string() {
|
||||
let s: ByteString = "hello".to_string().into();
|
||||
assert_eq!(&s, "hello");
|
||||
let t: &str = s.as_ref();
|
||||
assert_eq!(t, "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user