diff --git a/.lock b/.lock new file mode 100644 index 00000000..e69de29b diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/crates.js b/crates.js new file mode 100644 index 00000000..c8d6fe08 --- /dev/null +++ b/crates.js @@ -0,0 +1 @@ +window.ALL_CRATES = ["karyon_core","karyon_jsonrpc","karyon_net","karyon_p2p"]; \ No newline at end of file diff --git a/help.html b/help.html new file mode 100644 index 00000000..fd5dfa81 --- /dev/null +++ b/help.html @@ -0,0 +1,2 @@ +Help +

Rustdoc help

Back
\ No newline at end of file diff --git a/karyon_core/all.html b/karyon_core/all.html new file mode 100644 index 00000000..bc029013 --- /dev/null +++ b/karyon_core/all.html @@ -0,0 +1,2 @@ +List of all items in this crate +

List of all items

Structs

Enums

Traits

Functions

Type Aliases

\ No newline at end of file diff --git a/karyon_core/async_util/backoff/index.html b/karyon_core/async_util/backoff/index.html new file mode 100644 index 00000000..65008a8f --- /dev/null +++ b/karyon_core/async_util/backoff/index.html @@ -0,0 +1,3 @@ +karyon_core::async_util::backoff - Rust +

Structs

\ No newline at end of file diff --git a/karyon_core/async_util/backoff/sidebar-items.js b/karyon_core/async_util/backoff/sidebar-items.js new file mode 100644 index 00000000..0cc7671c --- /dev/null +++ b/karyon_core/async_util/backoff/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Backoff"]}; \ No newline at end of file diff --git a/karyon_core/async_util/backoff/struct.Backoff.html b/karyon_core/async_util/backoff/struct.Backoff.html new file mode 100644 index 00000000..0f60f3b3 --- /dev/null +++ b/karyon_core/async_util/backoff/struct.Backoff.html @@ -0,0 +1,51 @@ +Backoff in karyon_core::async_util::backoff - Rust +
pub struct Backoff {
+    base_delay: u64,
+    max_delay: u64,
+    retries: AtomicU32,
+    stop: AtomicBool,
+}
Expand description

Exponential backoff +https://en.wikipedia.org/wiki/Exponential_backoff

+

Examples

+
use karyon_core::async_util::Backoff;
+
+ async {
+    let backoff = Backoff::new(300, 3000);
+
+    loop {
+        backoff.sleep().await;
+     
+        // do something
+        break;
+    }
+
+    backoff.reset();
+
+    // ....
+ };
+
+

Fields§

§base_delay: u64

The base delay in milliseconds for the initial retry.

+
§max_delay: u64

The max delay in milliseconds allowed for a retry.

+
§retries: AtomicU32

Atomic counter

+
§stop: AtomicBool

Stop flag

+

Implementations§

source§

impl Backoff

source

pub fn new(base_delay: u64, max_delay: u64) -> Self

Creates a new Backoff.

+
source

pub async fn sleep(&self) -> u64

Sleep based on the current retry count and delay values. +Retruns the delay value.

+
source

pub fn reset(&self)

Reset the retry counter to 0.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/condvar/index.html b/karyon_core/async_util/condvar/index.html new file mode 100644 index 00000000..0fa783f1 --- /dev/null +++ b/karyon_core/async_util/condvar/index.html @@ -0,0 +1,2 @@ +karyon_core::async_util::condvar - Rust +

Structs

\ No newline at end of file diff --git a/karyon_core/async_util/condvar/sidebar-items.js b/karyon_core/async_util/condvar/sidebar-items.js new file mode 100644 index 00000000..5e8a00d1 --- /dev/null +++ b/karyon_core/async_util/condvar/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["CondVar","CondVarAwait","Wakers"]}; \ No newline at end of file diff --git a/karyon_core/async_util/condvar/struct.CondVar.html b/karyon_core/async_util/condvar/struct.CondVar.html new file mode 100644 index 00000000..0402a333 --- /dev/null +++ b/karyon_core/async_util/condvar/struct.CondVar.html @@ -0,0 +1,66 @@ +CondVar in karyon_core::async_util::condvar - Rust +
pub struct CondVar {
+    inner: Mutex<Wakers>,
+}
Expand description

CondVar is an async version of https://doc.rust-lang.org/std/sync/struct.Condvar.html

+

Example

+
 use std::sync::Arc;
+
+ use smol::lock::Mutex;
+
+ use karyon_core::async_util::CondVar;
+
+  async {
+     
+     let val = Arc::new(Mutex::new(false));
+     let condvar = Arc::new(CondVar::new());
+
+     let val_cloned = val.clone();
+     let condvar_cloned = condvar.clone();
+     smol::spawn(async move {
+         let mut val = val_cloned.lock().await;
+
+         // While the boolean flag is false, wait for a signal.
+         while !*val {
+             val = condvar_cloned.wait(val).await;
+         }
+
+         // ...
+     });
+
+     let condvar_cloned = condvar.clone();
+     smol::spawn(async move {
+         let mut val = val.lock().await;
+
+         // While the boolean flag is false, wait for a signal.
+         while !*val {
+             val = condvar_cloned.wait(val).await;
+         }
+
+         // ...
+     });
+     
+     // Wake up all waiting tasks on this condvar
+     condvar.broadcast();
+  };
+
+

Fields§

§inner: Mutex<Wakers>

Implementations§

source§

impl CondVar

source

pub fn new() -> Self

Creates a new CondVar

+
source

pub async fn wait<'a, T>(&self, g: MutexGuard<'a, T>) -> MutexGuard<'a, T>

Blocks the current task until this condition variable receives a notification.

+
source

pub fn signal(&self)

Wakes up one blocked task waiting on this condvar.

+
source

pub fn broadcast(&self)

Wakes up all blocked tasks waiting on this condvar.

+

Trait Implementations§

source§

impl Default for CondVar

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/condvar/struct.CondVarAwait.html b/karyon_core/async_util/condvar/struct.CondVarAwait.html new file mode 100644 index 00000000..b9b0f2e1 --- /dev/null +++ b/karyon_core/async_util/condvar/struct.CondVarAwait.html @@ -0,0 +1,35 @@ +CondVarAwait in karyon_core::async_util::condvar - Rust +
struct CondVarAwait<'a, T> {
+    id: Option<u16>,
+    condvar: &'a CondVar,
+    guard: Option<MutexGuard<'a, T>>,
+}

Fields§

§id: Option<u16>§condvar: &'a CondVar§guard: Option<MutexGuard<'a, T>>

Implementations§

source§

impl<'a, T> CondVarAwait<'a, T>

source

fn new(condvar: &'a CondVar, guard: MutexGuard<'a, T>) -> Self

Trait Implementations§

source§

impl<'a, T> Drop for CondVarAwait<'a, T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'a, T> Future for CondVarAwait<'a, T>

§

type Output = ()

The type of value produced on completion.
source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempt to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

§

impl<'a, T> !RefUnwindSafe for CondVarAwait<'a, T>

§

impl<'a, T> Send for CondVarAwait<'a, T>
where + T: Send,

§

impl<'a, T> Sync for CondVarAwait<'a, T>
where + T: Sync,

§

impl<'a, T> Unpin for CondVarAwait<'a, T>

§

impl<'a, T> !UnwindSafe for CondVarAwait<'a, T>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<F> FutureExt for F
where + F: Future + ?Sized,

§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
§

fn or<F>(self, other: F) -> Or<Self, F>
where + Self: Sized, + F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
§

fn race<F>(self, other: F) -> Race<Self, F>
where + Self: Sized, + F: Future<Output = Self::Output>,

Returns the result of self or other future, with no preference if both are ready. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches panics while polling the future. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Boxes the future and changes its type to dyn Future + Send + 'a. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Boxes the future and changes its type to dyn Future + 'a. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<F> IntoFuture for F
where + F: Future,

§

type Output = <F as Future>::Output

The output that the future will produce on completion.
§

type IntoFuture = F

Which kind of future are we turning this into?
source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/condvar/struct.Wakers.html b/karyon_core/async_util/condvar/struct.Wakers.html new file mode 100644 index 00000000..ac3304e4 --- /dev/null +++ b/karyon_core/async_util/condvar/struct.Wakers.html @@ -0,0 +1,21 @@ +Wakers in karyon_core::async_util::condvar - Rust +
struct Wakers {
+    wakers: HashMap<u16, Option<Waker>>,
+}
Expand description

Wakers is a helper struct to store the task wakers

+

Fields§

§wakers: HashMap<u16, Option<Waker>>

Implementations§

source§

impl Wakers

source

fn new() -> Self

source

fn put(&mut self, waker: Option<Waker>) -> u16

source

fn delete(&mut self, id: &u16) -> Option<Option<Waker>>

source

fn wake(&mut self, signal: bool)

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/condwait/index.html b/karyon_core/async_util/condwait/index.html new file mode 100644 index 00000000..97010b00 --- /dev/null +++ b/karyon_core/async_util/condwait/index.html @@ -0,0 +1,2 @@ +karyon_core::async_util::condwait - Rust +

Structs

  • CondWait is a wrapper struct for CondVar with a Mutex boolean flag.
\ No newline at end of file diff --git a/karyon_core/async_util/condwait/sidebar-items.js b/karyon_core/async_util/condwait/sidebar-items.js new file mode 100644 index 00000000..a3997ae6 --- /dev/null +++ b/karyon_core/async_util/condwait/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["CondWait"]}; \ No newline at end of file diff --git a/karyon_core/async_util/condwait/struct.CondWait.html b/karyon_core/async_util/condwait/struct.CondWait.html new file mode 100644 index 00000000..7f00c97f --- /dev/null +++ b/karyon_core/async_util/condwait/struct.CondWait.html @@ -0,0 +1,45 @@ +CondWait in karyon_core::async_util::condwait - Rust +
pub struct CondWait {
+    condvar: CondVar,
+    w: Mutex<bool>,
+}
Expand description

CondWait is a wrapper struct for CondVar with a Mutex boolean flag.

+

Example

+
 use std::sync::Arc;
+
+ use karyon_core::async_util::CondWait;
+
+  async {
+     let cond_wait = Arc::new(CondWait::new());
+     let cond_wait_cloned = cond_wait.clone();
+     let task = smol::spawn(async move {
+         cond_wait_cloned.wait().await;
+         // ...
+     });
+
+     cond_wait.signal().await;
+  };
+
+

Fields§

§condvar: CondVar

The CondVar

+
§w: Mutex<bool>

Boolean flag

+

Implementations§

source§

impl CondWait

source

pub fn new() -> Self

Creates a new CondWait.

+
source

pub async fn wait(&self)

Waits for a signal or broadcast.

+
source

pub async fn signal(&self)

Signal a waiting task.

+
source

pub async fn broadcast(&self)

Signal all waiting tasks.

+
source

pub async fn reset(&self)

Reset the boolean flag value to false.

+

Trait Implementations§

source§

impl Default for CondWait

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/enum.Either.html b/karyon_core/async_util/enum.Either.html new file mode 100644 index 00000000..872e68d7 --- /dev/null +++ b/karyon_core/async_util/enum.Either.html @@ -0,0 +1,34 @@ +Either in karyon_core::async_util - Rust +
pub enum Either<T1, T2> {
+    Left(T1),
+    Right(T2),
+}
Expand description

The return value from the select function, indicating which future +completed first.

+

Variants§

§

Left(T1)

§

Right(T2)

Trait Implementations§

source§

impl<T1: Debug, T2: Debug> Debug for Either<T1, T2>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T1, T2> RefUnwindSafe for Either<T1, T2>
where + T1: RefUnwindSafe, + T2: RefUnwindSafe,

§

impl<T1, T2> Send for Either<T1, T2>
where + T1: Send, + T2: Send,

§

impl<T1, T2> Sync for Either<T1, T2>
where + T1: Sync, + T2: Sync,

§

impl<T1, T2> Unpin for Either<T1, T2>
where + T1: Unpin, + T2: Unpin,

§

impl<T1, T2> UnwindSafe for Either<T1, T2>
where + T1: UnwindSafe, + T2: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/enum.TaskResult.html b/karyon_core/async_util/enum.TaskResult.html new file mode 100644 index 00000000..e1030497 --- /dev/null +++ b/karyon_core/async_util/enum.TaskResult.html @@ -0,0 +1,29 @@ +TaskResult in karyon_core::async_util - Rust +
pub enum TaskResult<T> {
+    Completed(T),
+    Cancelled,
+}
Expand description

The result of a spawned task.

+

Variants§

§

Completed(T)

§

Cancelled

Trait Implementations§

source§

impl<T: Debug> Debug for TaskResult<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T: Debug> Display for TaskResult<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for TaskResult<T>
where + T: RefUnwindSafe,

§

impl<T> Send for TaskResult<T>
where + T: Send,

§

impl<T> Sync for TaskResult<T>
where + T: Sync,

§

impl<T> Unpin for TaskResult<T>
where + T: Unpin,

§

impl<T> UnwindSafe for TaskResult<T>
where + T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/fn.select.html b/karyon_core/async_util/fn.select.html new file mode 100644 index 00000000..5508d079 --- /dev/null +++ b/karyon_core/async_util/fn.select.html @@ -0,0 +1,19 @@ +select in karyon_core::async_util - Rust +

Function karyon_core::async_util::select

source ·
pub fn select<T1, T2, F1, F2>(future1: F1, future2: F2) -> Select<F1, F2> 
where + F1: Future<Output = T1>, + F2: Future<Output = T2>,
Expand description

Returns the result of the future that completes first, preferring future1 +if both are ready.

+

Examples

+
use std::future;
+
+use karyon_core::async_util::{select, Either};
+
+ async {
+    let fut1 = future::pending::<String>();
+    let fut2 = future::ready(0);
+    let res = select(fut1, fut2).await;
+    assert!(matches!(res, Either::Right(0)));
+    // ....
+ };
+
+
\ No newline at end of file diff --git a/karyon_core/async_util/fn.timeout.html b/karyon_core/async_util/fn.timeout.html new file mode 100644 index 00000000..9bd37526 --- /dev/null +++ b/karyon_core/async_util/fn.timeout.html @@ -0,0 +1,15 @@ +timeout in karyon_core::async_util - Rust +
pub async fn timeout<T, F>(delay: Duration, future1: F) -> Result<T>
where + F: Future<Output = T>,
Expand description

Waits for a future to complete or times out if it exceeds a specified +duration.

+

Example

+
use std::{future, time::Duration};
+
+use karyon_core::async_util::timeout;
+
+async {
+    let fut = future::pending::<()>();
+    assert!(timeout(Duration::from_millis(100), fut).await.is_err());
+};
+
+
\ No newline at end of file diff --git a/karyon_core/async_util/index.html b/karyon_core/async_util/index.html new file mode 100644 index 00000000..d74442e2 --- /dev/null +++ b/karyon_core/async_util/index.html @@ -0,0 +1,8 @@ +karyon_core::async_util - Rust +

Module karyon_core::async_util

source ·
Expand description

A module containing async utilities that work with the +smol async runtime.

+

Modules

Structs

Enums

  • The return value from the select function, indicating which future +completed first.
  • The result of a spawned task.

Functions

  • Returns the result of the future that completes first, preferring future1 +if both are ready.
  • Waits for a future to complete or times out if it exceeds a specified +duration.
\ No newline at end of file diff --git a/karyon_core/async_util/select/enum.Either.html b/karyon_core/async_util/select/enum.Either.html new file mode 100644 index 00000000..8b171481 --- /dev/null +++ b/karyon_core/async_util/select/enum.Either.html @@ -0,0 +1,34 @@ +Either in karyon_core::async_util::select - Rust +
pub enum Either<T1, T2> {
+    Left(T1),
+    Right(T2),
+}
Expand description

The return value from the select function, indicating which future +completed first.

+

Variants§

§

Left(T1)

§

Right(T2)

Trait Implementations§

source§

impl<T1: Debug, T2: Debug> Debug for Either<T1, T2>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T1, T2> RefUnwindSafe for Either<T1, T2>
where + T1: RefUnwindSafe, + T2: RefUnwindSafe,

§

impl<T1, T2> Send for Either<T1, T2>
where + T1: Send, + T2: Send,

§

impl<T1, T2> Sync for Either<T1, T2>
where + T1: Sync, + T2: Sync,

§

impl<T1, T2> Unpin for Either<T1, T2>
where + T1: Unpin, + T2: Unpin,

§

impl<T1, T2> UnwindSafe for Either<T1, T2>
where + T1: UnwindSafe, + T2: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/select/fn.select.html b/karyon_core/async_util/select/fn.select.html new file mode 100644 index 00000000..aa9c7c0c --- /dev/null +++ b/karyon_core/async_util/select/fn.select.html @@ -0,0 +1,19 @@ +select in karyon_core::async_util::select - Rust +
pub fn select<T1, T2, F1, F2>(future1: F1, future2: F2) -> Select<F1, F2> 
where + F1: Future<Output = T1>, + F2: Future<Output = T2>,
Expand description

Returns the result of the future that completes first, preferring future1 +if both are ready.

+

Examples

+
use std::future;
+
+use karyon_core::async_util::{select, Either};
+
+ async {
+    let fut1 = future::pending::<String>();
+    let fut2 = future::ready(0);
+    let res = select(fut1, fut2).await;
+    assert!(matches!(res, Either::Right(0)));
+    // ....
+ };
+
+
\ No newline at end of file diff --git a/karyon_core/async_util/select/index.html b/karyon_core/async_util/select/index.html new file mode 100644 index 00000000..8bfcdd7d --- /dev/null +++ b/karyon_core/async_util/select/index.html @@ -0,0 +1,4 @@ +karyon_core::async_util::select - Rust +

Structs

Enums

  • The return value from the select function, indicating which future +completed first.

Functions

  • Returns the result of the future that completes first, preferring future1 +if both are ready.
\ No newline at end of file diff --git a/karyon_core/async_util/select/sidebar-items.js b/karyon_core/async_util/select/sidebar-items.js new file mode 100644 index 00000000..d1735c9d --- /dev/null +++ b/karyon_core/async_util/select/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Either"],"fn":["select"],"struct":["Select"]}; \ No newline at end of file diff --git a/karyon_core/async_util/select/struct.Select.html b/karyon_core/async_util/select/struct.Select.html new file mode 100644 index 00000000..2c7f6e0d --- /dev/null +++ b/karyon_core/async_util/select/struct.Select.html @@ -0,0 +1,44 @@ +Select in karyon_core::async_util::select - Rust +
pub struct Select<F1, F2> {
+    future1: F1,
+    future2: F2,
+}

Fields§

§future1: F1§future2: F2

Trait Implementations§

source§

impl<F1: Debug, F2: Debug> Debug for Select<F1, F2>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T1, T2, F1, F2> Future for Select<F1, F2>
where + F1: Future<Output = T1>, + F2: Future<Output = T2>,

§

type Output = Either<T1, T2>

The type of value produced on completion.
source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempt to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
source§

impl<'__pin, F1, F2> Unpin for Select<F1, F2>
where + __Origin<'__pin, F1, F2>: Unpin,

Auto Trait Implementations§

§

impl<F1, F2> RefUnwindSafe for Select<F1, F2>
where + F1: RefUnwindSafe, + F2: RefUnwindSafe,

§

impl<F1, F2> Send for Select<F1, F2>
where + F1: Send, + F2: Send,

§

impl<F1, F2> Sync for Select<F1, F2>
where + F1: Sync, + F2: Sync,

§

impl<F1, F2> UnwindSafe for Select<F1, F2>
where + F1: UnwindSafe, + F2: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<F> FutureExt for F
where + F: Future + ?Sized,

§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where + Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
§

fn or<F>(self, other: F) -> Or<Self, F>
where + Self: Sized, + F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
§

fn race<F>(self, other: F) -> Race<Self, F>
where + Self: Sized, + F: Future<Output = Self::Output>,

Returns the result of self or other future, with no preference if both are ready. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where + Self: Sized + UnwindSafe,

Catches panics while polling the future. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where + Self: Sized + Send + 'a,

Boxes the future and changes its type to dyn Future + Send + 'a. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where + Self: Sized + 'a,

Boxes the future and changes its type to dyn Future + 'a. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<F> IntoFuture for F
where + F: Future,

§

type Output = <F as Future>::Output

The output that the future will produce on completion.
§

type IntoFuture = F

Which kind of future are we turning this into?
source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/sidebar-items.js b/karyon_core/async_util/sidebar-items.js new file mode 100644 index 00000000..3eb889ed --- /dev/null +++ b/karyon_core/async_util/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Either","TaskResult"],"fn":["select","timeout"],"mod":["backoff","condvar","condwait","select","task_group","timeout"],"struct":["Backoff","CondVar","CondWait","TaskGroup"]}; \ No newline at end of file diff --git a/karyon_core/async_util/struct.Backoff.html b/karyon_core/async_util/struct.Backoff.html new file mode 100644 index 00000000..1156ad7f --- /dev/null +++ b/karyon_core/async_util/struct.Backoff.html @@ -0,0 +1,51 @@ +Backoff in karyon_core::async_util - Rust +
pub struct Backoff {
+    base_delay: u64,
+    max_delay: u64,
+    retries: AtomicU32,
+    stop: AtomicBool,
+}
Expand description

Exponential backoff +https://en.wikipedia.org/wiki/Exponential_backoff

+

Examples

+
use karyon_core::async_util::Backoff;
+
+ async {
+    let backoff = Backoff::new(300, 3000);
+
+    loop {
+        backoff.sleep().await;
+     
+        // do something
+        break;
+    }
+
+    backoff.reset();
+
+    // ....
+ };
+
+

Fields§

§base_delay: u64

The base delay in milliseconds for the initial retry.

+
§max_delay: u64

The max delay in milliseconds allowed for a retry.

+
§retries: AtomicU32

Atomic counter

+
§stop: AtomicBool

Stop flag

+

Implementations§

source§

impl Backoff

source

pub fn new(base_delay: u64, max_delay: u64) -> Self

Creates a new Backoff.

+
source

pub async fn sleep(&self) -> u64

Sleep based on the current retry count and delay values. +Retruns the delay value.

+
source

pub fn reset(&self)

Reset the retry counter to 0.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/struct.CondVar.html b/karyon_core/async_util/struct.CondVar.html new file mode 100644 index 00000000..919f97e2 --- /dev/null +++ b/karyon_core/async_util/struct.CondVar.html @@ -0,0 +1,66 @@ +CondVar in karyon_core::async_util - Rust +
pub struct CondVar {
+    inner: Mutex<Wakers>,
+}
Expand description

CondVar is an async version of https://doc.rust-lang.org/std/sync/struct.Condvar.html

+

Example

+
 use std::sync::Arc;
+
+ use smol::lock::Mutex;
+
+ use karyon_core::async_util::CondVar;
+
+  async {
+     
+     let val = Arc::new(Mutex::new(false));
+     let condvar = Arc::new(CondVar::new());
+
+     let val_cloned = val.clone();
+     let condvar_cloned = condvar.clone();
+     smol::spawn(async move {
+         let mut val = val_cloned.lock().await;
+
+         // While the boolean flag is false, wait for a signal.
+         while !*val {
+             val = condvar_cloned.wait(val).await;
+         }
+
+         // ...
+     });
+
+     let condvar_cloned = condvar.clone();
+     smol::spawn(async move {
+         let mut val = val.lock().await;
+
+         // While the boolean flag is false, wait for a signal.
+         while !*val {
+             val = condvar_cloned.wait(val).await;
+         }
+
+         // ...
+     });
+     
+     // Wake up all waiting tasks on this condvar
+     condvar.broadcast();
+  };
+
+

Fields§

§inner: Mutex<Wakers>

Implementations§

source§

impl CondVar

source

pub fn new() -> Self

Creates a new CondVar

+
source

pub async fn wait<'a, T>(&self, g: MutexGuard<'a, T>) -> MutexGuard<'a, T>

Blocks the current task until this condition variable receives a notification.

+
source

pub fn signal(&self)

Wakes up one blocked task waiting on this condvar.

+
source

pub fn broadcast(&self)

Wakes up all blocked tasks waiting on this condvar.

+

Trait Implementations§

source§

impl Default for CondVar

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/struct.CondWait.html b/karyon_core/async_util/struct.CondWait.html new file mode 100644 index 00000000..b5d958c0 --- /dev/null +++ b/karyon_core/async_util/struct.CondWait.html @@ -0,0 +1,45 @@ +CondWait in karyon_core::async_util - Rust +
pub struct CondWait {
+    condvar: CondVar,
+    w: Mutex<bool>,
+}
Expand description

CondWait is a wrapper struct for CondVar with a Mutex boolean flag.

+

Example

+
 use std::sync::Arc;
+
+ use karyon_core::async_util::CondWait;
+
+  async {
+     let cond_wait = Arc::new(CondWait::new());
+     let cond_wait_cloned = cond_wait.clone();
+     let task = smol::spawn(async move {
+         cond_wait_cloned.wait().await;
+         // ...
+     });
+
+     cond_wait.signal().await;
+  };
+
+

Fields§

§condvar: CondVar

The CondVar

+
§w: Mutex<bool>

Boolean flag

+

Implementations§

source§

impl CondWait

source

pub fn new() -> Self

Creates a new CondWait.

+
source

pub async fn wait(&self)

Waits for a signal or broadcast.

+
source

pub async fn signal(&self)

Signal a waiting task.

+
source

pub async fn broadcast(&self)

Signal all waiting tasks.

+
source

pub async fn reset(&self)

Reset the boolean flag value to false.

+

Trait Implementations§

source§

impl Default for CondWait

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/struct.TaskGroup.html b/karyon_core/async_util/struct.TaskGroup.html new file mode 100644 index 00000000..e77f95bb --- /dev/null +++ b/karyon_core/async_util/struct.TaskGroup.html @@ -0,0 +1,55 @@ +TaskGroup in karyon_core::async_util - Rust +
pub struct TaskGroup<'a> {
+    tasks: Mutex<Vec<TaskHandler>>,
+    stop_signal: Arc<CondWait>,
+    executor: Executor<'a>,
+}
Expand description

TaskGroup is a group of spawned tasks.

+

Example

+

+use std::sync::Arc;
+
+use karyon_core::async_util::TaskGroup;
+
+async {
+
+    let ex = Arc::new(smol::Executor::new());
+    let group = TaskGroup::new(ex);
+
+    group.spawn(smol::Timer::never(), |_| async {});
+
+    group.cancel().await;
+
+};
+
+

Fields§

§tasks: Mutex<Vec<TaskHandler>>§stop_signal: Arc<CondWait>§executor: Executor<'a>

Implementations§

source§

impl<'a> TaskGroup<'a>

source

pub fn new(executor: Executor<'a>) -> Self

Creates a new task group

+
source

pub fn spawn<T, Fut, CallbackF, CallbackFut>( + &self, + fut: Fut, + callback: CallbackF +)
where + T: Send + Sync + 'a, + Fut: Future<Output = T> + Send + 'a, + CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'a, + CallbackFut: Future<Output = ()> + Send + 'a,

Spawns a new task and calls the callback after it has completed +or been canceled. The callback will have the TaskResult as a +parameter, indicating whether the task completed or was canceled.

+
source

pub fn is_empty(&self) -> bool

Checks if the task group is empty.

+
source

pub fn len(&self) -> usize

Get the number of the tasks in the group.

+
source

pub async fn cancel(&self)

Cancels all tasks in the group.

+

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for TaskGroup<'a>

§

impl<'a> Send for TaskGroup<'a>

§

impl<'a> Sync for TaskGroup<'a>

§

impl<'a> Unpin for TaskGroup<'a>

§

impl<'a> !UnwindSafe for TaskGroup<'a>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/task_group/enum.TaskResult.html b/karyon_core/async_util/task_group/enum.TaskResult.html new file mode 100644 index 00000000..02384a3b --- /dev/null +++ b/karyon_core/async_util/task_group/enum.TaskResult.html @@ -0,0 +1,29 @@ +TaskResult in karyon_core::async_util::task_group - Rust +
pub enum TaskResult<T> {
+    Completed(T),
+    Cancelled,
+}
Expand description

The result of a spawned task.

+

Variants§

§

Completed(T)

§

Cancelled

Trait Implementations§

source§

impl<T: Debug> Debug for TaskResult<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T: Debug> Display for TaskResult<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for TaskResult<T>
where + T: RefUnwindSafe,

§

impl<T> Send for TaskResult<T>
where + T: Send,

§

impl<T> Sync for TaskResult<T>
where + T: Sync,

§

impl<T> Unpin for TaskResult<T>
where + T: Unpin,

§

impl<T> UnwindSafe for TaskResult<T>
where + T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/task_group/index.html b/karyon_core/async_util/task_group/index.html new file mode 100644 index 00000000..d18d8c7a --- /dev/null +++ b/karyon_core/async_util/task_group/index.html @@ -0,0 +1,2 @@ +karyon_core::async_util::task_group - Rust +

Structs

Enums

\ No newline at end of file diff --git a/karyon_core/async_util/task_group/sidebar-items.js b/karyon_core/async_util/task_group/sidebar-items.js new file mode 100644 index 00000000..c53fd29f --- /dev/null +++ b/karyon_core/async_util/task_group/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["TaskResult"],"struct":["TaskGroup","TaskHandler"]}; \ No newline at end of file diff --git a/karyon_core/async_util/task_group/struct.TaskGroup.html b/karyon_core/async_util/task_group/struct.TaskGroup.html new file mode 100644 index 00000000..6709bc7d --- /dev/null +++ b/karyon_core/async_util/task_group/struct.TaskGroup.html @@ -0,0 +1,55 @@ +TaskGroup in karyon_core::async_util::task_group - Rust +
pub struct TaskGroup<'a> {
+    tasks: Mutex<Vec<TaskHandler>>,
+    stop_signal: Arc<CondWait>,
+    executor: Executor<'a>,
+}
Expand description

TaskGroup is a group of spawned tasks.

+

Example

+

+use std::sync::Arc;
+
+use karyon_core::async_util::TaskGroup;
+
+async {
+
+    let ex = Arc::new(smol::Executor::new());
+    let group = TaskGroup::new(ex);
+
+    group.spawn(smol::Timer::never(), |_| async {});
+
+    group.cancel().await;
+
+};
+
+

Fields§

§tasks: Mutex<Vec<TaskHandler>>§stop_signal: Arc<CondWait>§executor: Executor<'a>

Implementations§

source§

impl<'a> TaskGroup<'a>

source

pub fn new(executor: Executor<'a>) -> Self

Creates a new task group

+
source

pub fn spawn<T, Fut, CallbackF, CallbackFut>( + &self, + fut: Fut, + callback: CallbackF +)
where + T: Send + Sync + 'a, + Fut: Future<Output = T> + Send + 'a, + CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'a, + CallbackFut: Future<Output = ()> + Send + 'a,

Spawns a new task and calls the callback after it has completed +or been canceled. The callback will have the TaskResult as a +parameter, indicating whether the task completed or was canceled.

+
source

pub fn is_empty(&self) -> bool

Checks if the task group is empty.

+
source

pub fn len(&self) -> usize

Get the number of the tasks in the group.

+
source

pub async fn cancel(&self)

Cancels all tasks in the group.

+

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for TaskGroup<'a>

§

impl<'a> Send for TaskGroup<'a>

§

impl<'a> Sync for TaskGroup<'a>

§

impl<'a> Unpin for TaskGroup<'a>

§

impl<'a> !UnwindSafe for TaskGroup<'a>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/task_group/struct.TaskHandler.html b/karyon_core/async_util/task_group/struct.TaskHandler.html new file mode 100644 index 00000000..05fadcac --- /dev/null +++ b/karyon_core/async_util/task_group/struct.TaskHandler.html @@ -0,0 +1,33 @@ +TaskHandler in karyon_core::async_util::task_group - Rust +
pub struct TaskHandler {
+    task: FallibleTask<()>,
+    cancel_flag: Arc<CondWait>,
+}
Expand description

TaskHandler

+

Fields§

§task: FallibleTask<()>§cancel_flag: Arc<CondWait>

Implementations§

source§

impl<'a> TaskHandler

source

fn new<T, Fut, CallbackF, CallbackFut>( + ex: Executor<'a>, + fut: Fut, + callback: CallbackF, + stop_signal: Arc<CondWait> +) -> TaskHandler
where + T: Send + Sync + 'a, + Fut: Future<Output = T> + Send + 'a, + CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'a, + CallbackFut: Future<Output = ()> + Send + 'a,

Creates a new task handle

+
source

async fn cancel(self)

Cancels the task.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/async_util/timeout/fn.timeout.html b/karyon_core/async_util/timeout/fn.timeout.html new file mode 100644 index 00000000..7e113959 --- /dev/null +++ b/karyon_core/async_util/timeout/fn.timeout.html @@ -0,0 +1,15 @@ +timeout in karyon_core::async_util::timeout - Rust +
pub async fn timeout<T, F>(delay: Duration, future1: F) -> Result<T>
where + F: Future<Output = T>,
Expand description

Waits for a future to complete or times out if it exceeds a specified +duration.

+

Example

+
use std::{future, time::Duration};
+
+use karyon_core::async_util::timeout;
+
+async {
+    let fut = future::pending::<()>();
+    assert!(timeout(Duration::from_millis(100), fut).await.is_err());
+};
+
+
\ No newline at end of file diff --git a/karyon_core/async_util/timeout/index.html b/karyon_core/async_util/timeout/index.html new file mode 100644 index 00000000..ba8f4dcc --- /dev/null +++ b/karyon_core/async_util/timeout/index.html @@ -0,0 +1,3 @@ +karyon_core::async_util::timeout - Rust +

Functions

  • Waits for a future to complete or times out if it exceeds a specified +duration.
\ No newline at end of file diff --git a/karyon_core/async_util/timeout/sidebar-items.js b/karyon_core/async_util/timeout/sidebar-items.js new file mode 100644 index 00000000..f8413902 --- /dev/null +++ b/karyon_core/async_util/timeout/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["timeout"]}; \ No newline at end of file diff --git a/karyon_core/crypto/enum.KeyPair.html b/karyon_core/crypto/enum.KeyPair.html new file mode 100644 index 00000000..2909cfbb --- /dev/null +++ b/karyon_core/crypto/enum.KeyPair.html @@ -0,0 +1,25 @@ +KeyPair in karyon_core::crypto - Rust +
pub enum KeyPair {
+    Ed25519(Ed25519KeyPair),
+}

Variants§

Implementations§

source§

impl KeyPair

source

pub fn generate(kp_type: &KeyPairType) -> Self

Generate a new random keypair.

+
source

pub fn sign(&self, msg: &[u8]) -> Vec<u8>

Sign a message using the private key.

+
source

pub fn public(&self) -> PublicKey

Get the public key of this keypair.

+
source

pub fn secret(&self) -> SecretKey

Get the secret key of this keypair.

+

Trait Implementations§

source§

impl Clone for KeyPair

source§

fn clone(&self) -> KeyPair

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/enum.KeyPairType.html b/karyon_core/crypto/enum.KeyPairType.html new file mode 100644 index 00000000..531b9118 --- /dev/null +++ b/karyon_core/crypto/enum.KeyPairType.html @@ -0,0 +1,21 @@ +KeyPairType in karyon_core::crypto - Rust +
pub enum KeyPairType {
+    Ed25519,
+}
Expand description

key cryptography type

+

Variants§

§

Ed25519

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/enum.PublicKey.html b/karyon_core/crypto/enum.PublicKey.html new file mode 100644 index 00000000..dae75d61 --- /dev/null +++ b/karyon_core/crypto/enum.PublicKey.html @@ -0,0 +1,22 @@ +PublicKey in karyon_core::crypto - Rust +
pub enum PublicKey {
+    Ed25519(Ed25519PublicKey),
+}

Variants§

Implementations§

source§

impl PublicKey

source

pub fn from_bytes(kp_type: &KeyPairType, pk: &[u8]) -> Result<Self>

source

pub fn as_bytes(&self) -> &[u8]

source

pub fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>

Verify a signature on a message with this public key.

+

Trait Implementations§

source§

impl Debug for PublicKey

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/index.html b/karyon_core/crypto/index.html new file mode 100644 index 00000000..a3dba642 --- /dev/null +++ b/karyon_core/crypto/index.html @@ -0,0 +1,3 @@ +karyon_core::crypto - Rust +

Module karyon_core::crypto

source ·
Expand description

Collects common cryptographic tools

+

Modules

Structs

Enums

\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/enum.KeyPair.html b/karyon_core/crypto/key_pair/enum.KeyPair.html new file mode 100644 index 00000000..532946ff --- /dev/null +++ b/karyon_core/crypto/key_pair/enum.KeyPair.html @@ -0,0 +1,25 @@ +KeyPair in karyon_core::crypto::key_pair - Rust +
pub enum KeyPair {
+    Ed25519(Ed25519KeyPair),
+}

Variants§

Implementations§

source§

impl KeyPair

source

pub fn generate(kp_type: &KeyPairType) -> Self

Generate a new random keypair.

+
source

pub fn sign(&self, msg: &[u8]) -> Vec<u8>

Sign a message using the private key.

+
source

pub fn public(&self) -> PublicKey

Get the public key of this keypair.

+
source

pub fn secret(&self) -> SecretKey

Get the secret key of this keypair.

+

Trait Implementations§

source§

impl Clone for KeyPair

source§

fn clone(&self) -> KeyPair

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/enum.KeyPairType.html b/karyon_core/crypto/key_pair/enum.KeyPairType.html new file mode 100644 index 00000000..6a382b97 --- /dev/null +++ b/karyon_core/crypto/key_pair/enum.KeyPairType.html @@ -0,0 +1,21 @@ +KeyPairType in karyon_core::crypto::key_pair - Rust +
pub enum KeyPairType {
+    Ed25519,
+}
Expand description

key cryptography type

+

Variants§

§

Ed25519

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/enum.PublicKey.html b/karyon_core/crypto/key_pair/enum.PublicKey.html new file mode 100644 index 00000000..e18c0ff7 --- /dev/null +++ b/karyon_core/crypto/key_pair/enum.PublicKey.html @@ -0,0 +1,22 @@ +PublicKey in karyon_core::crypto::key_pair - Rust +
pub enum PublicKey {
+    Ed25519(Ed25519PublicKey),
+}

Variants§

Implementations§

source§

impl PublicKey

source

pub fn from_bytes(kp_type: &KeyPairType, pk: &[u8]) -> Result<Self>

source

pub fn as_bytes(&self) -> &[u8]

source

pub fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>

Verify a signature on a message with this public key.

+

Trait Implementations§

source§

impl Debug for PublicKey

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/index.html b/karyon_core/crypto/key_pair/index.html new file mode 100644 index 00000000..d711da58 --- /dev/null +++ b/karyon_core/crypto/key_pair/index.html @@ -0,0 +1,2 @@ +karyon_core::crypto::key_pair - Rust +

Structs

Enums

Traits

\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/sidebar-items.js b/karyon_core/crypto/key_pair/sidebar-items.js new file mode 100644 index 00000000..dfe6bcf0 --- /dev/null +++ b/karyon_core/crypto/key_pair/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["KeyPair","KeyPairType","PublicKey"],"struct":["Ed25519KeyPair","Ed25519PublicKey","SecretKey"],"trait":["KeyPairExt","PublicKeyExt"]}; \ No newline at end of file diff --git a/karyon_core/crypto/key_pair/struct.Ed25519KeyPair.html b/karyon_core/crypto/key_pair/struct.Ed25519KeyPair.html new file mode 100644 index 00000000..40689e95 --- /dev/null +++ b/karyon_core/crypto/key_pair/struct.Ed25519KeyPair.html @@ -0,0 +1,19 @@ +Ed25519KeyPair in karyon_core::crypto::key_pair - Rust +
pub struct Ed25519KeyPair(SigningKey);

Tuple Fields§

§0: SigningKey

Implementations§

Trait Implementations§

source§

impl Clone for Ed25519KeyPair

source§

fn clone(&self) -> Ed25519KeyPair

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl KeyPairExt for Ed25519KeyPair

source§

fn sign(&self, msg: &[u8]) -> Vec<u8>

Sign a message using the private key.
source§

fn public(&self) -> PublicKey

Get the public key of this keypair.
source§

fn secret(&self) -> SecretKey

Get the secret key of this keypair.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/struct.Ed25519PublicKey.html b/karyon_core/crypto/key_pair/struct.Ed25519PublicKey.html new file mode 100644 index 00000000..09608910 --- /dev/null +++ b/karyon_core/crypto/key_pair/struct.Ed25519PublicKey.html @@ -0,0 +1,19 @@ +Ed25519PublicKey in karyon_core::crypto::key_pair - Rust +
pub struct Ed25519PublicKey(VerifyingKey);

Tuple Fields§

§0: VerifyingKey

Implementations§

Trait Implementations§

source§

impl Debug for Ed25519PublicKey

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl PublicKeyExt for Ed25519PublicKey

source§

fn as_bytes(&self) -> &[u8]

source§

fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>

Verify a signature on a message with this public key.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/struct.SecretKey.html b/karyon_core/crypto/key_pair/struct.SecretKey.html new file mode 100644 index 00000000..11dd1154 --- /dev/null +++ b/karyon_core/crypto/key_pair/struct.SecretKey.html @@ -0,0 +1,19 @@ +SecretKey in karyon_core::crypto::key_pair - Rust +
pub struct SecretKey(Vec<u8>);
Expand description

A Secret key

+

Tuple Fields§

§0: Vec<u8>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/trait.KeyPairExt.html b/karyon_core/crypto/key_pair/trait.KeyPairExt.html new file mode 100644 index 00000000..fb0eb157 --- /dev/null +++ b/karyon_core/crypto/key_pair/trait.KeyPairExt.html @@ -0,0 +1,11 @@ +KeyPairExt in karyon_core::crypto::key_pair - Rust +
trait KeyPairExt {
+    // Required methods
+    fn sign(&self, msg: &[u8]) -> Vec<u8>;
+    fn public(&self) -> PublicKey;
+    fn secret(&self) -> SecretKey;
+}
Expand description

An extension trait, adding essential methods to all KeyPair types.

+

Required Methods§

source

fn sign(&self, msg: &[u8]) -> Vec<u8>

Sign a message using the private key.

+
source

fn public(&self) -> PublicKey

Get the public key of this keypair.

+
source

fn secret(&self) -> SecretKey

Get the secret key of this keypair.

+

Implementors§

\ No newline at end of file diff --git a/karyon_core/crypto/key_pair/trait.PublicKeyExt.html b/karyon_core/crypto/key_pair/trait.PublicKeyExt.html new file mode 100644 index 00000000..0010aedb --- /dev/null +++ b/karyon_core/crypto/key_pair/trait.PublicKeyExt.html @@ -0,0 +1,8 @@ +PublicKeyExt in karyon_core::crypto::key_pair - Rust +
trait PublicKeyExt {
+    // Required methods
+    fn as_bytes(&self) -> &[u8] ;
+    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>;
+}
Expand description

An extension trait, adding essential methods to all PublicKey types.

+

Required Methods§

source

fn as_bytes(&self) -> &[u8]

source

fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>

Verify a signature on a message with this public key.

+

Implementors§

\ No newline at end of file diff --git a/karyon_core/crypto/sidebar-items.js b/karyon_core/crypto/sidebar-items.js new file mode 100644 index 00000000..8e970cae --- /dev/null +++ b/karyon_core/crypto/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["KeyPair","KeyPairType","PublicKey"],"mod":["key_pair"],"struct":["SecretKey"]}; \ No newline at end of file diff --git a/karyon_core/crypto/struct.SecretKey.html b/karyon_core/crypto/struct.SecretKey.html new file mode 100644 index 00000000..3356f549 --- /dev/null +++ b/karyon_core/crypto/struct.SecretKey.html @@ -0,0 +1,19 @@ +SecretKey in karyon_core::crypto - Rust +
pub struct SecretKey(Vec<u8>);
Expand description

A Secret key

+

Tuple Fields§

§0: Vec<u8>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/error/enum.Error.html b/karyon_core/error/enum.Error.html new file mode 100644 index 00000000..26c1b81c --- /dev/null +++ b/karyon_core/error/enum.Error.html @@ -0,0 +1,30 @@ +Error in karyon_core::error - Rust +

Enum karyon_core::error::Error

source ·
pub enum Error {
+    IO(Error),
+    TryInto(&'static str),
+    Timeout,
+    PathNotFound(&'static str),
+    Ed25519(Error),
+    ChannelSend(String),
+    ChannelRecv(RecvError),
+    BincodeDecode(DecodeError),
+    BincodeEncode(EncodeError),
+}

Variants§

§

IO(Error)

§

TryInto(&'static str)

§

Timeout

§

PathNotFound(&'static str)

§

Ed25519(Error)

§

ChannelSend(String)

§

ChannelRecv(RecvError)

§

BincodeDecode(DecodeError)

§

BincodeEncode(EncodeError)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<DecodeError> for Error

source§

fn from(source: DecodeError) -> Self

Converts to this type from the input type.
source§

impl From<EncodeError> for Error

source§

fn from(source: EncodeError) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<RecvError> for Error

source§

fn from(source: RecvError) -> Self

Converts to this type from the input type.
source§

impl<T> From<SendError<T>> for Error

source§

fn from(error: SendError<T>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/error/index.html b/karyon_core/error/index.html new file mode 100644 index 00000000..3d5291d6 --- /dev/null +++ b/karyon_core/error/index.html @@ -0,0 +1,3 @@ +karyon_core::error - Rust +

Module karyon_core::error

source ·
Expand description

Represents karyon’s Core Error.

+

Enums

Type Aliases

\ No newline at end of file diff --git a/karyon_core/error/sidebar-items.js b/karyon_core/error/sidebar-items.js new file mode 100644 index 00000000..c851f700 --- /dev/null +++ b/karyon_core/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Error"],"type":["Result"]}; \ No newline at end of file diff --git a/karyon_core/error/type.Result.html b/karyon_core/error/type.Result.html new file mode 100644 index 00000000..7e3f43ce --- /dev/null +++ b/karyon_core/error/type.Result.html @@ -0,0 +1,7 @@ +Result in karyon_core::error - Rust +

Type Alias karyon_core::error::Result

source ·
pub type Result<T> = Result<T, Error>;

Aliased Type§

enum Result<T> {
+    Ok(T),
+    Err(Error),
+}

Variants§

§1.0.0

Ok(T)

Contains the success value

+
§1.0.0

Err(Error)

Contains the error value

+
\ No newline at end of file diff --git a/karyon_core/event/index.html b/karyon_core/event/index.html new file mode 100644 index 00000000..f8b63528 --- /dev/null +++ b/karyon_core/event/index.html @@ -0,0 +1,3 @@ +karyon_core::event - Rust +

Module karyon_core::event

source ·
Expand description

event::EventSys implementation.

+

Structs

Traits

Type Aliases

\ No newline at end of file diff --git a/karyon_core/event/sidebar-items.js b/karyon_core/event/sidebar-items.js new file mode 100644 index 00000000..62b58a7c --- /dev/null +++ b/karyon_core/event/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Event","EventListener","EventSys"],"trait":["EventValue","EventValueAny","EventValueTopic"],"type":["ArcEventSys","EventListenerID","Listeners","WeakEventSys"]}; \ No newline at end of file diff --git a/karyon_core/event/struct.Event.html b/karyon_core/event/struct.Event.html new file mode 100644 index 00000000..35e230c1 --- /dev/null +++ b/karyon_core/event/struct.Event.html @@ -0,0 +1,28 @@ +Event in karyon_core::event - Rust +

Struct karyon_core::event::Event

source ·
pub struct Event {
+    created_at: DateTime<Utc>,
+    value: Arc<dyn EventValueAny>,
+}
Expand description

An event within the EventSys.

+

Fields§

§created_at: DateTime<Utc>

The time at which the event was created.

+
§value: Arc<dyn EventValueAny>

The value of the Event.

+

Implementations§

source§

impl Event

source

pub fn new(value: Arc<dyn EventValueAny>) -> Self

Creates a new Event.

+

Trait Implementations§

source§

impl Clone for Event

source§

fn clone(&self) -> Event

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Event

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Event

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Event

§

impl Send for Event

§

impl Sync for Event

§

impl Unpin for Event

§

impl !UnwindSafe for Event

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/event/struct.EventListener.html b/karyon_core/event/struct.EventListener.html new file mode 100644 index 00000000..c978683b --- /dev/null +++ b/karyon_core/event/struct.EventListener.html @@ -0,0 +1,43 @@ +EventListener in karyon_core::event - Rust +
pub struct EventListener<T, E> {
+    id: EventListenerID,
+    recv_chan: Receiver<Event>,
+    event_sys: WeakEventSys<T>,
+    event_id: String,
+    topic: T,
+    phantom: PhantomData<E>,
+}
Expand description

EventListener listens for and receives events from the EventSys.

+

Fields§

§id: EventListenerID§recv_chan: Receiver<Event>§event_sys: WeakEventSys<T>§event_id: String§topic: T§phantom: PhantomData<E>

Implementations§

source§

impl<T, E> EventListener<T, E>
where + T: Hash + Eq + Clone + Debug, + E: EventValueAny + Clone + EventValue,

source

fn new( + id: EventListenerID, + event_sys: WeakEventSys<T>, + recv_chan: Receiver<Event>, + event_id: &str, + topic: &T +) -> EventListener<T, E>

Create a new event listener.

+
source

pub async fn recv(&self) -> Result<E>

Receive the next event.

+
source

pub async fn cancel(&self)

Cancels the listener and removes it from the EventSys.

+
source

pub async fn topic(&self) -> &T

Returns the topic for this event listener.

+
source

pub async fn event_id(&self) -> &String

Returns the event id for this event listener.

+
source

fn event_sys(&self) -> ArcEventSys<T>

Auto Trait Implementations§

§

impl<T, E> !RefUnwindSafe for EventListener<T, E>

§

impl<T, E> Send for EventListener<T, E>
where + E: Send, + T: Send,

§

impl<T, E> Sync for EventListener<T, E>
where + E: Sync, + T: Send + Sync,

§

impl<T, E> !Unpin for EventListener<T, E>

§

impl<T, E> !UnwindSafe for EventListener<T, E>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/event/struct.EventSys.html b/karyon_core/event/struct.EventSys.html new file mode 100644 index 00000000..9a21ee3f --- /dev/null +++ b/karyon_core/event/struct.EventSys.html @@ -0,0 +1,90 @@ +EventSys in karyon_core::event - Rust +

Struct karyon_core::event::EventSys

source ·
pub struct EventSys<T> {
+    listeners: Mutex<HashMap<T, HashMap<String, HashMap<EventListenerID, Sender<Event>>>>>,
+}
Expand description

EventSys supports event emission to registered listeners based on topics.

+

Example

+
use karyon_core::event::{EventSys, EventValueTopic, EventValue};
+
+ async {
+    let event_sys = EventSys::new();
+
+    #[derive(Hash, PartialEq, Eq, Debug, Clone)]
+    enum Topic {
+        TopicA,
+        TopicB,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct A(usize);
+
+   impl EventValue for A {
+        fn id() -> &'static str {
+            "A"
+        }
+    }
+
+    let listener = event_sys.register::<A>(&Topic::TopicA).await;
+
+    event_sys.emit_by_topic(&Topic::TopicA, &A(3)) .await;
+    let msg: A = listener.recv().await.unwrap();
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct B(usize);
+
+    impl EventValue for B {
+        fn id() -> &'static str {
+            "B"
+        }
+    }
+
+    impl EventValueTopic for B {
+        type Topic = Topic;
+        fn topic() -> Self::Topic{
+            Topic::TopicB
+        }
+    }
+
+    let listener = event_sys.register::<B>(&Topic::TopicB).await;
+
+    event_sys.emit(&B(3)) .await;
+    let msg: B = listener.recv().await.unwrap();
+
+    // ....
+ };
+
+

Fields§

§listeners: Mutex<HashMap<T, HashMap<String, HashMap<EventListenerID, Sender<Event>>>>>

Implementations§

source§

impl<T> EventSys<T>
where + T: Hash + Eq + Debug + Clone,

source

pub fn new() -> ArcEventSys<T>

Creates a new EventSys

+
source

pub async fn emit<E: EventValueTopic<Topic = T> + Clone>(&self, value: &E)

Emits an event to the listeners.

+

The event must implement the EventValueTopic trait to indicate the +topic of the event. Otherwise, you can use emit_by_topic().

+
source

pub async fn emit_by_topic<E: EventValueAny + EventValue + Clone>( + &self, + topic: &T, + value: &E +)

Emits an event to the listeners.

+
source

pub async fn register<E: EventValueAny + EventValue + Clone>( + self: &Arc<Self>, + topic: &T +) -> EventListener<T, E>

Registers a new event listener for the given topic.

+
source

async fn remove(&self, topic: &T, event_id: &str, listener_id: &EventListenerID)

Removes the event listener attached to the given topic.

+

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for EventSys<T>

§

impl<T> Send for EventSys<T>
where + T: Send,

§

impl<T> Sync for EventSys<T>
where + T: Send,

§

impl<T> Unpin for EventSys<T>
where + T: Unpin,

§

impl<T> UnwindSafe for EventSys<T>
where + T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/event/trait.EventValue.html b/karyon_core/event/trait.EventValue.html new file mode 100644 index 00000000..1c73f9f4 --- /dev/null +++ b/karyon_core/event/trait.EventValue.html @@ -0,0 +1,7 @@ +EventValue in karyon_core::event - Rust +
pub trait EventValue: EventValueAny {
+    // Required method
+    fn id() -> &'static str
+       where Self: Sized;
+}

Required Methods§

source

fn id() -> &'static str
where + Self: Sized,

Implementors§

\ No newline at end of file diff --git a/karyon_core/event/trait.EventValueAny.html b/karyon_core/event/trait.EventValueAny.html new file mode 100644 index 00000000..0fdbc1c5 --- /dev/null +++ b/karyon_core/event/trait.EventValueAny.html @@ -0,0 +1,5 @@ +EventValueAny in karyon_core::event - Rust +
pub trait EventValueAny: Any + Send + Sync + Debug {
+    // Required method
+    fn value_as_any(&self) -> &dyn Any;
+}

Required Methods§

source

fn value_as_any(&self) -> &dyn Any

Implementors§

source§

impl<T: Send + Sync + Debug + Any> EventValueAny for T

\ No newline at end of file diff --git a/karyon_core/event/trait.EventValueTopic.html b/karyon_core/event/trait.EventValueTopic.html new file mode 100644 index 00000000..c2a580c7 --- /dev/null +++ b/karyon_core/event/trait.EventValueTopic.html @@ -0,0 +1,9 @@ +EventValueTopic in karyon_core::event - Rust +
pub trait EventValueTopic: EventValueAny + EventValue {
+    type Topic;
+
+    // Required method
+    fn topic() -> Self::Topic
+       where Self: Sized;
+}

Required Associated Types§

Required Methods§

source

fn topic() -> Self::Topic
where + Self: Sized,

Implementors§

\ No newline at end of file diff --git a/karyon_core/event/type.ArcEventSys.html b/karyon_core/event/type.ArcEventSys.html new file mode 100644 index 00000000..a0caae33 --- /dev/null +++ b/karyon_core/event/type.ArcEventSys.html @@ -0,0 +1,6 @@ +ArcEventSys in karyon_core::event - Rust +

Type Alias karyon_core::event::ArcEventSys

source ·
pub type ArcEventSys<T> = Arc<EventSys<T>>;

Aliased Type§

struct ArcEventSys<T> {
+    ptr: NonNull<ArcInner<EventSys<T>>>,
+    phantom: PhantomData<ArcInner<EventSys<T>>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<EventSys<T>>>§phantom: PhantomData<ArcInner<EventSys<T>>>§alloc: Global
\ No newline at end of file diff --git a/karyon_core/event/type.EventListenerID.html b/karyon_core/event/type.EventListenerID.html new file mode 100644 index 00000000..6f286c7b --- /dev/null +++ b/karyon_core/event/type.EventListenerID.html @@ -0,0 +1,2 @@ +EventListenerID in karyon_core::event - Rust +
pub type EventListenerID = u16;
\ No newline at end of file diff --git a/karyon_core/event/type.Listeners.html b/karyon_core/event/type.Listeners.html new file mode 100644 index 00000000..b24c9c36 --- /dev/null +++ b/karyon_core/event/type.Listeners.html @@ -0,0 +1,4 @@ +Listeners in karyon_core::event - Rust +

Type Alias karyon_core::event::Listeners

source ·
type Listeners<T> = HashMap<T, HashMap<String, HashMap<EventListenerID, Sender<Event>>>>;

Aliased Type§

struct Listeners<T> {
+    base: HashMap<T, HashMap<String, HashMap<u16, Sender<Event>>>, RandomState>,
+}

Fields§

§base: HashMap<T, HashMap<String, HashMap<u16, Sender<Event>>>, RandomState>
\ No newline at end of file diff --git a/karyon_core/event/type.WeakEventSys.html b/karyon_core/event/type.WeakEventSys.html new file mode 100644 index 00000000..dff0818a --- /dev/null +++ b/karyon_core/event/type.WeakEventSys.html @@ -0,0 +1,5 @@ +WeakEventSys in karyon_core::event - Rust +

Type Alias karyon_core::event::WeakEventSys

source ·
pub type WeakEventSys<T> = Weak<EventSys<T>>;

Aliased Type§

struct WeakEventSys<T> {
+    ptr: NonNull<ArcInner<EventSys<T>>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<EventSys<T>>>§alloc: Global
\ No newline at end of file diff --git a/karyon_core/index.html b/karyon_core/index.html new file mode 100644 index 00000000..9d44c02c --- /dev/null +++ b/karyon_core/index.html @@ -0,0 +1,4 @@ +karyon_core - Rust +

Crate karyon_core

source ·

Modules

Type Aliases

\ No newline at end of file diff --git a/karyon_core/pubsub/index.html b/karyon_core/pubsub/index.html new file mode 100644 index 00000000..69325615 --- /dev/null +++ b/karyon_core/pubsub/index.html @@ -0,0 +1,3 @@ +karyon_core::pubsub - Rust +

Module karyon_core::pubsub

source ·
Expand description

A simple publish-subscribe system Read More

+

Structs

Type Aliases

\ No newline at end of file diff --git a/karyon_core/pubsub/sidebar-items.js b/karyon_core/pubsub/sidebar-items.js new file mode 100644 index 00000000..f20f0a4c --- /dev/null +++ b/karyon_core/pubsub/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Publisher","Subscription"],"type":["ArcPublisher","SubscriptionID"]}; \ No newline at end of file diff --git a/karyon_core/pubsub/struct.Publisher.html b/karyon_core/pubsub/struct.Publisher.html new file mode 100644 index 00000000..71abfef0 --- /dev/null +++ b/karyon_core/pubsub/struct.Publisher.html @@ -0,0 +1,42 @@ +Publisher in karyon_core::pubsub - Rust +
pub struct Publisher<T> {
+    subs: Mutex<HashMap<SubscriptionID, Sender<T>>>,
+}
Expand description

A simple publish-subscribe system.

+ +
use karyon_core::pubsub::{Publisher};
+
+ async {
+    let publisher = Publisher::new();
+     
+    let sub = publisher.subscribe().await;
+     
+    publisher.notify(&String::from("MESSAGE")).await;
+
+    let msg = sub.recv().await;
+
+    // ....
+ };
+  
+

Fields§

§subs: Mutex<HashMap<SubscriptionID, Sender<T>>>

Implementations§

source§

impl<T: Clone> Publisher<T>

source

pub fn new() -> ArcPublisher<T>

Creates a new Publisher

+
source

pub async fn subscribe(self: &Arc<Self>) -> Subscription<T>

Subscribe and return a Subscription

+
source

pub async fn unsubscribe(self: &Arc<Self>, id: &SubscriptionID)

Unsubscribe from the Publisher

+
source

pub async fn notify(self: &Arc<Self>, value: &T)

Notify all subscribers

+

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Publisher<T>

§

impl<T> Send for Publisher<T>
where + T: Send,

§

impl<T> Sync for Publisher<T>
where + T: Send,

§

impl<T> Unpin for Publisher<T>

§

impl<T> UnwindSafe for Publisher<T>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/pubsub/struct.Subscription.html b/karyon_core/pubsub/struct.Subscription.html new file mode 100644 index 00000000..e1283e8b --- /dev/null +++ b/karyon_core/pubsub/struct.Subscription.html @@ -0,0 +1,31 @@ +Subscription in karyon_core::pubsub - Rust +
pub struct Subscription<T> {
+    id: SubscriptionID,
+    recv_chan: Receiver<T>,
+    publisher: ArcPublisher<T>,
+}

Fields§

§id: SubscriptionID§recv_chan: Receiver<T>§publisher: ArcPublisher<T>

Implementations§

source§

impl<T: Clone> Subscription<T>

source

pub fn new( + id: SubscriptionID, + publisher: ArcPublisher<T>, + recv_chan: Receiver<T> +) -> Subscription<T>

Creates a new Subscription

+
source

pub async fn recv(&self) -> Result<T>

Receive a message from the Publisher

+
source

pub async fn unsubscribe(&self)

Unsubscribe from the Publisher

+

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Subscription<T>

§

impl<T> Send for Subscription<T>
where + T: Send,

§

impl<T> Sync for Subscription<T>
where + T: Send,

§

impl<T> !Unpin for Subscription<T>

§

impl<T> !UnwindSafe for Subscription<T>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_core/pubsub/type.ArcPublisher.html b/karyon_core/pubsub/type.ArcPublisher.html new file mode 100644 index 00000000..50c7ef79 --- /dev/null +++ b/karyon_core/pubsub/type.ArcPublisher.html @@ -0,0 +1,6 @@ +ArcPublisher in karyon_core::pubsub - Rust +

Type Alias karyon_core::pubsub::ArcPublisher

source ·
pub type ArcPublisher<T> = Arc<Publisher<T>>;

Aliased Type§

struct ArcPublisher<T> {
+    ptr: NonNull<ArcInner<Publisher<T>>>,
+    phantom: PhantomData<ArcInner<Publisher<T>>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Publisher<T>>>§phantom: PhantomData<ArcInner<Publisher<T>>>§alloc: Global
\ No newline at end of file diff --git a/karyon_core/pubsub/type.SubscriptionID.html b/karyon_core/pubsub/type.SubscriptionID.html new file mode 100644 index 00000000..521cd390 --- /dev/null +++ b/karyon_core/pubsub/type.SubscriptionID.html @@ -0,0 +1,2 @@ +SubscriptionID in karyon_core::pubsub - Rust +
pub type SubscriptionID = u16;
\ No newline at end of file diff --git a/karyon_core/sidebar-items.js b/karyon_core/sidebar-items.js new file mode 100644 index 00000000..224b9de3 --- /dev/null +++ b/karyon_core/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["async_util","crypto","error","event","pubsub","util"],"type":["Executor","GlobalExecutor"]}; \ No newline at end of file diff --git a/karyon_core/type.Executor.html b/karyon_core/type.Executor.html new file mode 100644 index 00000000..6912d95f --- /dev/null +++ b/karyon_core/type.Executor.html @@ -0,0 +1,7 @@ +Executor in karyon_core - Rust +

Type Alias karyon_core::Executor

source ·
pub type Executor<'a> = Arc<Executor<'a>>;
Expand description

A pointer to an Executor

+

Aliased Type§

struct Executor<'a> {
+    ptr: NonNull<ArcInner<Executor<'a>>>,
+    phantom: PhantomData<ArcInner<Executor<'a>>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Executor<'a>>>§phantom: PhantomData<ArcInner<Executor<'a>>>§alloc: Global
\ No newline at end of file diff --git a/karyon_core/type.GlobalExecutor.html b/karyon_core/type.GlobalExecutor.html new file mode 100644 index 00000000..65066f79 --- /dev/null +++ b/karyon_core/type.GlobalExecutor.html @@ -0,0 +1,7 @@ +GlobalExecutor in karyon_core - Rust +

Type Alias karyon_core::GlobalExecutor

source ·
pub type GlobalExecutor = Arc<Executor<'static>>;
Expand description

A Global Executor

+

Aliased Type§

struct GlobalExecutor {
+    ptr: NonNull<ArcInner<Executor<'static>>>,
+    phantom: PhantomData<ArcInner<Executor<'static>>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Executor<'static>>>§phantom: PhantomData<ArcInner<Executor<'static>>>§alloc: Global
\ No newline at end of file diff --git a/karyon_core/util/decode/fn.decode.html b/karyon_core/util/decode/fn.decode.html new file mode 100644 index 00000000..e77582a6 --- /dev/null +++ b/karyon_core/util/decode/fn.decode.html @@ -0,0 +1,4 @@ +decode in karyon_core::util::decode - Rust +

Function karyon_core::util::decode::decode

source ·
pub fn decode<T: Decode>(src: &[u8]) -> Result<(T, usize)>
Expand description

Decodes a given type T from the given slice. returns the decoded value +along with the number of bytes read.

+
\ No newline at end of file diff --git a/karyon_core/util/decode/index.html b/karyon_core/util/decode/index.html new file mode 100644 index 00000000..cae6ea9c --- /dev/null +++ b/karyon_core/util/decode/index.html @@ -0,0 +1,3 @@ +karyon_core::util::decode - Rust +

Module karyon_core::util::decode

source ·

Functions

  • Decodes a given type T from the given slice. returns the decoded value +along with the number of bytes read.
\ No newline at end of file diff --git a/karyon_core/util/decode/sidebar-items.js b/karyon_core/util/decode/sidebar-items.js new file mode 100644 index 00000000..6afa3c39 --- /dev/null +++ b/karyon_core/util/decode/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["decode"]}; \ No newline at end of file diff --git a/karyon_core/util/encode/fn.encode.html b/karyon_core/util/encode/fn.encode.html new file mode 100644 index 00000000..1ce2697f --- /dev/null +++ b/karyon_core/util/encode/fn.encode.html @@ -0,0 +1,3 @@ +encode in karyon_core::util::encode - Rust +

Function karyon_core::util::encode::encode

source ·
pub fn encode<T: Encode>(msg: &T) -> Result<Vec<u8>>
Expand description

Encode the given type T into a Vec<u8>.

+
\ No newline at end of file diff --git a/karyon_core/util/encode/fn.encode_into_slice.html b/karyon_core/util/encode/fn.encode_into_slice.html new file mode 100644 index 00000000..3c0e9db4 --- /dev/null +++ b/karyon_core/util/encode/fn.encode_into_slice.html @@ -0,0 +1,3 @@ +encode_into_slice in karyon_core::util::encode - Rust +
pub fn encode_into_slice<T: Encode>(msg: &T, dst: &mut [u8]) -> Result<()>
Expand description

Encode the given type T into the given slice..

+
\ No newline at end of file diff --git a/karyon_core/util/encode/index.html b/karyon_core/util/encode/index.html new file mode 100644 index 00000000..29faa272 --- /dev/null +++ b/karyon_core/util/encode/index.html @@ -0,0 +1,2 @@ +karyon_core::util::encode - Rust +

Module karyon_core::util::encode

source ·

Functions

\ No newline at end of file diff --git a/karyon_core/util/encode/sidebar-items.js b/karyon_core/util/encode/sidebar-items.js new file mode 100644 index 00000000..852f8826 --- /dev/null +++ b/karyon_core/util/encode/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["encode","encode_into_slice"]}; \ No newline at end of file diff --git a/karyon_core/util/fn.decode.html b/karyon_core/util/fn.decode.html new file mode 100644 index 00000000..cf21310a --- /dev/null +++ b/karyon_core/util/fn.decode.html @@ -0,0 +1,4 @@ +decode in karyon_core::util - Rust +

Function karyon_core::util::decode

source ·
pub fn decode<T: Decode>(src: &[u8]) -> Result<(T, usize)>
Expand description

Decodes a given type T from the given slice. returns the decoded value +along with the number of bytes read.

+
\ No newline at end of file diff --git a/karyon_core/util/fn.encode.html b/karyon_core/util/fn.encode.html new file mode 100644 index 00000000..c8eb70d5 --- /dev/null +++ b/karyon_core/util/fn.encode.html @@ -0,0 +1,3 @@ +encode in karyon_core::util - Rust +

Function karyon_core::util::encode

source ·
pub fn encode<T: Encode>(msg: &T) -> Result<Vec<u8>>
Expand description

Encode the given type T into a Vec<u8>.

+
\ No newline at end of file diff --git a/karyon_core/util/fn.encode_into_slice.html b/karyon_core/util/fn.encode_into_slice.html new file mode 100644 index 00000000..b6563864 --- /dev/null +++ b/karyon_core/util/fn.encode_into_slice.html @@ -0,0 +1,3 @@ +encode_into_slice in karyon_core::util - Rust +
pub fn encode_into_slice<T: Encode>(msg: &T, dst: &mut [u8]) -> Result<()>
Expand description

Encode the given type T into the given slice..

+
\ No newline at end of file diff --git a/karyon_core/util/fn.home_dir.html b/karyon_core/util/fn.home_dir.html new file mode 100644 index 00000000..3e739385 --- /dev/null +++ b/karyon_core/util/fn.home_dir.html @@ -0,0 +1,3 @@ +home_dir in karyon_core::util - Rust +

Function karyon_core::util::home_dir

source ·
pub fn home_dir() -> Result<PathBuf>
Expand description

Returns the user’s home directory as a PathBuf.

+
\ No newline at end of file diff --git a/karyon_core/util/fn.random_16.html b/karyon_core/util/fn.random_16.html new file mode 100644 index 00000000..0d3d1358 --- /dev/null +++ b/karyon_core/util/fn.random_16.html @@ -0,0 +1,3 @@ +random_16 in karyon_core::util - Rust +

Function karyon_core::util::random_16

source ·
pub fn random_16() -> u16
Expand description

Generates and returns a random u16 using rand::rngs::OsRng.

+
\ No newline at end of file diff --git a/karyon_core/util/fn.random_32.html b/karyon_core/util/fn.random_32.html new file mode 100644 index 00000000..13da5fc8 --- /dev/null +++ b/karyon_core/util/fn.random_32.html @@ -0,0 +1,3 @@ +random_32 in karyon_core::util - Rust +

Function karyon_core::util::random_32

source ·
pub fn random_32() -> u32
Expand description

Generates and returns a random u32 using rand::rngs::OsRng.

+
\ No newline at end of file diff --git a/karyon_core/util/fn.tilde_expand.html b/karyon_core/util/fn.tilde_expand.html new file mode 100644 index 00000000..368c4dce --- /dev/null +++ b/karyon_core/util/fn.tilde_expand.html @@ -0,0 +1,3 @@ +tilde_expand in karyon_core::util - Rust +

Function karyon_core::util::tilde_expand

source ·
pub fn tilde_expand(path: &str) -> Result<PathBuf>
Expand description

Expands a tilde (~) in a path and returns the expanded PathBuf.

+
\ No newline at end of file diff --git a/karyon_core/util/index.html b/karyon_core/util/index.html new file mode 100644 index 00000000..4a501fbd --- /dev/null +++ b/karyon_core/util/index.html @@ -0,0 +1,4 @@ +karyon_core::util - Rust +

Module karyon_core::util

source ·
Expand description

A set of helper tools and functions.

+

Modules

Functions

  • Decodes a given type T from the given slice. returns the decoded value +along with the number of bytes read.
  • Encode the given type T into a Vec<u8>.
  • Encode the given type T into the given slice..
  • Returns the user’s home directory as a PathBuf.
  • Generates and returns a random u16 using rand::rngs::OsRng.
  • Generates and returns a random u32 using rand::rngs::OsRng.
  • Expands a tilde (~) in a path and returns the expanded PathBuf.
\ No newline at end of file diff --git a/karyon_core/util/path/fn.home_dir.html b/karyon_core/util/path/fn.home_dir.html new file mode 100644 index 00000000..42f74126 --- /dev/null +++ b/karyon_core/util/path/fn.home_dir.html @@ -0,0 +1,3 @@ +home_dir in karyon_core::util::path - Rust +

Function karyon_core::util::path::home_dir

source ·
pub fn home_dir() -> Result<PathBuf>
Expand description

Returns the user’s home directory as a PathBuf.

+
\ No newline at end of file diff --git a/karyon_core/util/path/fn.tilde_expand.html b/karyon_core/util/path/fn.tilde_expand.html new file mode 100644 index 00000000..76471471 --- /dev/null +++ b/karyon_core/util/path/fn.tilde_expand.html @@ -0,0 +1,3 @@ +tilde_expand in karyon_core::util::path - Rust +
pub fn tilde_expand(path: &str) -> Result<PathBuf>
Expand description

Expands a tilde (~) in a path and returns the expanded PathBuf.

+
\ No newline at end of file diff --git a/karyon_core/util/path/index.html b/karyon_core/util/path/index.html new file mode 100644 index 00000000..41d0fa50 --- /dev/null +++ b/karyon_core/util/path/index.html @@ -0,0 +1,2 @@ +karyon_core::util::path - Rust +

Module karyon_core::util::path

source ·

Functions

  • Returns the user’s home directory as a PathBuf.
  • Expands a tilde (~) in a path and returns the expanded PathBuf.
\ No newline at end of file diff --git a/karyon_core/util/path/sidebar-items.js b/karyon_core/util/path/sidebar-items.js new file mode 100644 index 00000000..3d356690 --- /dev/null +++ b/karyon_core/util/path/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["home_dir","tilde_expand"]}; \ No newline at end of file diff --git a/karyon_core/util/sidebar-items.js b/karyon_core/util/sidebar-items.js new file mode 100644 index 00000000..f3067248 --- /dev/null +++ b/karyon_core/util/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["decode","encode","encode_into_slice","home_dir","random_16","random_32","tilde_expand"],"mod":["decode","encode","path"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/all.html b/karyon_jsonrpc/all.html new file mode 100644 index 00000000..261f9e80 --- /dev/null +++ b/karyon_jsonrpc/all.html @@ -0,0 +1,2 @@ +List of all items in this crate +

List of all items

Structs

Enums

Traits

Macros

Functions

Type Aliases

Constants

\ No newline at end of file diff --git a/karyon_jsonrpc/client/index.html b/karyon_jsonrpc/client/index.html new file mode 100644 index 00000000..183b7305 --- /dev/null +++ b/karyon_jsonrpc/client/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::client - Rust +

Module karyon_jsonrpc::client

source ·

Structs

\ No newline at end of file diff --git a/karyon_jsonrpc/client/sidebar-items.js b/karyon_jsonrpc/client/sidebar-items.js new file mode 100644 index 00000000..78b6e29b --- /dev/null +++ b/karyon_jsonrpc/client/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Client","ClientConfig"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/client/struct.Client.html b/karyon_jsonrpc/client/struct.Client.html new file mode 100644 index 00000000..4ed662bd --- /dev/null +++ b/karyon_jsonrpc/client/struct.Client.html @@ -0,0 +1,28 @@ +Client in karyon_jsonrpc::client - Rust +
pub struct Client {
+    codec: Codec,
+    config: ClientConfig,
+}
Expand description

Represents an RPC client

+

Fields§

§codec: Codec§config: ClientConfig

Implementations§

source§

impl Client

source

pub fn new<C: ToConn>(conn: C, config: ClientConfig) -> Self

Creates a new RPC client by passing a Tcp, Unix, or Tls connection.

+
source

pub async fn call<T: Serialize + DeserializeOwned, V: DeserializeOwned>( + &self, + method: &str, + params: T +) -> Result<V, Error>

Calls the provided method, waits for the response, and returns the result.

+

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/client/struct.ClientConfig.html b/karyon_jsonrpc/client/struct.ClientConfig.html new file mode 100644 index 00000000..56ed113d --- /dev/null +++ b/karyon_jsonrpc/client/struct.ClientConfig.html @@ -0,0 +1,21 @@ +ClientConfig in karyon_jsonrpc::client - Rust +
pub struct ClientConfig {
+    pub timeout: Option<u64>,
+}
Expand description

Represents client config

+

Fields§

§timeout: Option<u64>

Trait Implementations§

source§

impl Default for ClientConfig

source§

fn default() -> ClientConfig

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/codec/constant.DEFAULT_BUFFER_SIZE.html b/karyon_jsonrpc/codec/constant.DEFAULT_BUFFER_SIZE.html new file mode 100644 index 00000000..f68508bd --- /dev/null +++ b/karyon_jsonrpc/codec/constant.DEFAULT_BUFFER_SIZE.html @@ -0,0 +1,2 @@ +DEFAULT_BUFFER_SIZE in karyon_jsonrpc::codec - Rust +
const DEFAULT_BUFFER_SIZE: usize = 1024;
\ No newline at end of file diff --git a/karyon_jsonrpc/codec/constant.DEFAULT_MAX_ALLOWED_BUFFER_SIZE.html b/karyon_jsonrpc/codec/constant.DEFAULT_MAX_ALLOWED_BUFFER_SIZE.html new file mode 100644 index 00000000..aa73e168 --- /dev/null +++ b/karyon_jsonrpc/codec/constant.DEFAULT_MAX_ALLOWED_BUFFER_SIZE.html @@ -0,0 +1,2 @@ +DEFAULT_MAX_ALLOWED_BUFFER_SIZE in karyon_jsonrpc::codec - Rust +
const DEFAULT_MAX_ALLOWED_BUFFER_SIZE: usize = _; // 1_048_576usize
\ No newline at end of file diff --git a/karyon_jsonrpc/codec/index.html b/karyon_jsonrpc/codec/index.html new file mode 100644 index 00000000..693e8a91 --- /dev/null +++ b/karyon_jsonrpc/codec/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::codec - Rust +

Module karyon_jsonrpc::codec

source ·

Structs

Constants

\ No newline at end of file diff --git a/karyon_jsonrpc/codec/sidebar-items.js b/karyon_jsonrpc/codec/sidebar-items.js new file mode 100644 index 00000000..02c1569b --- /dev/null +++ b/karyon_jsonrpc/codec/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["DEFAULT_BUFFER_SIZE","DEFAULT_MAX_ALLOWED_BUFFER_SIZE"],"struct":["Codec","CodecConfig"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/codec/struct.Codec.html b/karyon_jsonrpc/codec/struct.Codec.html new file mode 100644 index 00000000..4ba9402b --- /dev/null +++ b/karyon_jsonrpc/codec/struct.Codec.html @@ -0,0 +1,30 @@ +Codec in karyon_jsonrpc::codec - Rust +

Struct karyon_jsonrpc::codec::Codec

source ·
pub struct Codec {
+    conn: Conn,
+    config: CodecConfig,
+}

Fields§

§conn: Conn§config: CodecConfig

Implementations§

source§

impl Codec

source

pub fn new(conn: Conn, config: CodecConfig) -> Self

Creates a new Codec

+
source

pub async fn read_until(&self, buffer: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes into buffer until the 0x0A byte or EOF is +reached.

+

If successful, this function will return the total number of bytes read.

+
source

pub async fn write_all(&self, buf: &[u8]) -> Result<(), Error>

Writes an entire buffer into the given connection.

+
source

pub async fn read_until_with_timeout( + &self, + buffer: &mut Vec<u8>, + t: u64 +) -> Result<usize, Error>

Auto Trait Implementations§

§

impl !RefUnwindSafe for Codec

§

impl Send for Codec

§

impl Sync for Codec

§

impl Unpin for Codec

§

impl !UnwindSafe for Codec

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/codec/struct.CodecConfig.html b/karyon_jsonrpc/codec/struct.CodecConfig.html new file mode 100644 index 00000000..1a8f3017 --- /dev/null +++ b/karyon_jsonrpc/codec/struct.CodecConfig.html @@ -0,0 +1,25 @@ +CodecConfig in karyon_jsonrpc::codec - Rust +
pub struct CodecConfig {
+    pub default_buffer_size: usize,
+    pub max_allowed_buffer_size: usize,
+}
Expand description

Represents Codec config

+

Fields§

§default_buffer_size: usize§max_allowed_buffer_size: usize

The maximum allowed buffer size to receive a message. If set to zero, +there will be no size limit.

+

Trait Implementations§

source§

impl Clone for CodecConfig

source§

fn clone(&self) -> CodecConfig

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Default for CodecConfig

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/constant.JSONRPC_VERSION.html b/karyon_jsonrpc/constant.JSONRPC_VERSION.html new file mode 100644 index 00000000..7b5ec0df --- /dev/null +++ b/karyon_jsonrpc/constant.JSONRPC_VERSION.html @@ -0,0 +1,2 @@ +JSONRPC_VERSION in karyon_jsonrpc - Rust +
pub(crate) const JSONRPC_VERSION: &str = "2.0";
\ No newline at end of file diff --git a/karyon_jsonrpc/enum.Endpoint.html b/karyon_jsonrpc/enum.Endpoint.html new file mode 100644 index 00000000..43a88963 --- /dev/null +++ b/karyon_jsonrpc/enum.Endpoint.html @@ -0,0 +1,50 @@ +Endpoint in karyon_jsonrpc - Rust +
pub enum Endpoint {
+    Udp(Addr, u16),
+    Tcp(Addr, u16),
+    Tls(Addr, u16),
+    Ws(Addr, u16),
+    Unix(String),
+}
Expand description

Endpoint defines generic network endpoints for karyon.

+

Example

+
use std::net::SocketAddr;
+
+use karyon_net::Endpoint;
+
+let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+let socketaddr: SocketAddr = "127.0.0.1:3000".parse().unwrap();
+let endpoint =  Endpoint::new_udp_addr(&socketaddr);
+
+

Variants§

§

Udp(Addr, u16)

§

Tcp(Addr, u16)

§

Tls(Addr, u16)

§

Ws(Addr, u16)

§

Unix(String)

Implementations§

source§

impl Endpoint

source

pub fn new_tcp_addr(addr: &SocketAddr) -> Endpoint

Creates a new TCP endpoint from a SocketAddr.

+
source

pub fn new_udp_addr(addr: &SocketAddr) -> Endpoint

Creates a new UDP endpoint from a SocketAddr.

+
source

pub fn new_tls_addr(addr: &SocketAddr) -> Endpoint

Creates a new TLS endpoint from a SocketAddr.

+
source

pub fn new_ws_addr(addr: &SocketAddr) -> Endpoint

Creates a new WS endpoint from a SocketAddr.

+
source

pub fn new_unix_addr(addr: &SocketAddr) -> Endpoint

Creates a new Unix endpoint from a UnixSocketAddress.

+
source

pub fn port(&self) -> Result<&u16, Error>

Returns the Port of the endpoint.

+
source

pub fn addr(&self) -> Result<&Addr, Error>

Returns the Addr of the endpoint.

+

Trait Implementations§

source§

impl Clone for Endpoint

source§

fn clone(&self) -> Endpoint

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Display for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl FromStr for Endpoint

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Endpoint, <Endpoint as FromStr>::Err>

Parses a string s to return a value of this type. Read more
source§

impl Hash for Endpoint

source§

fn hash<__H>(&self, state: &mut __H)
where + __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Endpoint

source§

fn eq(&self, other: &Endpoint) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl Eq for Endpoint

source§

impl StructuralEq for Endpoint

source§

impl StructuralPartialEq for Endpoint

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/enum.JsonRPCError.html b/karyon_jsonrpc/enum.JsonRPCError.html new file mode 100644 index 00000000..4d95f65e --- /dev/null +++ b/karyon_jsonrpc/enum.JsonRPCError.html @@ -0,0 +1,31 @@ +JsonRPCError in karyon_jsonrpc - Rust +
pub enum JsonRPCError {
+    IO(Error),
+    CallError(i32, String),
+    RPCMethodError(i32, &'static str),
+    InvalidParams(&'static str),
+    InvalidRequest(&'static str),
+    ParseJSON(Error),
+    InvalidMsg(&'static str),
+    KaryonCore(Error),
+    KaryonNet(NetError),
+}
Expand description

Represents karyon’s jsonrpc Error.

+

Variants§

§

IO(Error)

§

CallError(i32, String)

§

RPCMethodError(i32, &'static str)

§

InvalidParams(&'static str)

§

InvalidRequest(&'static str)

§

ParseJSON(Error)

§

InvalidMsg(&'static str)

§

KaryonCore(Error)

§

KaryonNet(NetError)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: NetError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/error/enum.Error.html b/karyon_jsonrpc/error/enum.Error.html new file mode 100644 index 00000000..f202cae4 --- /dev/null +++ b/karyon_jsonrpc/error/enum.Error.html @@ -0,0 +1,31 @@ +Error in karyon_jsonrpc::error - Rust +
pub enum Error {
+    IO(Error),
+    CallError(i32, String),
+    RPCMethodError(i32, &'static str),
+    InvalidParams(&'static str),
+    InvalidRequest(&'static str),
+    ParseJSON(Error),
+    InvalidMsg(&'static str),
+    KaryonCore(Error),
+    KaryonNet(NetError),
+}
Expand description

Represents karyon’s jsonrpc Error.

+

Variants§

§

IO(Error)

§

CallError(i32, String)

§

RPCMethodError(i32, &'static str)

§

InvalidParams(&'static str)

§

InvalidRequest(&'static str)

§

ParseJSON(Error)

§

InvalidMsg(&'static str)

§

KaryonCore(Error)

§

KaryonNet(NetError)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: NetError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/error/index.html b/karyon_jsonrpc/error/index.html new file mode 100644 index 00000000..a2625250 --- /dev/null +++ b/karyon_jsonrpc/error/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::error - Rust +

Module karyon_jsonrpc::error

source ·

Enums

  • Represents karyon’s jsonrpc Error.

Type Aliases

\ No newline at end of file diff --git a/karyon_jsonrpc/error/sidebar-items.js b/karyon_jsonrpc/error/sidebar-items.js new file mode 100644 index 00000000..c851f700 --- /dev/null +++ b/karyon_jsonrpc/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Error"],"type":["Result"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/error/type.Result.html b/karyon_jsonrpc/error/type.Result.html new file mode 100644 index 00000000..bb4b8a71 --- /dev/null +++ b/karyon_jsonrpc/error/type.Result.html @@ -0,0 +1,7 @@ +Result in karyon_jsonrpc::error - Rust +

Type Alias karyon_jsonrpc::error::Result

source ·
pub type Result<T> = Result<T, Error>;

Aliased Type§

enum Result<T> {
+    Ok(T),
+    Err(Error),
+}

Variants§

§1.0.0

Ok(T)

Contains the success value

+
§1.0.0

Err(Error)

Contains the error value

+
\ No newline at end of file diff --git a/karyon_jsonrpc/index.html b/karyon_jsonrpc/index.html new file mode 100644 index 00000000..d55a6c23 --- /dev/null +++ b/karyon_jsonrpc/index.html @@ -0,0 +1,58 @@ +karyon_jsonrpc - Rust +

Crate karyon_jsonrpc

source ·
Expand description

A fast and lightweight async implementation of JSON-RPC +2.0, supporting the Tcp and Unix protocols.

+

Example

+
use std::sync::Arc;
+
+use serde_json::Value;
+use smol::net::{TcpStream, TcpListener};
+
+use karyon_jsonrpc::{JsonRPCError, Server, Client, register_service, ServerConfig, ClientConfig};
+
+struct HelloWorld {}
+
+impl HelloWorld {
+    async fn say_hello(&self, params: Value) -> Result<Value, JsonRPCError> {
+        let msg: String = serde_json::from_value(params)?;
+        Ok(serde_json::json!(format!("Hello {msg}!")))
+    }
+
+    async fn foo(&self, params: Value) -> Result<Value, JsonRPCError> {
+        Ok(serde_json::json!("foo!"))
+    }
+
+    async fn bar(&self, params: Value) -> Result<Value, JsonRPCError> {
+        Ok(serde_json::json!("bar!"))
+    }
+}
+
+// Server
+async {
+    let ex = Arc::new(smol::Executor::new());
+
+    // Creates a new server
+    let listener = TcpListener::bind("127.0.0.1:60000").await.unwrap();
+    let config = ServerConfig::default();
+    let server = Server::new(listener, config, ex.clone());
+
+    // Register the HelloWorld service
+    register_service!(HelloWorld, say_hello, foo, bar);
+    server.attach_service(HelloWorld{});
+
+    // Starts the server
+    ex.run(server.start());
+};
+
+// Client
+async {
+
+    // Creates a new client
+    let conn = TcpStream::connect("127.0.0.1:60000").await.unwrap();
+    let config = ClientConfig::default();
+    let client = Client::new(conn, config);
+
+    let result: String = client.call("HelloWorld.say_hello", "world".to_string()).await.unwrap();
+};
+
+

Modules

Macros

Structs

Enums

  • Endpoint defines generic network endpoints for karyon.
  • Represents karyon’s jsonrpc Error.

Constants

Traits

  • Defines the interface for an RPC service.

Type Aliases

\ No newline at end of file diff --git a/karyon_jsonrpc/macro.register_service!.html b/karyon_jsonrpc/macro.register_service!.html new file mode 100644 index 00000000..b1121cc7 --- /dev/null +++ b/karyon_jsonrpc/macro.register_service!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.register_service.html...

+ + + \ No newline at end of file diff --git a/karyon_jsonrpc/macro.register_service.html b/karyon_jsonrpc/macro.register_service.html new file mode 100644 index 00000000..832f2d61 --- /dev/null +++ b/karyon_jsonrpc/macro.register_service.html @@ -0,0 +1,24 @@ +register_service in karyon_jsonrpc - Rust +
macro_rules! register_service {
+    ($t:ty, $($m:ident),*) => { ... };
+}
Expand description

Implements the RPCService trait for a provided type.

+

Example

+
use serde_json::Value;
+
+use karyon_jsonrpc::{JsonRPCError, register_service};
+
+struct Hello {}
+
+impl Hello {
+    async fn foo(&self, params: Value) -> Result<Value, JsonRPCError> {
+        Ok(serde_json::json!("foo!"))
+    }
+
+    async fn bar(&self, params: Value) -> Result<Value, JsonRPCError> {
+        Ok(serde_json::json!("bar!"))
+    }
+}
+
+register_service!(Hello, foo, bar);
+
+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/constant.INTERNAL_ERROR_CODE.html b/karyon_jsonrpc/message/constant.INTERNAL_ERROR_CODE.html new file mode 100644 index 00000000..b45da494 --- /dev/null +++ b/karyon_jsonrpc/message/constant.INTERNAL_ERROR_CODE.html @@ -0,0 +1,3 @@ +INTERNAL_ERROR_CODE in karyon_jsonrpc::message - Rust +
pub const INTERNAL_ERROR_CODE: i32 = -32603;
Expand description

Internal error: Internal JSON-RPC error.

+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/constant.INVALID_PARAMS_ERROR_CODE.html b/karyon_jsonrpc/message/constant.INVALID_PARAMS_ERROR_CODE.html new file mode 100644 index 00000000..0b8c4987 --- /dev/null +++ b/karyon_jsonrpc/message/constant.INVALID_PARAMS_ERROR_CODE.html @@ -0,0 +1,3 @@ +INVALID_PARAMS_ERROR_CODE in karyon_jsonrpc::message - Rust +
pub const INVALID_PARAMS_ERROR_CODE: i32 = -32602;
Expand description

Invalid params: Invalid method parameter(s).

+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/constant.INVALID_REQUEST_ERROR_CODE.html b/karyon_jsonrpc/message/constant.INVALID_REQUEST_ERROR_CODE.html new file mode 100644 index 00000000..ecec5c9a --- /dev/null +++ b/karyon_jsonrpc/message/constant.INVALID_REQUEST_ERROR_CODE.html @@ -0,0 +1,3 @@ +INVALID_REQUEST_ERROR_CODE in karyon_jsonrpc::message - Rust +
pub const INVALID_REQUEST_ERROR_CODE: i32 = -32600;
Expand description

Invalid request: The JSON sent is not a valid Request object.

+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/constant.METHOD_NOT_FOUND_ERROR_CODE.html b/karyon_jsonrpc/message/constant.METHOD_NOT_FOUND_ERROR_CODE.html new file mode 100644 index 00000000..3c1d7a19 --- /dev/null +++ b/karyon_jsonrpc/message/constant.METHOD_NOT_FOUND_ERROR_CODE.html @@ -0,0 +1,3 @@ +METHOD_NOT_FOUND_ERROR_CODE in karyon_jsonrpc::message - Rust +
pub const METHOD_NOT_FOUND_ERROR_CODE: i32 = -32601;
Expand description

Method not found: The method does not exist / is not available.

+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/constant.PARSE_ERROR_CODE.html b/karyon_jsonrpc/message/constant.PARSE_ERROR_CODE.html new file mode 100644 index 00000000..3428a414 --- /dev/null +++ b/karyon_jsonrpc/message/constant.PARSE_ERROR_CODE.html @@ -0,0 +1,3 @@ +PARSE_ERROR_CODE in karyon_jsonrpc::message - Rust +
pub const PARSE_ERROR_CODE: i32 = -32700;
Expand description

Parse error: Invalid JSON was received by the server.

+
\ No newline at end of file diff --git a/karyon_jsonrpc/message/index.html b/karyon_jsonrpc/message/index.html new file mode 100644 index 00000000..addab3ca --- /dev/null +++ b/karyon_jsonrpc/message/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::message - Rust +

Module karyon_jsonrpc::message

source ·

Structs

Constants

\ No newline at end of file diff --git a/karyon_jsonrpc/message/sidebar-items.js b/karyon_jsonrpc/message/sidebar-items.js new file mode 100644 index 00000000..0263947b --- /dev/null +++ b/karyon_jsonrpc/message/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["INTERNAL_ERROR_CODE","INVALID_PARAMS_ERROR_CODE","INVALID_REQUEST_ERROR_CODE","METHOD_NOT_FOUND_ERROR_CODE","PARSE_ERROR_CODE"],"struct":["Error","Notification","Request","Response"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/message/struct.Error.html b/karyon_jsonrpc/message/struct.Error.html new file mode 100644 index 00000000..6781b49d --- /dev/null +++ b/karyon_jsonrpc/message/struct.Error.html @@ -0,0 +1,27 @@ +Error in karyon_jsonrpc::message - Rust +
pub struct Error {
+    pub code: i32,
+    pub message: String,
+    pub data: Option<Value>,
+}

Fields§

§code: i32§message: String§data: Option<Value>

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Error

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Serialize for Error

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> DeserializeOwned for T
where + T: for<'de> Deserialize<'de>,

\ No newline at end of file diff --git a/karyon_jsonrpc/message/struct.Notification.html b/karyon_jsonrpc/message/struct.Notification.html new file mode 100644 index 00000000..9d989872 --- /dev/null +++ b/karyon_jsonrpc/message/struct.Notification.html @@ -0,0 +1,27 @@ +Notification in karyon_jsonrpc::message - Rust +
pub struct Notification {
+    pub jsonrpc: String,
+    pub method: String,
+    pub params: Option<Value>,
+}

Fields§

§jsonrpc: String§method: String§params: Option<Value>

Trait Implementations§

source§

impl Debug for Notification

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Notification

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Notification

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Serialize for Notification

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> DeserializeOwned for T
where + T: for<'de> Deserialize<'de>,

\ No newline at end of file diff --git a/karyon_jsonrpc/message/struct.Request.html b/karyon_jsonrpc/message/struct.Request.html new file mode 100644 index 00000000..73a1a2c4 --- /dev/null +++ b/karyon_jsonrpc/message/struct.Request.html @@ -0,0 +1,28 @@ +Request in karyon_jsonrpc::message - Rust +
pub struct Request {
+    pub jsonrpc: String,
+    pub method: String,
+    pub params: Value,
+    pub id: Value,
+}

Fields§

§jsonrpc: String§method: String§params: Value§id: Value

Trait Implementations§

source§

impl Debug for Request

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Request

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Request

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Serialize for Request

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> DeserializeOwned for T
where + T: for<'de> Deserialize<'de>,

\ No newline at end of file diff --git a/karyon_jsonrpc/message/struct.Response.html b/karyon_jsonrpc/message/struct.Response.html new file mode 100644 index 00000000..f23f5362 --- /dev/null +++ b/karyon_jsonrpc/message/struct.Response.html @@ -0,0 +1,28 @@ +Response in karyon_jsonrpc::message - Rust +
pub struct Response {
+    pub jsonrpc: String,
+    pub result: Option<Value>,
+    pub error: Option<Error>,
+    pub id: Option<Value>,
+}

Fields§

§jsonrpc: String§result: Option<Value>§error: Option<Error>§id: Option<Value>

Trait Implementations§

source§

impl Debug for Response

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for Response

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Response

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Serialize for Response

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> DeserializeOwned for T
where + T: for<'de> Deserialize<'de>,

\ No newline at end of file diff --git a/karyon_jsonrpc/server/constant.FAILED_TO_PARSE_ERROR_MSG.html b/karyon_jsonrpc/server/constant.FAILED_TO_PARSE_ERROR_MSG.html new file mode 100644 index 00000000..4adad03f --- /dev/null +++ b/karyon_jsonrpc/server/constant.FAILED_TO_PARSE_ERROR_MSG.html @@ -0,0 +1,2 @@ +FAILED_TO_PARSE_ERROR_MSG in karyon_jsonrpc::server - Rust +
pub const FAILED_TO_PARSE_ERROR_MSG: &str = "Failed to parse";
\ No newline at end of file diff --git a/karyon_jsonrpc/server/constant.INTERNAL_ERROR_MSG.html b/karyon_jsonrpc/server/constant.INTERNAL_ERROR_MSG.html new file mode 100644 index 00000000..9b2b35e3 --- /dev/null +++ b/karyon_jsonrpc/server/constant.INTERNAL_ERROR_MSG.html @@ -0,0 +1,2 @@ +INTERNAL_ERROR_MSG in karyon_jsonrpc::server - Rust +
pub const INTERNAL_ERROR_MSG: &str = "Internal error";
\ No newline at end of file diff --git a/karyon_jsonrpc/server/constant.INVALID_REQUEST_ERROR_MSG.html b/karyon_jsonrpc/server/constant.INVALID_REQUEST_ERROR_MSG.html new file mode 100644 index 00000000..50836ab0 --- /dev/null +++ b/karyon_jsonrpc/server/constant.INVALID_REQUEST_ERROR_MSG.html @@ -0,0 +1,2 @@ +INVALID_REQUEST_ERROR_MSG in karyon_jsonrpc::server - Rust +
pub const INVALID_REQUEST_ERROR_MSG: &str = "Invalid request";
\ No newline at end of file diff --git a/karyon_jsonrpc/server/constant.METHOD_NOT_FOUND_ERROR_MSG.html b/karyon_jsonrpc/server/constant.METHOD_NOT_FOUND_ERROR_MSG.html new file mode 100644 index 00000000..4d504174 --- /dev/null +++ b/karyon_jsonrpc/server/constant.METHOD_NOT_FOUND_ERROR_MSG.html @@ -0,0 +1,2 @@ +METHOD_NOT_FOUND_ERROR_MSG in karyon_jsonrpc::server - Rust +
pub const METHOD_NOT_FOUND_ERROR_MSG: &str = "Method not found";
\ No newline at end of file diff --git a/karyon_jsonrpc/server/fn.pack_err_res.html b/karyon_jsonrpc/server/fn.pack_err_res.html new file mode 100644 index 00000000..74e5cd41 --- /dev/null +++ b/karyon_jsonrpc/server/fn.pack_err_res.html @@ -0,0 +1,2 @@ +pack_err_res in karyon_jsonrpc::server - Rust +
fn pack_err_res(code: i32, msg: &str, id: Option<Value>) -> Response
\ No newline at end of file diff --git a/karyon_jsonrpc/server/index.html b/karyon_jsonrpc/server/index.html new file mode 100644 index 00000000..8af71e3f --- /dev/null +++ b/karyon_jsonrpc/server/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::server - Rust +

Module karyon_jsonrpc::server

source ·

Structs

Constants

Functions

\ No newline at end of file diff --git a/karyon_jsonrpc/server/sidebar-items.js b/karyon_jsonrpc/server/sidebar-items.js new file mode 100644 index 00000000..85ea4bdd --- /dev/null +++ b/karyon_jsonrpc/server/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["FAILED_TO_PARSE_ERROR_MSG","INTERNAL_ERROR_MSG","INVALID_REQUEST_ERROR_MSG","METHOD_NOT_FOUND_ERROR_MSG"],"fn":["pack_err_res"],"struct":["Server","ServerConfig"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/server/struct.Server.html b/karyon_jsonrpc/server/struct.Server.html new file mode 100644 index 00000000..33c335da --- /dev/null +++ b/karyon_jsonrpc/server/struct.Server.html @@ -0,0 +1,35 @@ +Server in karyon_jsonrpc::server - Rust +
pub struct Server<'a> {
+    listener: Listener,
+    services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>,
+    task_group: TaskGroup<'a>,
+    config: ServerConfig,
+}
Expand description

Represents an RPC server

+

Fields§

§listener: Listener§services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>§task_group: TaskGroup<'a>§config: ServerConfig

Implementations§

source§

impl<'a> Server<'a>

source

pub fn new<T: ToListener>( + listener: T, + config: ServerConfig, + ex: Executor<'a> +) -> Arc<Self>

Creates a new RPC server by passing a listener. It supports Tcp, Unix, and Tls.

+
source

pub fn local_endpoint(&self) -> Result<Endpoint, Error>

Returns the local endpoint.

+
source

pub async fn start(self: Arc<Self>) -> Result<(), Error>

Starts the RPC server

+
source

pub async fn attach_service(&self, service: impl RPCService + 'a)

Attach a new service to the RPC server

+
source

pub async fn shutdown(&self)

Shuts down the RPC server

+
source

async fn handle_conn(self: &Arc<Self>, conn: Conn) -> Result<(), Error>

Handles a new connection

+
source

async fn handle_request(&self, buffer: &[u8]) -> Response

Handles a request

+

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Server<'a>

§

impl<'a> Send for Server<'a>

§

impl<'a> Sync for Server<'a>

§

impl<'a> Unpin for Server<'a>

§

impl<'a> !UnwindSafe for Server<'a>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/server/struct.ServerConfig.html b/karyon_jsonrpc/server/struct.ServerConfig.html new file mode 100644 index 00000000..8b4d43a9 --- /dev/null +++ b/karyon_jsonrpc/server/struct.ServerConfig.html @@ -0,0 +1,21 @@ +ServerConfig in karyon_jsonrpc::server - Rust +
pub struct ServerConfig {
+    codec_config: CodecConfig,
+}
Expand description

RPC server config

+

Fields§

§codec_config: CodecConfig

Trait Implementations§

source§

impl Default for ServerConfig

source§

fn default() -> ServerConfig

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/service/index.html b/karyon_jsonrpc/service/index.html new file mode 100644 index 00000000..58922eb3 --- /dev/null +++ b/karyon_jsonrpc/service/index.html @@ -0,0 +1,2 @@ +karyon_jsonrpc::service - Rust +

Module karyon_jsonrpc::service

source ·

Traits

  • Defines the interface for an RPC service.

Type Aliases

\ No newline at end of file diff --git a/karyon_jsonrpc/service/sidebar-items.js b/karyon_jsonrpc/service/sidebar-items.js new file mode 100644 index 00000000..2060887a --- /dev/null +++ b/karyon_jsonrpc/service/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"trait":["RPCService"],"type":["RPCMethod","RPCMethodOutput"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/service/trait.RPCService.html b/karyon_jsonrpc/service/trait.RPCService.html new file mode 100644 index 00000000..79fb79e7 --- /dev/null +++ b/karyon_jsonrpc/service/trait.RPCService.html @@ -0,0 +1,7 @@ +RPCService in karyon_jsonrpc::service - Rust +
pub trait RPCService: Sync + Send {
+    // Required methods
+    fn get_method<'a>(&'a self, name: &'a str) -> Option<RPCMethod<'_>>;
+    fn name(&self) -> String;
+}
Expand description

Defines the interface for an RPC service.

+

Required Methods§

source

fn get_method<'a>(&'a self, name: &'a str) -> Option<RPCMethod<'_>>

source

fn name(&self) -> String

Implementors§

\ No newline at end of file diff --git a/karyon_jsonrpc/service/type.RPCMethod.html b/karyon_jsonrpc/service/type.RPCMethod.html new file mode 100644 index 00000000..d8016e08 --- /dev/null +++ b/karyon_jsonrpc/service/type.RPCMethod.html @@ -0,0 +1,3 @@ +RPCMethod in karyon_jsonrpc::service - Rust +

Type Alias karyon_jsonrpc::service::RPCMethod

source ·
pub type RPCMethod<'a> = Box<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>;
Expand description

Represents the RPC method

+

Aliased Type§

struct RPCMethod<'a>(Unique<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>, Global);

Fields§

§0: Unique<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>§1: Global
\ No newline at end of file diff --git a/karyon_jsonrpc/service/type.RPCMethodOutput.html b/karyon_jsonrpc/service/type.RPCMethodOutput.html new file mode 100644 index 00000000..a22c4afb --- /dev/null +++ b/karyon_jsonrpc/service/type.RPCMethodOutput.html @@ -0,0 +1,2 @@ +RPCMethodOutput in karyon_jsonrpc::service - Rust +
type RPCMethodOutput<'a> = Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>>;

Aliased Type§

struct RPCMethodOutput<'a> { /* private fields */ }
\ No newline at end of file diff --git a/karyon_jsonrpc/sidebar-items.js b/karyon_jsonrpc/sidebar-items.js new file mode 100644 index 00000000..651ef2e7 --- /dev/null +++ b/karyon_jsonrpc/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["JSONRPC_VERSION"],"enum":["Endpoint","JsonRPCError"],"macro":["register_service"],"mod":["client","codec","error","message","server","service"],"struct":["Client","ClientConfig","CodecConfig","Server","ServerConfig"],"trait":["RPCService"],"type":["RPCMethod"]}; \ No newline at end of file diff --git a/karyon_jsonrpc/struct.Client.html b/karyon_jsonrpc/struct.Client.html new file mode 100644 index 00000000..0152af15 --- /dev/null +++ b/karyon_jsonrpc/struct.Client.html @@ -0,0 +1,28 @@ +Client in karyon_jsonrpc - Rust +

Struct karyon_jsonrpc::Client

source ·
pub struct Client {
+    codec: Codec,
+    config: ClientConfig,
+}
Expand description

Represents an RPC client

+

Fields§

§codec: Codec§config: ClientConfig

Implementations§

source§

impl Client

source

pub fn new<C: ToConn>(conn: C, config: ClientConfig) -> Self

Creates a new RPC client by passing a Tcp, Unix, or Tls connection.

+
source

pub async fn call<T: Serialize + DeserializeOwned, V: DeserializeOwned>( + &self, + method: &str, + params: T +) -> Result<V, Error>

Calls the provided method, waits for the response, and returns the result.

+

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/struct.ClientConfig.html b/karyon_jsonrpc/struct.ClientConfig.html new file mode 100644 index 00000000..9d796e37 --- /dev/null +++ b/karyon_jsonrpc/struct.ClientConfig.html @@ -0,0 +1,21 @@ +ClientConfig in karyon_jsonrpc - Rust +
pub struct ClientConfig {
+    pub timeout: Option<u64>,
+}
Expand description

Represents client config

+

Fields§

§timeout: Option<u64>

Trait Implementations§

source§

impl Default for ClientConfig

source§

fn default() -> ClientConfig

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/struct.CodecConfig.html b/karyon_jsonrpc/struct.CodecConfig.html new file mode 100644 index 00000000..ca7dfdb1 --- /dev/null +++ b/karyon_jsonrpc/struct.CodecConfig.html @@ -0,0 +1,25 @@ +CodecConfig in karyon_jsonrpc - Rust +
pub struct CodecConfig {
+    pub default_buffer_size: usize,
+    pub max_allowed_buffer_size: usize,
+}
Expand description

Represents Codec config

+

Fields§

§default_buffer_size: usize§max_allowed_buffer_size: usize

The maximum allowed buffer size to receive a message. If set to zero, +there will be no size limit.

+

Trait Implementations§

source§

impl Clone for CodecConfig

source§

fn clone(&self) -> CodecConfig

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Default for CodecConfig

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/struct.Server.html b/karyon_jsonrpc/struct.Server.html new file mode 100644 index 00000000..98cc152f --- /dev/null +++ b/karyon_jsonrpc/struct.Server.html @@ -0,0 +1,35 @@ +Server in karyon_jsonrpc - Rust +

Struct karyon_jsonrpc::Server

source ·
pub struct Server<'a> {
+    listener: Listener,
+    services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>,
+    task_group: TaskGroup<'a>,
+    config: ServerConfig,
+}
Expand description

Represents an RPC server

+

Fields§

§listener: Listener§services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>§task_group: TaskGroup<'a>§config: ServerConfig

Implementations§

source§

impl<'a> Server<'a>

source

pub fn new<T: ToListener>( + listener: T, + config: ServerConfig, + ex: Executor<'a> +) -> Arc<Self>

Creates a new RPC server by passing a listener. It supports Tcp, Unix, and Tls.

+
source

pub fn local_endpoint(&self) -> Result<Endpoint, Error>

Returns the local endpoint.

+
source

pub async fn start(self: Arc<Self>) -> Result<(), Error>

Starts the RPC server

+
source

pub async fn attach_service(&self, service: impl RPCService + 'a)

Attach a new service to the RPC server

+
source

pub async fn shutdown(&self)

Shuts down the RPC server

+
source

async fn handle_conn(self: &Arc<Self>, conn: Conn) -> Result<(), Error>

Handles a new connection

+
source

async fn handle_request(&self, buffer: &[u8]) -> Response

Handles a request

+

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Server<'a>

§

impl<'a> Send for Server<'a>

§

impl<'a> Sync for Server<'a>

§

impl<'a> Unpin for Server<'a>

§

impl<'a> !UnwindSafe for Server<'a>

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/struct.ServerConfig.html b/karyon_jsonrpc/struct.ServerConfig.html new file mode 100644 index 00000000..f23c2274 --- /dev/null +++ b/karyon_jsonrpc/struct.ServerConfig.html @@ -0,0 +1,21 @@ +ServerConfig in karyon_jsonrpc - Rust +
pub struct ServerConfig {
+    codec_config: CodecConfig,
+}
Expand description

RPC server config

+

Fields§

§codec_config: CodecConfig

Trait Implementations§

source§

impl Default for ServerConfig

source§

fn default() -> ServerConfig

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_jsonrpc/trait.RPCService.html b/karyon_jsonrpc/trait.RPCService.html new file mode 100644 index 00000000..0813713d --- /dev/null +++ b/karyon_jsonrpc/trait.RPCService.html @@ -0,0 +1,7 @@ +RPCService in karyon_jsonrpc - Rust +
pub trait RPCService: Sync + Send {
+    // Required methods
+    fn get_method<'a>(&'a self, name: &'a str) -> Option<RPCMethod<'_>>;
+    fn name(&self) -> String;
+}
Expand description

Defines the interface for an RPC service.

+

Required Methods§

source

fn get_method<'a>(&'a self, name: &'a str) -> Option<RPCMethod<'_>>

source

fn name(&self) -> String

Implementors§

\ No newline at end of file diff --git a/karyon_jsonrpc/type.RPCMethod.html b/karyon_jsonrpc/type.RPCMethod.html new file mode 100644 index 00000000..4f6d7cf2 --- /dev/null +++ b/karyon_jsonrpc/type.RPCMethod.html @@ -0,0 +1,3 @@ +RPCMethod in karyon_jsonrpc - Rust +

Type Alias karyon_jsonrpc::RPCMethod

source ·
pub type RPCMethod<'a> = Box<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>;
Expand description

Represents the RPC method

+

Aliased Type§

struct RPCMethod<'a>(Unique<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>, Global);

Fields§

§0: Unique<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value, Error>> + Send + Sync + 'a>> + Send + 'a>§1: Global
\ No newline at end of file diff --git a/karyon_net/all.html b/karyon_net/all.html new file mode 100644 index 00000000..704d176c --- /dev/null +++ b/karyon_net/all.html @@ -0,0 +1,2 @@ +List of all items in this crate +

List of all items

Structs

Enums

Traits

Functions

Type Aliases

\ No newline at end of file diff --git a/karyon_net/connection/fn.dial.html b/karyon_net/connection/fn.dial.html new file mode 100644 index 00000000..6647a4be --- /dev/null +++ b/karyon_net/connection/fn.dial.html @@ -0,0 +1,19 @@ +dial in karyon_net::connection - Rust +

Function karyon_net::connection::dial

source ·
pub async fn dial(endpoint: &Endpoint) -> Result<Conn>
Expand description

Connects to the provided endpoint.

+

it only supports tcp4/6, udp4/6, and unix.

+

#Example

+ +
use karyon_net::{Endpoint, dial};
+
+async {
+    let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+    let conn = dial(&endpoint).await.unwrap();
+
+    conn.write(b"MSG").await.unwrap();
+
+    let mut buffer = [0;32];
+    conn.read(&mut buffer).await.unwrap();
+};
+
+
\ No newline at end of file diff --git a/karyon_net/connection/index.html b/karyon_net/connection/index.html new file mode 100644 index 00000000..f9157f7d --- /dev/null +++ b/karyon_net/connection/index.html @@ -0,0 +1,3 @@ +karyon_net::connection - Rust +

Module karyon_net::connection

source ·

Traits

Functions

  • Connects to the provided endpoint.

Type Aliases

  • Alias for Box<dyn Connection>
\ No newline at end of file diff --git a/karyon_net/connection/sidebar-items.js b/karyon_net/connection/sidebar-items.js new file mode 100644 index 00000000..30b9ee7c --- /dev/null +++ b/karyon_net/connection/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial"],"trait":["Connection","ToConn"],"type":["Conn"]}; \ No newline at end of file diff --git a/karyon_net/connection/trait.Connection.html b/karyon_net/connection/trait.Connection.html new file mode 100644 index 00000000..99b451e8 --- /dev/null +++ b/karyon_net/connection/trait.Connection.html @@ -0,0 +1,40 @@ +Connection in karyon_net::connection - Rust +
pub trait Connection: Send + Sync {
+    // Required methods
+    fn peer_endpoint(&self) -> Result<Endpoint>;
+    fn local_endpoint(&self) -> Result<Endpoint>;
+    fn read<'life0, 'life1, 'async_trait>(
+        &'life0 self,
+        buf: &'life1 mut [u8]
+    ) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait,
+             'life1: 'async_trait;
+    fn write<'life0, 'life1, 'async_trait>(
+        &'life0 self,
+        buf: &'life1 [u8]
+    ) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait,
+             'life1: 'async_trait;
+}
Expand description

Connection is a generic network connection interface for +udp::UdpConn, tcp::TcpConn, and unix::UnixConn.

+

If you are familiar with the Go language, this is similar to the +Conn interface

+

Required Methods§

source

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection

+
source

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection

+
source

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.

+
source

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection

+

Trait Implementations§

source§

impl From<TcpStream> for Box<dyn Connection>

source§

fn from(conn: TcpStream) -> Self

Converts to this type from the input type.
source§

impl From<TlsStream<TcpStream>> for Box<dyn Connection>

source§

fn from(conn: TlsStream<TcpStream>) -> Self

Converts to this type from the input type.
source§

impl From<UdpSocket> for Box<dyn Connection>

source§

fn from(conn: UdpSocket) -> Self

Converts to this type from the input type.
source§

impl From<UnixStream> for Box<dyn Connection>

source§

fn from(conn: UnixStream) -> Self

Converts to this type from the input type.

Implementors§

\ No newline at end of file diff --git a/karyon_net/connection/trait.ToConn.html b/karyon_net/connection/trait.ToConn.html new file mode 100644 index 00000000..04d4bdc3 --- /dev/null +++ b/karyon_net/connection/trait.ToConn.html @@ -0,0 +1,6 @@ +ToConn in karyon_net::connection - Rust +
pub trait ToConn {
+    // Required method
+    fn to_conn(self) -> Conn;
+}
Expand description

A trait for objects which can be converted to Conn.

+

Required Methods§

source

fn to_conn(self) -> Conn

Implementations on Foreign Types§

source§

impl ToConn for TcpStream

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for TlsStream<TcpStream>

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for UdpSocket

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for UnixStream

source§

fn to_conn(self) -> Box<dyn Connection>

Implementors§

\ No newline at end of file diff --git a/karyon_net/connection/type.Conn.html b/karyon_net/connection/type.Conn.html new file mode 100644 index 00000000..e0a678c1 --- /dev/null +++ b/karyon_net/connection/type.Conn.html @@ -0,0 +1,3 @@ +Conn in karyon_net::connection - Rust +

Type Alias karyon_net::connection::Conn

source ·
pub type Conn = Box<dyn Connection>;
Expand description

Alias for Box<dyn Connection>

+

Aliased Type§

struct Conn(Unique<dyn Connection>, Global);

Fields§

§0: Unique<dyn Connection>§1: Global
\ No newline at end of file diff --git a/karyon_net/endpoint/enum.Addr.html b/karyon_net/endpoint/enum.Addr.html new file mode 100644 index 00000000..c3526261 --- /dev/null +++ b/karyon_net/endpoint/enum.Addr.html @@ -0,0 +1,31 @@ +Addr in karyon_net::endpoint - Rust +
pub enum Addr {
+    Ip(IpAddr),
+    Domain(String),
+}
Expand description

Addr defines a type for an address, either IP or domain.

+

Variants§

§

Ip(IpAddr)

§

Domain(String)

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for Addr

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for Addr

source§

fn clone(&self) -> Addr

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Addr

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for Addr

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Display for Addr

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encode for Addr

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl Hash for Addr

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Addr

source§

fn eq(&self, other: &Addr) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<Addr> for IpAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(addr: Addr) -> Result<IpAddr, Self::Error>

Performs the conversion.
source§

impl Eq for Addr

source§

impl StructuralEq for Addr

source§

impl StructuralPartialEq for Addr

Auto Trait Implementations§

§

impl RefUnwindSafe for Addr

§

impl Send for Addr

§

impl Sync for Addr

§

impl Unpin for Addr

§

impl UnwindSafe for Addr

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/endpoint/enum.Endpoint.html b/karyon_net/endpoint/enum.Endpoint.html new file mode 100644 index 00000000..9f135df7 --- /dev/null +++ b/karyon_net/endpoint/enum.Endpoint.html @@ -0,0 +1,49 @@ +Endpoint in karyon_net::endpoint - Rust +
pub enum Endpoint {
+    Udp(Addr, Port),
+    Tcp(Addr, Port),
+    Tls(Addr, Port),
+    Ws(Addr, Port),
+    Unix(String),
+}
Expand description

Endpoint defines generic network endpoints for karyon.

+

Example

+
use std::net::SocketAddr;
+
+use karyon_net::Endpoint;
+
+let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+let socketaddr: SocketAddr = "127.0.0.1:3000".parse().unwrap();
+let endpoint =  Endpoint::new_udp_addr(&socketaddr);
+
+

Variants§

§

Udp(Addr, Port)

§

Tcp(Addr, Port)

§

Tls(Addr, Port)

§

Ws(Addr, Port)

§

Unix(String)

Implementations§

source§

impl Endpoint

source

pub fn new_tcp_addr(addr: &SocketAddr) -> Endpoint

Creates a new TCP endpoint from a SocketAddr.

+
source

pub fn new_udp_addr(addr: &SocketAddr) -> Endpoint

Creates a new UDP endpoint from a SocketAddr.

+
source

pub fn new_tls_addr(addr: &SocketAddr) -> Endpoint

Creates a new TLS endpoint from a SocketAddr.

+
source

pub fn new_ws_addr(addr: &SocketAddr) -> Endpoint

Creates a new WS endpoint from a SocketAddr.

+
source

pub fn new_unix_addr(addr: &UnixSocketAddress) -> Endpoint

Creates a new Unix endpoint from a UnixSocketAddress.

+
source

pub fn port(&self) -> Result<&Port>

Returns the Port of the endpoint.

+
source

pub fn addr(&self) -> Result<&Addr>

Returns the Addr of the endpoint.

+

Trait Implementations§

source§

impl Clone for Endpoint

source§

fn clone(&self) -> Endpoint

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromStr for Endpoint

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl Hash for Endpoint

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Endpoint

source§

fn eq(&self, other: &Endpoint) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<Endpoint> for PathBuf

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<PathBuf, Self::Error>

Performs the conversion.
source§

impl TryFrom<Endpoint> for SocketAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<UnixSocketAddress, Self::Error>

Performs the conversion.
source§

impl TryFrom<Endpoint> for SocketAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<SocketAddr, Self::Error>

Performs the conversion.
source§

impl Eq for Endpoint

source§

impl StructuralEq for Endpoint

source§

impl StructuralPartialEq for Endpoint

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/endpoint/index.html b/karyon_net/endpoint/index.html new file mode 100644 index 00000000..3356a5e6 --- /dev/null +++ b/karyon_net/endpoint/index.html @@ -0,0 +1,2 @@ +karyon_net::endpoint - Rust +

Module karyon_net::endpoint

source ·

Enums

  • Addr defines a type for an address, either IP or domain.
  • Endpoint defines generic network endpoints for karyon.

Type Aliases

  • Port defined as a u16.
\ No newline at end of file diff --git a/karyon_net/endpoint/sidebar-items.js b/karyon_net/endpoint/sidebar-items.js new file mode 100644 index 00000000..58939313 --- /dev/null +++ b/karyon_net/endpoint/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Addr","Endpoint"],"type":["Port"]}; \ No newline at end of file diff --git a/karyon_net/endpoint/type.Port.html b/karyon_net/endpoint/type.Port.html new file mode 100644 index 00000000..68a76918 --- /dev/null +++ b/karyon_net/endpoint/type.Port.html @@ -0,0 +1,3 @@ +Port in karyon_net::endpoint - Rust +

Type Alias karyon_net::endpoint::Port

source ·
pub type Port = u16;
Expand description

Port defined as a u16.

+
\ No newline at end of file diff --git a/karyon_net/enum.Addr.html b/karyon_net/enum.Addr.html new file mode 100644 index 00000000..fbc5e30b --- /dev/null +++ b/karyon_net/enum.Addr.html @@ -0,0 +1,31 @@ +Addr in karyon_net - Rust +

Enum karyon_net::Addr

source ·
pub enum Addr {
+    Ip(IpAddr),
+    Domain(String),
+}
Expand description

Addr defines a type for an address, either IP or domain.

+

Variants§

§

Ip(IpAddr)

§

Domain(String)

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for Addr

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for Addr

source§

fn clone(&self) -> Addr

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Addr

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for Addr

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Display for Addr

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encode for Addr

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl Hash for Addr

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Addr

source§

fn eq(&self, other: &Addr) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<Addr> for IpAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(addr: Addr) -> Result<IpAddr, Self::Error>

Performs the conversion.
source§

impl Eq for Addr

source§

impl StructuralEq for Addr

source§

impl StructuralPartialEq for Addr

Auto Trait Implementations§

§

impl RefUnwindSafe for Addr

§

impl Send for Addr

§

impl Sync for Addr

§

impl Unpin for Addr

§

impl UnwindSafe for Addr

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/enum.Endpoint.html b/karyon_net/enum.Endpoint.html new file mode 100644 index 00000000..161e8916 --- /dev/null +++ b/karyon_net/enum.Endpoint.html @@ -0,0 +1,49 @@ +Endpoint in karyon_net - Rust +

Enum karyon_net::Endpoint

source ·
pub enum Endpoint {
+    Udp(Addr, Port),
+    Tcp(Addr, Port),
+    Tls(Addr, Port),
+    Ws(Addr, Port),
+    Unix(String),
+}
Expand description

Endpoint defines generic network endpoints for karyon.

+

Example

+
use std::net::SocketAddr;
+
+use karyon_net::Endpoint;
+
+let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+let socketaddr: SocketAddr = "127.0.0.1:3000".parse().unwrap();
+let endpoint =  Endpoint::new_udp_addr(&socketaddr);
+
+

Variants§

§

Udp(Addr, Port)

§

Tcp(Addr, Port)

§

Tls(Addr, Port)

§

Ws(Addr, Port)

§

Unix(String)

Implementations§

source§

impl Endpoint

source

pub fn new_tcp_addr(addr: &SocketAddr) -> Endpoint

Creates a new TCP endpoint from a SocketAddr.

+
source

pub fn new_udp_addr(addr: &SocketAddr) -> Endpoint

Creates a new UDP endpoint from a SocketAddr.

+
source

pub fn new_tls_addr(addr: &SocketAddr) -> Endpoint

Creates a new TLS endpoint from a SocketAddr.

+
source

pub fn new_ws_addr(addr: &SocketAddr) -> Endpoint

Creates a new WS endpoint from a SocketAddr.

+
source

pub fn new_unix_addr(addr: &UnixSocketAddress) -> Endpoint

Creates a new Unix endpoint from a UnixSocketAddress.

+
source

pub fn port(&self) -> Result<&Port>

Returns the Port of the endpoint.

+
source

pub fn addr(&self) -> Result<&Addr>

Returns the Addr of the endpoint.

+

Trait Implementations§

source§

impl Clone for Endpoint

source§

fn clone(&self) -> Endpoint

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Endpoint

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromStr for Endpoint

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl Hash for Endpoint

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for Endpoint

source§

fn eq(&self, other: &Endpoint) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<Endpoint> for PathBuf

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<PathBuf, Self::Error>

Performs the conversion.
source§

impl TryFrom<Endpoint> for SocketAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<UnixSocketAddress, Self::Error>

Performs the conversion.
source§

impl TryFrom<Endpoint> for SocketAddr

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(endpoint: Endpoint) -> Result<SocketAddr, Self::Error>

Performs the conversion.
source§

impl Eq for Endpoint

source§

impl StructuralEq for Endpoint

source§

impl StructuralPartialEq for Endpoint

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/enum.NetError.html b/karyon_net/enum.NetError.html new file mode 100644 index 00000000..a82926b0 --- /dev/null +++ b/karyon_net/enum.NetError.html @@ -0,0 +1,33 @@ +NetError in karyon_net - Rust +

Enum karyon_net::NetError

source ·
pub enum NetError {
+    IO(Error),
+    TryFromEndpoint,
+    InvalidAddress(String),
+    InvalidEndpoint(String),
+    ParseEndpoint(String),
+    Timeout,
+    ChannelSend(String),
+    ChannelRecv(RecvError),
+    Rustls(Error),
+    InvalidDnsNameError(InvalidDnsNameError),
+    KaryonCore(Error),
+}
Expand description

Represents karyon’s Net Error

+

Variants§

§

IO(Error)

§

TryFromEndpoint

§

InvalidAddress(String)

§

InvalidEndpoint(String)

§

ParseEndpoint(String)

§

Timeout

§

ChannelSend(String)

§

ChannelRecv(RecvError)

§

Rustls(Error)

§

InvalidDnsNameError(InvalidDnsNameError)

§

KaryonCore(Error)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<InvalidDnsNameError> for Error

source§

fn from(source: InvalidDnsNameError) -> Self

Converts to this type from the input type.
source§

impl From<RecvError> for Error

source§

fn from(source: RecvError) -> Self

Converts to this type from the input type.
source§

impl<T> From<SendError<T>> for Error

source§

fn from(error: SendError<T>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/error/enum.Error.html b/karyon_net/error/enum.Error.html new file mode 100644 index 00000000..d2ec2a98 --- /dev/null +++ b/karyon_net/error/enum.Error.html @@ -0,0 +1,32 @@ +Error in karyon_net::error - Rust +

Enum karyon_net::error::Error

source ·
pub enum Error {
+    IO(Error),
+    TryFromEndpoint,
+    InvalidAddress(String),
+    InvalidEndpoint(String),
+    ParseEndpoint(String),
+    Timeout,
+    ChannelSend(String),
+    ChannelRecv(RecvError),
+    Rustls(Error),
+    InvalidDnsNameError(InvalidDnsNameError),
+    KaryonCore(Error),
+}

Variants§

§

IO(Error)

§

TryFromEndpoint

§

InvalidAddress(String)

§

InvalidEndpoint(String)

§

ParseEndpoint(String)

§

Timeout

§

ChannelSend(String)

§

ChannelRecv(RecvError)

§

Rustls(Error)

§

InvalidDnsNameError(InvalidDnsNameError)

§

KaryonCore(Error)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<InvalidDnsNameError> for Error

source§

fn from(source: InvalidDnsNameError) -> Self

Converts to this type from the input type.
source§

impl From<RecvError> for Error

source§

fn from(source: RecvError) -> Self

Converts to this type from the input type.
source§

impl<T> From<SendError<T>> for Error

source§

fn from(error: SendError<T>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/error/index.html b/karyon_net/error/index.html new file mode 100644 index 00000000..c56ad6fd --- /dev/null +++ b/karyon_net/error/index.html @@ -0,0 +1,2 @@ +karyon_net::error - Rust +

Module karyon_net::error

source ·

Enums

Type Aliases

\ No newline at end of file diff --git a/karyon_net/error/sidebar-items.js b/karyon_net/error/sidebar-items.js new file mode 100644 index 00000000..c851f700 --- /dev/null +++ b/karyon_net/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Error"],"type":["Result"]}; \ No newline at end of file diff --git a/karyon_net/error/type.Result.html b/karyon_net/error/type.Result.html new file mode 100644 index 00000000..2fc8a59e --- /dev/null +++ b/karyon_net/error/type.Result.html @@ -0,0 +1,7 @@ +Result in karyon_net::error - Rust +

Type Alias karyon_net::error::Result

source ·
pub type Result<T> = Result<T, Error>;

Aliased Type§

enum Result<T> {
+    Ok(T),
+    Err(Error),
+}

Variants§

§1.0.0

Ok(T)

Contains the success value

+
§1.0.0

Err(Error)

Contains the error value

+
\ No newline at end of file diff --git a/karyon_net/fn.dial.html b/karyon_net/fn.dial.html new file mode 100644 index 00000000..9da9ea59 --- /dev/null +++ b/karyon_net/fn.dial.html @@ -0,0 +1,19 @@ +dial in karyon_net - Rust +

Function karyon_net::dial

source ·
pub async fn dial(endpoint: &Endpoint) -> Result<Conn>
Expand description

Connects to the provided endpoint.

+

it only supports tcp4/6, udp4/6, and unix.

+

#Example

+ +
use karyon_net::{Endpoint, dial};
+
+async {
+    let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+    let conn = dial(&endpoint).await.unwrap();
+
+    conn.write(b"MSG").await.unwrap();
+
+    let mut buffer = [0;32];
+    conn.read(&mut buffer).await.unwrap();
+};
+
+
\ No newline at end of file diff --git a/karyon_net/fn.dial_tcp.html b/karyon_net/fn.dial_tcp.html new file mode 100644 index 00000000..de686f92 --- /dev/null +++ b/karyon_net/fn.dial_tcp.html @@ -0,0 +1,3 @@ +dial_tcp in karyon_net - Rust +

Function karyon_net::dial_tcp

source ·
pub async fn dial_tcp(endpoint: &Endpoint) -> Result<TcpConn>
Expand description

Connects to the given TCP address and port.

+
\ No newline at end of file diff --git a/karyon_net/fn.dial_udp.html b/karyon_net/fn.dial_udp.html new file mode 100644 index 00000000..5246ac32 --- /dev/null +++ b/karyon_net/fn.dial_udp.html @@ -0,0 +1,3 @@ +dial_udp in karyon_net - Rust +

Function karyon_net::dial_udp

source ·
pub async fn dial_udp(endpoint: &Endpoint) -> Result<UdpConn>
Expand description

Connects to the given UDP address and port.

+
\ No newline at end of file diff --git a/karyon_net/fn.dial_unix.html b/karyon_net/fn.dial_unix.html new file mode 100644 index 00000000..bd20d791 --- /dev/null +++ b/karyon_net/fn.dial_unix.html @@ -0,0 +1,3 @@ +dial_unix in karyon_net - Rust +

Function karyon_net::dial_unix

source ·
pub async fn dial_unix(path: &String) -> Result<UnixConn>
Expand description

Connects to the given Unix socket path.

+
\ No newline at end of file diff --git a/karyon_net/fn.listen.html b/karyon_net/fn.listen.html new file mode 100644 index 00000000..fdcfbd78 --- /dev/null +++ b/karyon_net/fn.listen.html @@ -0,0 +1,15 @@ +listen in karyon_net - Rust +

Function karyon_net::listen

source ·
pub async fn listen(endpoint: &Endpoint) -> Result<Box<dyn ConnListener>>
Expand description

Listens to the provided endpoint.

+

it only supports tcp4/6, and unix.

+

#Example

+ +
use karyon_net::{Endpoint, listen};
+
+async {
+    let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+    let listener = listen(&endpoint).await.unwrap();
+    let conn = listener.accept().await.unwrap();
+};
+
+
\ No newline at end of file diff --git a/karyon_net/fn.listen_tcp.html b/karyon_net/fn.listen_tcp.html new file mode 100644 index 00000000..6967561c --- /dev/null +++ b/karyon_net/fn.listen_tcp.html @@ -0,0 +1,3 @@ +listen_tcp in karyon_net - Rust +

Function karyon_net::listen_tcp

source ·
pub async fn listen_tcp(endpoint: &Endpoint) -> Result<TcpListener>
Expand description

Listens on the given TCP address and port.

+
\ No newline at end of file diff --git a/karyon_net/fn.listen_udp.html b/karyon_net/fn.listen_udp.html new file mode 100644 index 00000000..65e0ab7e --- /dev/null +++ b/karyon_net/fn.listen_udp.html @@ -0,0 +1,3 @@ +listen_udp in karyon_net - Rust +

Function karyon_net::listen_udp

source ·
pub async fn listen_udp(endpoint: &Endpoint) -> Result<UdpConn>
Expand description

Listens on the given UDP address and port.

+
\ No newline at end of file diff --git a/karyon_net/fn.listen_unix.html b/karyon_net/fn.listen_unix.html new file mode 100644 index 00000000..7259a857 --- /dev/null +++ b/karyon_net/fn.listen_unix.html @@ -0,0 +1,3 @@ +listen_unix in karyon_net - Rust +

Function karyon_net::listen_unix

source ·
pub fn listen_unix(path: &String) -> Result<UnixListener>
Expand description

Listens on the given Unix socket path.

+
\ No newline at end of file diff --git a/karyon_net/index.html b/karyon_net/index.html new file mode 100644 index 00000000..68a9005f --- /dev/null +++ b/karyon_net/index.html @@ -0,0 +1,4 @@ +karyon_net - Rust +

Crate karyon_net

source ·

Modules

Structs

Enums

  • Addr defines a type for an address, either IP or domain.
  • Endpoint defines generic network endpoints for karyon.
  • Represents karyon’s Net Error

Traits

Functions

  • Connects to the provided endpoint.
  • Connects to the given TCP address and port.
  • Connects to the given UDP address and port.
  • Connects to the given Unix socket path.
  • Listens to the provided endpoint.
  • Listens on the given TCP address and port.
  • Listens on the given UDP address and port.
  • Listens on the given Unix socket path.

Type Aliases

  • Alias for Box<dyn Connection>
  • Alias for Box<dyn ConnListener>
  • Represents karyon’s Net Result
  • Port defined as a u16.
\ No newline at end of file diff --git a/karyon_net/listener/fn.listen.html b/karyon_net/listener/fn.listen.html new file mode 100644 index 00000000..722b6efa --- /dev/null +++ b/karyon_net/listener/fn.listen.html @@ -0,0 +1,15 @@ +listen in karyon_net::listener - Rust +

Function karyon_net::listener::listen

source ·
pub async fn listen(endpoint: &Endpoint) -> Result<Box<dyn ConnListener>>
Expand description

Listens to the provided endpoint.

+

it only supports tcp4/6, and unix.

+

#Example

+ +
use karyon_net::{Endpoint, listen};
+
+async {
+    let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+
+    let listener = listen(&endpoint).await.unwrap();
+    let conn = listener.accept().await.unwrap();
+};
+
+
\ No newline at end of file diff --git a/karyon_net/listener/index.html b/karyon_net/listener/index.html new file mode 100644 index 00000000..991020a4 --- /dev/null +++ b/karyon_net/listener/index.html @@ -0,0 +1,2 @@ +karyon_net::listener - Rust +

Module karyon_net::listener

source ·

Traits

Functions

  • Listens to the provided endpoint.

Type Aliases

\ No newline at end of file diff --git a/karyon_net/listener/sidebar-items.js b/karyon_net/listener/sidebar-items.js new file mode 100644 index 00000000..d99597d0 --- /dev/null +++ b/karyon_net/listener/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["listen"],"trait":["ConnListener","ToListener"],"type":["Listener"]}; \ No newline at end of file diff --git a/karyon_net/listener/trait.ConnListener.html b/karyon_net/listener/trait.ConnListener.html new file mode 100644 index 00000000..928e87e7 --- /dev/null +++ b/karyon_net/listener/trait.ConnListener.html @@ -0,0 +1,23 @@ +ConnListener in karyon_net::listener - Rust +
pub trait ConnListener: Send + Sync {
+    // Required methods
+    fn local_endpoint(&self) -> Result<Endpoint>;
+    fn accept<'life0, 'async_trait>(
+        &'life0 self
+    ) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait;
+}
Expand description

ConnListener is a generic network listener.

+

Required Methods§

source

fn local_endpoint(&self) -> Result<Endpoint>

source

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

Trait Implementations§

source§

impl From<TcpListener> for Box<dyn ConnListener>

source§

fn from(listener: TcpListener) -> Self

Converts to this type from the input type.
source§

impl From<TlsListener> for Box<dyn ConnListener>

source§

fn from(listener: TlsListener) -> Self

Converts to this type from the input type.
source§

impl From<UnixListener> for Box<dyn ConnListener>

source§

fn from(listener: UnixListener) -> Self

Converts to this type from the input type.

Implementations on Foreign Types§

source§

impl ConnListener for TcpListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

source§

impl ConnListener for UnixListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

Implementors§

\ No newline at end of file diff --git a/karyon_net/listener/trait.ToListener.html b/karyon_net/listener/trait.ToListener.html new file mode 100644 index 00000000..8c972b23 --- /dev/null +++ b/karyon_net/listener/trait.ToListener.html @@ -0,0 +1,6 @@ +ToListener in karyon_net::listener - Rust +
pub trait ToListener {
+    // Required method
+    fn to_listener(self) -> Listener;
+}
Expand description

A trait for objects which can be converted to Listener.

+

Required Methods§

Implementations on Foreign Types§

source§

impl ToListener for TcpListener

source§

impl ToListener for UnixListener

Implementors§

\ No newline at end of file diff --git a/karyon_net/listener/type.Listener.html b/karyon_net/listener/type.Listener.html new file mode 100644 index 00000000..1b6ab3d6 --- /dev/null +++ b/karyon_net/listener/type.Listener.html @@ -0,0 +1,3 @@ +Listener in karyon_net::listener - Rust +

Type Alias karyon_net::listener::Listener

source ·
pub type Listener = Box<dyn ConnListener>;
Expand description

Alias for Box<dyn ConnListener>

+

Aliased Type§

struct Listener(Unique<dyn ConnListener>, Global);

Fields§

§0: Unique<dyn ConnListener>§1: Global
\ No newline at end of file diff --git a/karyon_net/sidebar-items.js b/karyon_net/sidebar-items.js new file mode 100644 index 00000000..54c99992 --- /dev/null +++ b/karyon_net/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Addr","Endpoint","NetError"],"fn":["dial","dial_tcp","dial_udp","dial_unix","listen","listen_tcp","listen_udp","listen_unix"],"mod":["connection","endpoint","error","listener","tls","transports"],"struct":["TcpConn","UdpConn","UnixConn"],"trait":["ConnListener","Connection","ToConn","ToListener"],"type":["Conn","Listener","NetResult","Port"]}; \ No newline at end of file diff --git a/karyon_net/struct.TcpConn.html b/karyon_net/struct.TcpConn.html new file mode 100644 index 00000000..c3d4e3e9 --- /dev/null +++ b/karyon_net/struct.TcpConn.html @@ -0,0 +1,36 @@ +TcpConn in karyon_net - Rust +

Struct karyon_net::TcpConn

source ·
pub struct TcpConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TcpStream>>,
+    write: Mutex<WriteHalf<TcpStream>>,
+}
Expand description

TCP network connection implementation of the Connection trait.

+

Fields§

§inner: TcpStream§read: Mutex<ReadHalf<TcpStream>>§write: Mutex<WriteHalf<TcpStream>>

Implementations§

source§

impl TcpConn

source

pub fn new(conn: TcpStream) -> Self

Creates a new TcpConn

+

Trait Implementations§

source§

impl Connection for TcpConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for TcpConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/struct.UdpConn.html b/karyon_net/struct.UdpConn.html new file mode 100644 index 00000000..f29413fb --- /dev/null +++ b/karyon_net/struct.UdpConn.html @@ -0,0 +1,37 @@ +UdpConn in karyon_net - Rust +

Struct karyon_net::UdpConn

source ·
pub struct UdpConn {
+    inner: UdpSocket,
+}
Expand description

UDP network connection implementation of the Connection trait.

+

Fields§

§inner: UdpSocket

Implementations§

source§

impl UdpConn

source

pub fn new(conn: UdpSocket) -> Self

Creates a new UdpConn

+
source§

impl UdpConn

source

pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, Endpoint)>

Receives a single datagram message. Returns the number of bytes read +and the origin endpoint.

+
source

pub async fn send_to(&self, buf: &[u8], addr: &Endpoint) -> Result<usize>

Sends data to the given address. Returns the number of bytes written.

+

Trait Implementations§

source§

impl Connection for UdpConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for UdpConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/struct.UnixConn.html b/karyon_net/struct.UnixConn.html new file mode 100644 index 00000000..eb2581a9 --- /dev/null +++ b/karyon_net/struct.UnixConn.html @@ -0,0 +1,36 @@ +UnixConn in karyon_net - Rust +

Struct karyon_net::UnixConn

source ·
pub struct UnixConn {
+    inner: UnixStream,
+    read: Mutex<ReadHalf<UnixStream>>,
+    write: Mutex<WriteHalf<UnixStream>>,
+}
Expand description

Unix domain socket implementation of the Connection trait.

+

Fields§

§inner: UnixStream§read: Mutex<ReadHalf<UnixStream>>§write: Mutex<WriteHalf<UnixStream>>

Implementations§

source§

impl UnixConn

source

pub fn new(conn: UnixStream) -> Self

Creates a new UnixConn

+

Trait Implementations§

source§

impl Connection for UnixConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for UnixConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/tls/fn.dial.html b/karyon_net/tls/fn.dial.html new file mode 100644 index 00000000..d88fb1f1 --- /dev/null +++ b/karyon_net/tls/fn.dial.html @@ -0,0 +1,7 @@ +dial in karyon_net::tls - Rust +

Function karyon_net::tls::dial

source ·
pub async fn dial(
+    endpoint: &Endpoint,
+    config: ClientConfig,
+    dns_name: &'static str
+) -> Result<Box<dyn Connection>>
Expand description

Connects to the given TLS endpoint, returns Conn (Connection).

+
\ No newline at end of file diff --git a/karyon_net/tls/fn.dial_tls.html b/karyon_net/tls/fn.dial_tls.html new file mode 100644 index 00000000..19de5c2c --- /dev/null +++ b/karyon_net/tls/fn.dial_tls.html @@ -0,0 +1,7 @@ +dial_tls in karyon_net::tls - Rust +

Function karyon_net::tls::dial_tls

source ·
pub async fn dial_tls(
+    endpoint: &Endpoint,
+    config: ClientConfig,
+    dns_name: &'static str
+) -> Result<TlsConn>
Expand description

Connects to the given TLS address and port.

+
\ No newline at end of file diff --git a/karyon_net/tls/fn.listen_tls.html b/karyon_net/tls/fn.listen_tls.html new file mode 100644 index 00000000..55cbcd4e --- /dev/null +++ b/karyon_net/tls/fn.listen_tls.html @@ -0,0 +1,6 @@ +listen_tls in karyon_net::tls - Rust +

Function karyon_net::tls::listen_tls

source ·
pub async fn listen_tls(
+    endpoint: &Endpoint,
+    config: ServerConfig
+) -> Result<TlsListener>
Expand description

Listens on the given TLS address and port.

+
\ No newline at end of file diff --git a/karyon_net/tls/index.html b/karyon_net/tls/index.html new file mode 100644 index 00000000..ba8dd62b --- /dev/null +++ b/karyon_net/tls/index.html @@ -0,0 +1,2 @@ +karyon_net::tls - Rust +

Module karyon_net::tls

source ·

Structs

Functions

  • Connects to the given TLS endpoint, returns Conn (Connection).
  • Connects to the given TLS address and port.
  • Listens on the given TLS address and port.
\ No newline at end of file diff --git a/karyon_net/tls/sidebar-items.js b/karyon_net/tls/sidebar-items.js new file mode 100644 index 00000000..42ec1e09 --- /dev/null +++ b/karyon_net/tls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial","dial_tls","listen_tls"],"struct":["TlsConn","TlsListener"]}; \ No newline at end of file diff --git a/karyon_net/tls/struct.TlsConn.html b/karyon_net/tls/struct.TlsConn.html new file mode 100644 index 00000000..3befcd8c --- /dev/null +++ b/karyon_net/tls/struct.TlsConn.html @@ -0,0 +1,36 @@ +TlsConn in karyon_net::tls - Rust +

Struct karyon_net::tls::TlsConn

source ·
pub struct TlsConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TlsStream<TcpStream>>>,
+    write: Mutex<WriteHalf<TlsStream<TcpStream>>>,
+}
Expand description

TLS network connection implementation of the Connection trait.

+

Fields§

§inner: TcpStream§read: Mutex<ReadHalf<TlsStream<TcpStream>>>§write: Mutex<WriteHalf<TlsStream<TcpStream>>>

Implementations§

source§

impl TlsConn

source

pub fn new(sock: TcpStream, conn: TlsStream<TcpStream>) -> Self

Creates a new TlsConn

+

Trait Implementations§

source§

impl Connection for TlsConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for TlsConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/tls/struct.TlsListener.html b/karyon_net/tls/struct.TlsListener.html new file mode 100644 index 00000000..69d6a256 --- /dev/null +++ b/karyon_net/tls/struct.TlsListener.html @@ -0,0 +1,26 @@ +TlsListener in karyon_net::tls - Rust +

Struct karyon_net::tls::TlsListener

source ·
pub struct TlsListener {
+    acceptor: TlsAcceptor,
+    listener: TcpListener,
+}
Expand description

Tls network listener implementation of the Listener ConnListener trait.

+

Fields§

§acceptor: TlsAcceptor§listener: TcpListener

Trait Implementations§

source§

impl ConnListener for TlsListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

source§

impl From<TlsListener> for Box<dyn ConnListener>

source§

fn from(listener: TlsListener) -> Self

Converts to this type from the input type.
source§

impl ToListener for TlsListener

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/trait.ConnListener.html b/karyon_net/trait.ConnListener.html new file mode 100644 index 00000000..a2460d31 --- /dev/null +++ b/karyon_net/trait.ConnListener.html @@ -0,0 +1,23 @@ +ConnListener in karyon_net - Rust +
pub trait ConnListener: Send + Sync {
+    // Required methods
+    fn local_endpoint(&self) -> Result<Endpoint>;
+    fn accept<'life0, 'async_trait>(
+        &'life0 self
+    ) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait;
+}
Expand description

ConnListener is a generic network listener.

+

Required Methods§

source

fn local_endpoint(&self) -> Result<Endpoint>

source

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

Trait Implementations§

source§

impl From<TcpListener> for Box<dyn ConnListener>

source§

fn from(listener: TcpListener) -> Self

Converts to this type from the input type.
source§

impl From<TlsListener> for Box<dyn ConnListener>

source§

fn from(listener: TlsListener) -> Self

Converts to this type from the input type.
source§

impl From<UnixListener> for Box<dyn ConnListener>

source§

fn from(listener: UnixListener) -> Self

Converts to this type from the input type.

Implementations on Foreign Types§

source§

impl ConnListener for TcpListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

source§

impl ConnListener for UnixListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

Implementors§

\ No newline at end of file diff --git a/karyon_net/trait.Connection.html b/karyon_net/trait.Connection.html new file mode 100644 index 00000000..1c20238e --- /dev/null +++ b/karyon_net/trait.Connection.html @@ -0,0 +1,40 @@ +Connection in karyon_net - Rust +
pub trait Connection: Send + Sync {
+    // Required methods
+    fn peer_endpoint(&self) -> Result<Endpoint>;
+    fn local_endpoint(&self) -> Result<Endpoint>;
+    fn read<'life0, 'life1, 'async_trait>(
+        &'life0 self,
+        buf: &'life1 mut [u8]
+    ) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait,
+             'life1: 'async_trait;
+    fn write<'life0, 'life1, 'async_trait>(
+        &'life0 self,
+        buf: &'life1 [u8]
+    ) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
+       where Self: 'async_trait,
+             'life0: 'async_trait,
+             'life1: 'async_trait;
+}
Expand description

Connection is a generic network connection interface for +udp::UdpConn, tcp::TcpConn, and unix::UnixConn.

+

If you are familiar with the Go language, this is similar to the +Conn interface

+

Required Methods§

source

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection

+
source

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection

+
source

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.

+
source

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection

+

Trait Implementations§

source§

impl From<TcpStream> for Box<dyn Connection>

source§

fn from(conn: TcpStream) -> Self

Converts to this type from the input type.
source§

impl From<TlsStream<TcpStream>> for Box<dyn Connection>

source§

fn from(conn: TlsStream<TcpStream>) -> Self

Converts to this type from the input type.
source§

impl From<UdpSocket> for Box<dyn Connection>

source§

fn from(conn: UdpSocket) -> Self

Converts to this type from the input type.
source§

impl From<UnixStream> for Box<dyn Connection>

source§

fn from(conn: UnixStream) -> Self

Converts to this type from the input type.

Implementors§

\ No newline at end of file diff --git a/karyon_net/trait.ToConn.html b/karyon_net/trait.ToConn.html new file mode 100644 index 00000000..b9cbc042 --- /dev/null +++ b/karyon_net/trait.ToConn.html @@ -0,0 +1,6 @@ +ToConn in karyon_net - Rust +

Trait karyon_net::ToConn

source ·
pub trait ToConn {
+    // Required method
+    fn to_conn(self) -> Conn;
+}
Expand description

A trait for objects which can be converted to Conn.

+

Required Methods§

source

fn to_conn(self) -> Conn

Implementations on Foreign Types§

source§

impl ToConn for TcpStream

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for TlsStream<TcpStream>

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for UdpSocket

source§

fn to_conn(self) -> Box<dyn Connection>

source§

impl ToConn for UnixStream

source§

fn to_conn(self) -> Box<dyn Connection>

Implementors§

\ No newline at end of file diff --git a/karyon_net/trait.ToListener.html b/karyon_net/trait.ToListener.html new file mode 100644 index 00000000..1573d573 --- /dev/null +++ b/karyon_net/trait.ToListener.html @@ -0,0 +1,6 @@ +ToListener in karyon_net - Rust +
pub trait ToListener {
+    // Required method
+    fn to_listener(self) -> Listener;
+}
Expand description

A trait for objects which can be converted to Listener.

+

Required Methods§

Implementations on Foreign Types§

source§

impl ToListener for TcpListener

source§

impl ToListener for UnixListener

Implementors§

\ No newline at end of file diff --git a/karyon_net/transports/index.html b/karyon_net/transports/index.html new file mode 100644 index 00000000..9a376ed3 --- /dev/null +++ b/karyon_net/transports/index.html @@ -0,0 +1,2 @@ +karyon_net::transports - Rust +

Module karyon_net::transports

source ·

Modules

\ No newline at end of file diff --git a/karyon_net/transports/sidebar-items.js b/karyon_net/transports/sidebar-items.js new file mode 100644 index 00000000..756a9b43 --- /dev/null +++ b/karyon_net/transports/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["tcp","tls","udp","unix"]}; \ No newline at end of file diff --git a/karyon_net/transports/tcp/fn.dial_tcp.html b/karyon_net/transports/tcp/fn.dial_tcp.html new file mode 100644 index 00000000..8f332b71 --- /dev/null +++ b/karyon_net/transports/tcp/fn.dial_tcp.html @@ -0,0 +1,3 @@ +dial_tcp in karyon_net::transports::tcp - Rust +
pub async fn dial_tcp(endpoint: &Endpoint) -> Result<TcpConn>
Expand description

Connects to the given TCP address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/tcp/fn.listen_tcp.html b/karyon_net/transports/tcp/fn.listen_tcp.html new file mode 100644 index 00000000..7bbedb14 --- /dev/null +++ b/karyon_net/transports/tcp/fn.listen_tcp.html @@ -0,0 +1,3 @@ +listen_tcp in karyon_net::transports::tcp - Rust +
pub async fn listen_tcp(endpoint: &Endpoint) -> Result<TcpListener>
Expand description

Listens on the given TCP address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/tcp/index.html b/karyon_net/transports/tcp/index.html new file mode 100644 index 00000000..f87c9e4f --- /dev/null +++ b/karyon_net/transports/tcp/index.html @@ -0,0 +1,2 @@ +karyon_net::transports::tcp - Rust +

Module karyon_net::transports::tcp

source ·

Structs

Functions

  • Connects to the given TCP address and port.
  • Listens on the given TCP address and port.
\ No newline at end of file diff --git a/karyon_net/transports/tcp/sidebar-items.js b/karyon_net/transports/tcp/sidebar-items.js new file mode 100644 index 00000000..49ccb20f --- /dev/null +++ b/karyon_net/transports/tcp/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial_tcp","listen_tcp"],"struct":["TcpConn"]}; \ No newline at end of file diff --git a/karyon_net/transports/tcp/struct.TcpConn.html b/karyon_net/transports/tcp/struct.TcpConn.html new file mode 100644 index 00000000..525a029a --- /dev/null +++ b/karyon_net/transports/tcp/struct.TcpConn.html @@ -0,0 +1,36 @@ +TcpConn in karyon_net::transports::tcp - Rust +
pub struct TcpConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TcpStream>>,
+    write: Mutex<WriteHalf<TcpStream>>,
+}
Expand description

TCP network connection implementation of the Connection trait.

+

Fields§

§inner: TcpStream§read: Mutex<ReadHalf<TcpStream>>§write: Mutex<WriteHalf<TcpStream>>

Implementations§

source§

impl TcpConn

source

pub fn new(conn: TcpStream) -> Self

Creates a new TcpConn

+

Trait Implementations§

source§

impl Connection for TcpConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for TcpConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/transports/tls/fn.dial.html b/karyon_net/transports/tls/fn.dial.html new file mode 100644 index 00000000..821f0023 --- /dev/null +++ b/karyon_net/transports/tls/fn.dial.html @@ -0,0 +1,7 @@ +dial in karyon_net::transports::tls - Rust +

Function karyon_net::transports::tls::dial

source ·
pub async fn dial(
+    endpoint: &Endpoint,
+    config: ClientConfig,
+    dns_name: &'static str
+) -> Result<Box<dyn Connection>>
Expand description

Connects to the given TLS endpoint, returns Conn (Connection).

+
\ No newline at end of file diff --git a/karyon_net/transports/tls/fn.dial_tls.html b/karyon_net/transports/tls/fn.dial_tls.html new file mode 100644 index 00000000..2ac6f047 --- /dev/null +++ b/karyon_net/transports/tls/fn.dial_tls.html @@ -0,0 +1,7 @@ +dial_tls in karyon_net::transports::tls - Rust +
pub async fn dial_tls(
+    endpoint: &Endpoint,
+    config: ClientConfig,
+    dns_name: &'static str
+) -> Result<TlsConn>
Expand description

Connects to the given TLS address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/tls/fn.listen_tls.html b/karyon_net/transports/tls/fn.listen_tls.html new file mode 100644 index 00000000..c9f5761e --- /dev/null +++ b/karyon_net/transports/tls/fn.listen_tls.html @@ -0,0 +1,6 @@ +listen_tls in karyon_net::transports::tls - Rust +
pub async fn listen_tls(
+    endpoint: &Endpoint,
+    config: ServerConfig
+) -> Result<TlsListener>
Expand description

Listens on the given TLS address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/tls/index.html b/karyon_net/transports/tls/index.html new file mode 100644 index 00000000..83bef8d9 --- /dev/null +++ b/karyon_net/transports/tls/index.html @@ -0,0 +1,2 @@ +karyon_net::transports::tls - Rust +

Module karyon_net::transports::tls

source ·

Structs

Functions

  • Connects to the given TLS endpoint, returns Conn (Connection).
  • Connects to the given TLS address and port.
  • Listens on the given TLS address and port.
\ No newline at end of file diff --git a/karyon_net/transports/tls/sidebar-items.js b/karyon_net/transports/tls/sidebar-items.js new file mode 100644 index 00000000..42ec1e09 --- /dev/null +++ b/karyon_net/transports/tls/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial","dial_tls","listen_tls"],"struct":["TlsConn","TlsListener"]}; \ No newline at end of file diff --git a/karyon_net/transports/tls/struct.TlsConn.html b/karyon_net/transports/tls/struct.TlsConn.html new file mode 100644 index 00000000..cdcdc9ee --- /dev/null +++ b/karyon_net/transports/tls/struct.TlsConn.html @@ -0,0 +1,36 @@ +TlsConn in karyon_net::transports::tls - Rust +
pub struct TlsConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TlsStream<TcpStream>>>,
+    write: Mutex<WriteHalf<TlsStream<TcpStream>>>,
+}
Expand description

TLS network connection implementation of the Connection trait.

+

Fields§

§inner: TcpStream§read: Mutex<ReadHalf<TlsStream<TcpStream>>>§write: Mutex<WriteHalf<TlsStream<TcpStream>>>

Implementations§

source§

impl TlsConn

source

pub fn new(sock: TcpStream, conn: TlsStream<TcpStream>) -> Self

Creates a new TlsConn

+

Trait Implementations§

source§

impl Connection for TlsConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for TlsConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/transports/tls/struct.TlsListener.html b/karyon_net/transports/tls/struct.TlsListener.html new file mode 100644 index 00000000..34c27e05 --- /dev/null +++ b/karyon_net/transports/tls/struct.TlsListener.html @@ -0,0 +1,26 @@ +TlsListener in karyon_net::transports::tls - Rust +
pub struct TlsListener {
+    acceptor: TlsAcceptor,
+    listener: TcpListener,
+}
Expand description

Tls network listener implementation of the Listener ConnListener trait.

+

Fields§

§acceptor: TlsAcceptor§listener: TcpListener

Trait Implementations§

source§

impl ConnListener for TlsListener

source§

fn local_endpoint(&self) -> Result<Endpoint>

source§

fn accept<'life0, 'async_trait>( + &'life0 self +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Connection>>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait,

source§

impl From<TlsListener> for Box<dyn ConnListener>

source§

fn from(listener: TlsListener) -> Self

Converts to this type from the input type.
source§

impl ToListener for TlsListener

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/transports/udp/fn.dial_udp.html b/karyon_net/transports/udp/fn.dial_udp.html new file mode 100644 index 00000000..05655289 --- /dev/null +++ b/karyon_net/transports/udp/fn.dial_udp.html @@ -0,0 +1,3 @@ +dial_udp in karyon_net::transports::udp - Rust +
pub async fn dial_udp(endpoint: &Endpoint) -> Result<UdpConn>
Expand description

Connects to the given UDP address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/udp/fn.listen_udp.html b/karyon_net/transports/udp/fn.listen_udp.html new file mode 100644 index 00000000..187ee799 --- /dev/null +++ b/karyon_net/transports/udp/fn.listen_udp.html @@ -0,0 +1,3 @@ +listen_udp in karyon_net::transports::udp - Rust +
pub async fn listen_udp(endpoint: &Endpoint) -> Result<UdpConn>
Expand description

Listens on the given UDP address and port.

+
\ No newline at end of file diff --git a/karyon_net/transports/udp/index.html b/karyon_net/transports/udp/index.html new file mode 100644 index 00000000..d21878af --- /dev/null +++ b/karyon_net/transports/udp/index.html @@ -0,0 +1,2 @@ +karyon_net::transports::udp - Rust +

Module karyon_net::transports::udp

source ·

Structs

Functions

  • Connects to the given UDP address and port.
  • Listens on the given UDP address and port.
\ No newline at end of file diff --git a/karyon_net/transports/udp/sidebar-items.js b/karyon_net/transports/udp/sidebar-items.js new file mode 100644 index 00000000..e89a9fb7 --- /dev/null +++ b/karyon_net/transports/udp/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial_udp","listen_udp"],"struct":["UdpConn"]}; \ No newline at end of file diff --git a/karyon_net/transports/udp/struct.UdpConn.html b/karyon_net/transports/udp/struct.UdpConn.html new file mode 100644 index 00000000..8544bb08 --- /dev/null +++ b/karyon_net/transports/udp/struct.UdpConn.html @@ -0,0 +1,37 @@ +UdpConn in karyon_net::transports::udp - Rust +
pub struct UdpConn {
+    inner: UdpSocket,
+}
Expand description

UDP network connection implementation of the Connection trait.

+

Fields§

§inner: UdpSocket

Implementations§

source§

impl UdpConn

source

pub fn new(conn: UdpSocket) -> Self

Creates a new UdpConn

+
source§

impl UdpConn

source

pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, Endpoint)>

Receives a single datagram message. Returns the number of bytes read +and the origin endpoint.

+
source

pub async fn send_to(&self, buf: &[u8], addr: &Endpoint) -> Result<usize>

Sends data to the given address. Returns the number of bytes written.

+

Trait Implementations§

source§

impl Connection for UdpConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for UdpConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/transports/unix/fn.dial_unix.html b/karyon_net/transports/unix/fn.dial_unix.html new file mode 100644 index 00000000..88106677 --- /dev/null +++ b/karyon_net/transports/unix/fn.dial_unix.html @@ -0,0 +1,3 @@ +dial_unix in karyon_net::transports::unix - Rust +
pub async fn dial_unix(path: &String) -> Result<UnixConn>
Expand description

Connects to the given Unix socket path.

+
\ No newline at end of file diff --git a/karyon_net/transports/unix/fn.listen_unix.html b/karyon_net/transports/unix/fn.listen_unix.html new file mode 100644 index 00000000..ff260178 --- /dev/null +++ b/karyon_net/transports/unix/fn.listen_unix.html @@ -0,0 +1,3 @@ +listen_unix in karyon_net::transports::unix - Rust +
pub fn listen_unix(path: &String) -> Result<UnixListener>
Expand description

Listens on the given Unix socket path.

+
\ No newline at end of file diff --git a/karyon_net/transports/unix/index.html b/karyon_net/transports/unix/index.html new file mode 100644 index 00000000..5acde473 --- /dev/null +++ b/karyon_net/transports/unix/index.html @@ -0,0 +1,2 @@ +karyon_net::transports::unix - Rust +

Module karyon_net::transports::unix

source ·

Structs

Functions

\ No newline at end of file diff --git a/karyon_net/transports/unix/sidebar-items.js b/karyon_net/transports/unix/sidebar-items.js new file mode 100644 index 00000000..8324649b --- /dev/null +++ b/karyon_net/transports/unix/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["dial_unix","listen_unix"],"struct":["UnixConn"]}; \ No newline at end of file diff --git a/karyon_net/transports/unix/struct.UnixConn.html b/karyon_net/transports/unix/struct.UnixConn.html new file mode 100644 index 00000000..4b0b067d --- /dev/null +++ b/karyon_net/transports/unix/struct.UnixConn.html @@ -0,0 +1,36 @@ +UnixConn in karyon_net::transports::unix - Rust +
pub struct UnixConn {
+    inner: UnixStream,
+    read: Mutex<ReadHalf<UnixStream>>,
+    write: Mutex<WriteHalf<UnixStream>>,
+}
Expand description

Unix domain socket implementation of the Connection trait.

+

Fields§

§inner: UnixStream§read: Mutex<ReadHalf<UnixStream>>§write: Mutex<WriteHalf<UnixStream>>

Implementations§

source§

impl UnixConn

source

pub fn new(conn: UnixStream) -> Self

Creates a new UnixConn

+

Trait Implementations§

source§

impl Connection for UnixConn

source§

fn peer_endpoint(&self) -> Result<Endpoint>

Returns the remote peer endpoint of this connection
source§

fn local_endpoint(&self) -> Result<Endpoint>

Returns the local socket endpoint of this connection
source§

fn read<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 mut [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Reads data from this connection.
source§

fn write<'life0, 'life1, 'async_trait>( + &'life0 self, + buf: &'life1 [u8] +) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where + Self: 'async_trait, + 'life0: 'async_trait, + 'life1: 'async_trait,

Writes data to this connection
source§

impl ToConn for UnixConn

source§

fn to_conn(self) -> Box<dyn Connection>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_net/type.Conn.html b/karyon_net/type.Conn.html new file mode 100644 index 00000000..0b11a675 --- /dev/null +++ b/karyon_net/type.Conn.html @@ -0,0 +1,3 @@ +Conn in karyon_net - Rust +

Type Alias karyon_net::Conn

source ·
pub type Conn = Box<dyn Connection>;
Expand description

Alias for Box<dyn Connection>

+

Aliased Type§

struct Conn(Unique<dyn Connection>, Global);

Fields§

§0: Unique<dyn Connection>§1: Global
\ No newline at end of file diff --git a/karyon_net/type.Listener.html b/karyon_net/type.Listener.html new file mode 100644 index 00000000..79b0aeec --- /dev/null +++ b/karyon_net/type.Listener.html @@ -0,0 +1,3 @@ +Listener in karyon_net - Rust +

Type Alias karyon_net::Listener

source ·
pub type Listener = Box<dyn ConnListener>;
Expand description

Alias for Box<dyn ConnListener>

+

Aliased Type§

struct Listener(Unique<dyn ConnListener>, Global);

Fields§

§0: Unique<dyn ConnListener>§1: Global
\ No newline at end of file diff --git a/karyon_net/type.NetResult.html b/karyon_net/type.NetResult.html new file mode 100644 index 00000000..3ca988bf --- /dev/null +++ b/karyon_net/type.NetResult.html @@ -0,0 +1,8 @@ +NetResult in karyon_net - Rust +

Type Alias karyon_net::NetResult

source ·
pub type NetResult<T> = Result<T, Error>;
Expand description

Represents karyon’s Net Result

+

Aliased Type§

enum NetResult<T> {
+    Ok(T),
+    Err(Error),
+}

Variants§

§1.0.0

Ok(T)

Contains the success value

+
§1.0.0

Err(Error)

Contains the error value

+
\ No newline at end of file diff --git a/karyon_net/type.Port.html b/karyon_net/type.Port.html new file mode 100644 index 00000000..ff62aef2 --- /dev/null +++ b/karyon_net/type.Port.html @@ -0,0 +1,3 @@ +Port in karyon_net - Rust +

Type Alias karyon_net::Port

source ·
pub type Port = u16;
Expand description

Port defined as a u16.

+
\ No newline at end of file diff --git a/karyon_p2p/all.html b/karyon_p2p/all.html new file mode 100644 index 00000000..a9f22aeb --- /dev/null +++ b/karyon_p2p/all.html @@ -0,0 +1,2 @@ +List of all items in this crate +

List of all items

Structs

Enums

Traits

Macros

Functions

Type Aliases

Statics

Constants

\ No newline at end of file diff --git a/karyon_p2p/backend/index.html b/karyon_p2p/backend/index.html new file mode 100644 index 00000000..c7ebbfad --- /dev/null +++ b/karyon_p2p/backend/index.html @@ -0,0 +1,3 @@ +karyon_p2p::backend - Rust +

Module karyon_p2p::backend

source ·

Structs

  • Backend serves as the central entry point for initiating and managing +the P2P network.

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/backend/sidebar-items.js b/karyon_p2p/backend/sidebar-items.js new file mode 100644 index 00000000..96b92a1a --- /dev/null +++ b/karyon_p2p/backend/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Backend"],"type":["ArcBackend"]}; \ No newline at end of file diff --git a/karyon_p2p/backend/struct.Backend.html b/karyon_p2p/backend/struct.Backend.html new file mode 100644 index 00000000..6deb8209 --- /dev/null +++ b/karyon_p2p/backend/struct.Backend.html @@ -0,0 +1,51 @@ +Backend in karyon_p2p::backend - Rust +

Struct karyon_p2p::backend::Backend

source ·
pub struct Backend {
+    config: Arc<Config>,
+    key_pair: KeyPair,
+    monitor: Arc<Monitor>,
+    discovery: Arc<Discovery>,
+    peer_pool: Arc<PeerPool>,
+}
Expand description

Backend serves as the central entry point for initiating and managing +the P2P network.

+

Fields§

§config: Arc<Config>

The Configuration for the P2P network.

+
§key_pair: KeyPair

Identity Key pair

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+
§discovery: Arc<Discovery>

Discovery instance.

+
§peer_pool: Arc<PeerPool>

PeerPool instance.

+

Implementations§

source§

impl Backend

source

pub fn new(key_pair: &KeyPair, config: Config, ex: GlobalExecutor) -> ArcBackend

Creates a new Backend.

+
source

pub async fn run(self: &Arc<Self>) -> Result<(), Error>

Run the Backend, starting the PeerPool and Discovery instances.

+
source

pub async fn attach_protocol<P: Protocol>( + &self, + c: impl Fn(ArcPeer) -> ArcProtocol + Send + Sync + 'static +) -> Result<(), Error>

Attach a custom protocol to the network

+
source

pub async fn peers(&self) -> usize

Returns the number of currently connected peers.

+
source

pub fn config(&self) -> Arc<Config>

Returns the Config.

+
source

pub async fn key_pair(&self) -> &KeyPair

Returns the KeyPair.

+
source

pub fn inbound_slots(&self) -> usize

Returns the number of occupied inbound slots.

+
source

pub fn outbound_slots(&self) -> usize

Returns the number of occupied outbound slots.

+
source

pub async fn monitor(&self) -> Subscription<MonitorEvent>

Subscribes to the monitor to receive network events.

+
source

pub async fn shutdown(&self)

Shuts down the Backend.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/backend/type.ArcBackend.html b/karyon_p2p/backend/type.ArcBackend.html new file mode 100644 index 00000000..d0a054bd --- /dev/null +++ b/karyon_p2p/backend/type.ArcBackend.html @@ -0,0 +1,6 @@ +ArcBackend in karyon_p2p::backend - Rust +

Type Alias karyon_p2p::backend::ArcBackend

source ·
pub type ArcBackend = Arc<Backend>;

Aliased Type§

struct ArcBackend {
+    ptr: NonNull<ArcInner<Backend>>,
+    phantom: PhantomData<ArcInner<Backend>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Backend>>§phantom: PhantomData<ArcInner<Backend>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/codec/index.html b/karyon_p2p/codec/index.html new file mode 100644 index 00000000..e4110a4e --- /dev/null +++ b/karyon_p2p/codec/index.html @@ -0,0 +1,2 @@ +karyon_p2p::codec - Rust +

Module karyon_p2p::codec

source ·

Structs

  • A Codec working with generic network connections.

Traits

\ No newline at end of file diff --git a/karyon_p2p/codec/sidebar-items.js b/karyon_p2p/codec/sidebar-items.js new file mode 100644 index 00000000..12a732e0 --- /dev/null +++ b/karyon_p2p/codec/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Codec"],"trait":["CodecMsg"]}; \ No newline at end of file diff --git a/karyon_p2p/codec/struct.Codec.html b/karyon_p2p/codec/struct.Codec.html new file mode 100644 index 00000000..5c47a8ec --- /dev/null +++ b/karyon_p2p/codec/struct.Codec.html @@ -0,0 +1,44 @@ +Codec in karyon_p2p::codec - Rust +

Struct karyon_p2p::codec::Codec

source ·
pub struct Codec {
+    conn: Box<dyn Connection>,
+}
Expand description

A Codec working with generic network connections.

+

It is responsible for both decoding data received from the network and +encoding data before sending it.

+

Fields§

§conn: Box<dyn Connection>

Implementations§

source§

impl Codec

source

pub fn new(conn: Box<dyn Connection>) -> Self

Creates a new Codec.

+
source

pub async fn read(&self) -> Result<NetMsg, Error>

Reads a message of type NetMsg from the connection.

+

It reads the first 6 bytes as the header of the message, then reads +and decodes the remaining message data based on the determined header.

+
source

pub async fn write<T: CodecMsg>( + &self, + command: NetMsgCmd, + msg: &T +) -> Result<(), Error>

Writes a message of type T to the connection.

+

Before appending the actual message payload, it calculates the length of +the encoded message in bytes and appends this length to the message header.

+
source

pub async fn read_timeout(&self, duration: Duration) -> Result<NetMsg, Error>

Reads a message of type NetMsg with the given timeout.

+
source

async fn read_exact(&self, buf: &mut [u8]) -> Result<(), Error>

Reads the exact number of bytes required to fill buf.

+
source

async fn write_all(&self, buf: &[u8]) -> Result<(), Error>

Writes an entire buffer into the connection.

+

Auto Trait Implementations§

§

impl !RefUnwindSafe for Codec

§

impl Send for Codec

§

impl Sync for Codec

§

impl Unpin for Codec

§

impl !UnwindSafe for Codec

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/codec/trait.CodecMsg.html b/karyon_p2p/codec/trait.CodecMsg.html new file mode 100644 index 00000000..d6da49ad --- /dev/null +++ b/karyon_p2p/codec/trait.CodecMsg.html @@ -0,0 +1,2 @@ +CodecMsg in karyon_p2p::codec - Rust +
pub trait CodecMsg: Decode + Encode + Debug { }

Object Safety§

This trait is not object safe.

Implementors§

source§

impl<T: Encode + Decode + Debug> CodecMsg for T

\ No newline at end of file diff --git a/karyon_p2p/config/index.html b/karyon_p2p/config/index.html new file mode 100644 index 00000000..818225c5 --- /dev/null +++ b/karyon_p2p/config/index.html @@ -0,0 +1,2 @@ +karyon_p2p::config - Rust +

Module karyon_p2p::config

source ·

Structs

  • the Configuration for the P2P network.
\ No newline at end of file diff --git a/karyon_p2p/config/sidebar-items.js b/karyon_p2p/config/sidebar-items.js new file mode 100644 index 00000000..4cadad77 --- /dev/null +++ b/karyon_p2p/config/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Config"]}; \ No newline at end of file diff --git a/karyon_p2p/config/struct.Config.html b/karyon_p2p/config/struct.Config.html new file mode 100644 index 00000000..99633fa4 --- /dev/null +++ b/karyon_p2p/config/struct.Config.html @@ -0,0 +1,80 @@ +Config in karyon_p2p::config - Rust +

Struct karyon_p2p::config::Config

source ·
pub struct Config {
Show 21 fields + pub version: Version, + pub handshake_timeout: u64, + pub ping_interval: u64, + pub ping_timeout: u64, + pub max_connect_retries: usize, + pub bootstrap_peers: Vec<Endpoint>, + pub listen_endpoint: Option<Endpoint>, + pub peer_endpoints: Vec<Endpoint>, + pub inbound_slots: usize, + pub outbound_slots: usize, + pub discovery_port: Port, + pub seeding_interval: u64, + pub lookup_inbound_slots: usize, + pub lookup_outbound_slots: usize, + pub lookup_response_timeout: u64, + pub lookup_connection_lifespan: u64, + pub lookup_connect_retries: usize, + pub refresh_interval: u64, + pub refresh_response_timeout: u64, + pub refresh_connect_retries: usize, + pub enable_tls: bool, +
}
Expand description

the Configuration for the P2P network.

+

Fields§

§version: Version

Represents the network version.

+
§handshake_timeout: u64

Timeout duration for the handshake with new peers, in seconds.

+
§ping_interval: u64

Interval at which the ping protocol sends ping messages to a peer to +maintain connections, in seconds.

+
§ping_timeout: u64

Timeout duration for receiving the pong message corresponding to the +sent ping message, in seconds.

+
§max_connect_retries: usize

The maximum number of retries for outbound connection establishment.

+
§bootstrap_peers: Vec<Endpoint>

A list of bootstrap peers for the seeding process.

+
§listen_endpoint: Option<Endpoint>

An optional listening endpoint to accept incoming connections.

+
§peer_endpoints: Vec<Endpoint>

A list of endpoints representing peers that the Discovery will +manually connect to.

+
§inbound_slots: usize

The number of available inbound slots for incoming connections.

+
§outbound_slots: usize

The number of available outbound slots for outgoing connections.

+
§discovery_port: Port

TCP/UDP port for lookup and refresh processes.

+
§seeding_interval: u64

Time interval, in seconds, at which the Discovery restarts the +seeding process.

+
§lookup_inbound_slots: usize

The number of available inbound slots for incoming connections during +the lookup process.

+
§lookup_outbound_slots: usize

The number of available outbound slots for outgoing connections during +the lookup process.

+
§lookup_response_timeout: u64

Timeout duration for a peer response during the lookup process, in +seconds.

+
§lookup_connection_lifespan: u64

Maximum allowable time for a live connection with a peer during the +lookup process, in seconds.

+
§lookup_connect_retries: usize

The maximum number of retries for outbound connection establishment +during the lookup process.

+
§refresh_interval: u64

Interval at which the table refreshes its entries, in seconds.

+
§refresh_response_timeout: u64

Timeout duration for a peer response during the table refresh process, +in seconds.

+
§refresh_connect_retries: usize

The maximum number of retries for outbound connection establishment +during the refresh process.

+
§enable_tls: bool

Enables TLS for all connections.

+

Trait Implementations§

source§

impl Default for Config

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/connection/enum.ConnDirection.html b/karyon_p2p/connection/enum.ConnDirection.html new file mode 100644 index 00000000..8e93d860 --- /dev/null +++ b/karyon_p2p/connection/enum.ConnDirection.html @@ -0,0 +1,32 @@ +ConnDirection in karyon_p2p::connection - Rust +
pub enum ConnDirection {
+    Inbound,
+    Outbound,
+}
Expand description

Defines the direction of a network connection.

+

Variants§

§

Inbound

§

Outbound

Trait Implementations§

source§

impl Clone for ConnDirection

source§

fn clone(&self) -> ConnDirection

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ConnDirection

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for ConnDirection

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/connection/index.html b/karyon_p2p/connection/index.html new file mode 100644 index 00000000..d7326a37 --- /dev/null +++ b/karyon_p2p/connection/index.html @@ -0,0 +1,2 @@ +karyon_p2p::connection - Rust +

Module karyon_p2p::connection

source ·

Structs

Enums

\ No newline at end of file diff --git a/karyon_p2p/connection/sidebar-items.js b/karyon_p2p/connection/sidebar-items.js new file mode 100644 index 00000000..bc62ae41 --- /dev/null +++ b/karyon_p2p/connection/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["ConnDirection"],"struct":["ConnQueue","NewConn"]}; \ No newline at end of file diff --git a/karyon_p2p/connection/struct.ConnQueue.html b/karyon_p2p/connection/struct.ConnQueue.html new file mode 100644 index 00000000..f2483b01 --- /dev/null +++ b/karyon_p2p/connection/struct.ConnQueue.html @@ -0,0 +1,35 @@ +ConnQueue in karyon_p2p::connection - Rust +
pub struct ConnQueue {
+    queue: Mutex<VecDeque<NewConn>>,
+    conn_available: CondVar,
+}
Expand description

Connection queue

+

Fields§

§queue: Mutex<VecDeque<NewConn>>§conn_available: CondVar

Implementations§

source§

impl ConnQueue

source

pub fn new() -> Arc<Self>

source

pub async fn handle( + &self, + conn: Conn, + direction: ConnDirection +) -> Result<(), Error>

Push a connection into the queue and wait for the disconnect signal

+
source

pub async fn next(&self) -> NewConn

Receive the next connection in the queue

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/connection/struct.NewConn.html b/karyon_p2p/connection/struct.NewConn.html new file mode 100644 index 00000000..f4d4334c --- /dev/null +++ b/karyon_p2p/connection/struct.NewConn.html @@ -0,0 +1,29 @@ +NewConn in karyon_p2p::connection - Rust +
pub struct NewConn {
+    pub direction: ConnDirection,
+    pub conn: Conn,
+    pub disconnect_signal: Sender<Result<(), Error>>,
+}

Fields§

§direction: ConnDirection§conn: Conn§disconnect_signal: Sender<Result<(), Error>>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/connector/index.html b/karyon_p2p/connector/index.html new file mode 100644 index 00000000..86e6837a --- /dev/null +++ b/karyon_p2p/connector/index.html @@ -0,0 +1,2 @@ +karyon_p2p::connector - Rust +

Module karyon_p2p::connector

source ·

Structs

  • Responsible for creating outbound connections with other peers.

Statics

\ No newline at end of file diff --git a/karyon_p2p/connector/sidebar-items.js b/karyon_p2p/connector/sidebar-items.js new file mode 100644 index 00000000..42ef46b4 --- /dev/null +++ b/karyon_p2p/connector/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"static":["DNS_NAME"],"struct":["Connector"]}; \ No newline at end of file diff --git a/karyon_p2p/connector/static.DNS_NAME.html b/karyon_p2p/connector/static.DNS_NAME.html new file mode 100644 index 00000000..3c5ae277 --- /dev/null +++ b/karyon_p2p/connector/static.DNS_NAME.html @@ -0,0 +1,2 @@ +DNS_NAME in karyon_p2p::connector - Rust +
static DNS_NAME: &str
\ No newline at end of file diff --git a/karyon_p2p/connector/struct.Connector.html b/karyon_p2p/connector/struct.Connector.html new file mode 100644 index 00000000..f69043a3 --- /dev/null +++ b/karyon_p2p/connector/struct.Connector.html @@ -0,0 +1,70 @@ +Connector in karyon_p2p::connector - Rust +
pub struct Connector {
+    key_pair: KeyPair,
+    task_group: TaskGroup<'static>,
+    connection_slots: Arc<ConnectionSlots>,
+    max_retries: usize,
+    enable_tls: bool,
+    monitor: Arc<Monitor>,
+}
Expand description

Responsible for creating outbound connections with other peers.

+

Fields§

§key_pair: KeyPair

Identity Key pair

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+
§connection_slots: Arc<ConnectionSlots>

Manages available outbound slots.

+
§max_retries: usize

The maximum number of retries allowed before successfully +establishing a connection.

+
§enable_tls: bool

Enables secure connection.

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+

Implementations§

source§

impl Connector

source

pub fn new( + key_pair: &KeyPair, + max_retries: usize, + connection_slots: Arc<ConnectionSlots>, + enable_tls: bool, + monitor: Arc<Monitor>, + ex: GlobalExecutor +) -> Arc<Self>

Creates a new Connector

+
source

pub async fn shutdown(&self)

Shuts down the connector

+
source

pub async fn connect( + &self, + endpoint: &Endpoint, + peer_id: &Option<PeerID> +) -> Result<Conn, Error>

Establish a connection to the specified endpoint. If the connection +attempt fails, it performs a backoff and retries until the maximum allowed +number of retries is exceeded. On a successful connection, it returns a +Conn instance.

+

This method will block until it finds an available slot.

+
source

pub async fn connect_with_cback<Fut>( + self: &Arc<Self>, + endpoint: &Endpoint, + peer_id: &Option<PeerID>, + callback: impl FnOnce(Conn) -> Fut + Send + 'static +) -> Result<(), Error>
where + Fut: Future<Output = Result<(), Error>> + Send + 'static,

Establish a connection to the given endpoint. For each new connection, +it invokes the provided callback, and pass the connection to the callback.

+
source

async fn dial( + &self, + endpoint: &Endpoint, + peer_id: &Option<PeerID> +) -> Result<Conn, Error>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/discovery/index.html b/karyon_p2p/discovery/index.html new file mode 100644 index 00000000..df651a5b --- /dev/null +++ b/karyon_p2p/discovery/index.html @@ -0,0 +1,2 @@ +karyon_p2p::discovery - Rust +

Module karyon_p2p::discovery

source ·

Modules

Structs

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/discovery/lookup/constant.MAX_PEERS_IN_PEERSMSG.html b/karyon_p2p/discovery/lookup/constant.MAX_PEERS_IN_PEERSMSG.html new file mode 100644 index 00000000..9141f97b --- /dev/null +++ b/karyon_p2p/discovery/lookup/constant.MAX_PEERS_IN_PEERSMSG.html @@ -0,0 +1,3 @@ +MAX_PEERS_IN_PEERSMSG in karyon_p2p::discovery::lookup - Rust +
pub const MAX_PEERS_IN_PEERSMSG: usize = 10;
Expand description

Maximum number of peers that can be returned in a PeersMsg.

+
\ No newline at end of file diff --git a/karyon_p2p/discovery/lookup/index.html b/karyon_p2p/discovery/lookup/index.html new file mode 100644 index 00000000..c00b1011 --- /dev/null +++ b/karyon_p2p/discovery/lookup/index.html @@ -0,0 +1,2 @@ +karyon_p2p::discovery::lookup - Rust +

Structs

Constants

\ No newline at end of file diff --git a/karyon_p2p/discovery/lookup/sidebar-items.js b/karyon_p2p/discovery/lookup/sidebar-items.js new file mode 100644 index 00000000..25957055 --- /dev/null +++ b/karyon_p2p/discovery/lookup/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["MAX_PEERS_IN_PEERSMSG"],"struct":["LookupService"]}; \ No newline at end of file diff --git a/karyon_p2p/discovery/lookup/struct.LookupService.html b/karyon_p2p/discovery/lookup/struct.LookupService.html new file mode 100644 index 00000000..e976edf6 --- /dev/null +++ b/karyon_p2p/discovery/lookup/struct.LookupService.html @@ -0,0 +1,111 @@ +LookupService in karyon_p2p::discovery::lookup - Rust +
pub struct LookupService {
+    id: PeerID,
+    table: Arc<Mutex<RoutingTable>>,
+    listener: Arc<Listener>,
+    connector: Arc<Connector>,
+    outbound_slots: Arc<ConnectionSlots>,
+    listen_endpoint: Option<RwLock<Endpoint>>,
+    config: Arc<Config>,
+    monitor: Arc<Monitor>,
+}

Fields§

§id: PeerID

Peer’s ID

+
§table: Arc<Mutex<RoutingTable>>

Routing Table

+
§listener: Arc<Listener>

Listener

+
§connector: Arc<Connector>

Connector

+
§outbound_slots: Arc<ConnectionSlots>

Outbound slots.

+
§listen_endpoint: Option<RwLock<Endpoint>>

Resolved listen endpoint

+
§config: Arc<Config>

Holds the configuration for the P2P network.

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+

Implementations§

source§

impl LookupService

source

pub fn new( + key_pair: &KeyPair, + id: &PeerID, + table: Arc<Mutex<RoutingTable>>, + config: Arc<Config>, + monitor: Arc<Monitor>, + ex: GlobalExecutor +) -> Self

Creates a new lookup service

+
source

pub async fn start(self: &Arc<Self>) -> Result<(), Error>

Start the lookup service.

+
source

pub async fn set_listen_endpoint(&self, resolved_endpoint: &Endpoint)

Set the resolved listen endpoint.

+
source

pub async fn shutdown(&self)

Shuts down the lookup service.

+
source

pub async fn start_lookup( + &self, + endpoint: &Endpoint, + peer_id: Option<PeerID> +) -> Result<(), Error>

Starts iterative lookup and populate the routing table.

+

This method begins by generating a random peer ID and connecting to the +provided endpoint. It then sends a FindPeer message containing the +randomly generated peer ID. Upon receiving peers from the initial lookup, +it starts connecting to these received peers and sends them a FindPeer +message that contains our own peer ID.

+
source

async fn random_lookup( + &self, + endpoint: &Endpoint, + peer_id: Option<PeerID>, + random_peers: &mut Vec<PeerMsg> +) -> Result<(), Error>

Starts a random lookup

+

This will perfom lookup on a random generated PeerID

+
source

async fn self_lookup( + &self, + random_peers: &Vec<PeerMsg>, + peer_buffer: &mut Vec<PeerMsg> +)

Starts a self lookup

+
source

async fn connect( + &self, + endpoint: Endpoint, + peer_id: Option<PeerID>, + target_peer_id: &PeerID +) -> Result<Vec<PeerMsg>, Error>

Connects to the given endpoint and initiates a lookup process for the +provided peer ID.

+
source

async fn handle_outbound( + &self, + io_codec: Codec, + target_peer_id: &PeerID +) -> Result<Vec<PeerMsg>, Error>

Handles outbound connection

+
source

async fn start_listener(self: &Arc<Self>) -> Result<(), Error>

Start a listener.

+
source

async fn handle_inbound(self: &Arc<Self>, conn: Conn) -> Result<(), Error>

Handles inbound connection

+
source

async fn send_ping_msg(&self, io_codec: &Codec) -> Result<(), Error>

Sends a Ping msg and wait to receive the Pong message.

+
source

async fn send_pong_msg( + &self, + nonce: [u8; 32], + io_codec: &Codec +) -> Result<(), Error>

Sends a Pong msg

+
source

async fn send_findpeer_msg( + &self, + io_codec: &Codec, + peer_id: &PeerID +) -> Result<PeersMsg, Error>

Sends a FindPeer msg and wait to receivet the Peers msg.

+
source

async fn send_peers_msg( + &self, + peer_id: &PeerID, + io_codec: &Codec +) -> Result<(), Error>

Sends a Peers msg.

+
source

async fn send_peer_msg( + &self, + io_codec: &Codec, + endpoint: Endpoint +) -> Result<(), Error>

Sends a Peer msg.

+
source

async fn send_shutdown_msg(&self, io_codec: &Codec) -> Result<(), Error>

Sends a Shutdown msg.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/constant.MAX_FAILURES.html b/karyon_p2p/discovery/refresh/constant.MAX_FAILURES.html new file mode 100644 index 00000000..c611b1e0 --- /dev/null +++ b/karyon_p2p/discovery/refresh/constant.MAX_FAILURES.html @@ -0,0 +1,3 @@ +MAX_FAILURES in karyon_p2p::discovery::refresh - Rust +
pub const MAX_FAILURES: u32 = 3;
Expand description

Maximum failures for an entry before removing it from the routing table.

+
\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/constant.PINGMSG_SIZE.html b/karyon_p2p/discovery/refresh/constant.PINGMSG_SIZE.html new file mode 100644 index 00000000..d8845f9b --- /dev/null +++ b/karyon_p2p/discovery/refresh/constant.PINGMSG_SIZE.html @@ -0,0 +1,3 @@ +PINGMSG_SIZE in karyon_p2p::discovery::refresh - Rust +
const PINGMSG_SIZE: usize = 32;
Expand description

Ping message size

+
\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/index.html b/karyon_p2p/discovery/refresh/index.html new file mode 100644 index 00000000..c999ed33 --- /dev/null +++ b/karyon_p2p/discovery/refresh/index.html @@ -0,0 +1,2 @@ +karyon_p2p::discovery::refresh - Rust +

Structs

Constants

  • Maximum failures for an entry before removing it from the routing table.
  • Ping message size
\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/sidebar-items.js b/karyon_p2p/discovery/refresh/sidebar-items.js new file mode 100644 index 00000000..ab42b268 --- /dev/null +++ b/karyon_p2p/discovery/refresh/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["MAX_FAILURES","PINGMSG_SIZE"],"struct":["PingMsg","PongMsg","RefreshService"]}; \ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/struct.PingMsg.html b/karyon_p2p/discovery/refresh/struct.PingMsg.html new file mode 100644 index 00000000..063e8bd8 --- /dev/null +++ b/karyon_p2p/discovery/refresh/struct.PingMsg.html @@ -0,0 +1,30 @@ +PingMsg in karyon_p2p::discovery::refresh - Rust +
pub struct PingMsg(pub [u8; 32]);

Tuple Fields§

§0: [u8; 32]

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PingMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PingMsg

source§

fn clone(&self) -> PingMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PingMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PingMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PingMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/struct.PongMsg.html b/karyon_p2p/discovery/refresh/struct.PongMsg.html new file mode 100644 index 00000000..2553385b --- /dev/null +++ b/karyon_p2p/discovery/refresh/struct.PongMsg.html @@ -0,0 +1,29 @@ +PongMsg in karyon_p2p::discovery::refresh - Rust +
pub struct PongMsg(pub [u8; 32]);

Tuple Fields§

§0: [u8; 32]

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PongMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Debug for PongMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PongMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PongMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/discovery/refresh/struct.RefreshService.html b/karyon_p2p/discovery/refresh/struct.RefreshService.html new file mode 100644 index 00000000..7033c6d5 --- /dev/null +++ b/karyon_p2p/discovery/refresh/struct.RefreshService.html @@ -0,0 +1,65 @@ +RefreshService in karyon_p2p::discovery::refresh - Rust +
pub struct RefreshService {
+    table: Arc<Mutex<RoutingTable>>,
+    listen_endpoint: Option<RwLock<Endpoint>>,
+    task_group: TaskGroup<'static>,
+    executor: GlobalExecutor,
+    config: Arc<Config>,
+    monitor: Arc<Monitor>,
+}

Fields§

§table: Arc<Mutex<RoutingTable>>

Routing table

+
§listen_endpoint: Option<RwLock<Endpoint>>

Resolved listen endpoint

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+
§executor: GlobalExecutor

A global executor

+
§config: Arc<Config>

Holds the configuration for the P2P network.

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+

Implementations§

source§

impl RefreshService

source

pub fn new( + config: Arc<Config>, + table: Arc<Mutex<RoutingTable>>, + monitor: Arc<Monitor>, + executor: GlobalExecutor +) -> Self

Creates a new refresh service

+
source

pub async fn start(self: &Arc<Self>) -> Result<(), Error>

Start the refresh service

+
source

pub async fn set_listen_endpoint(&self, resolved_endpoint: &Endpoint)

Set the resolved listen endpoint.

+
source

pub async fn shutdown(&self)

Shuts down the refresh service

+
source

async fn refresh_loop(self: Arc<Self>) -> Result<(), Error>

Initiates periodic refreshing of the routing table. This function will +selects the first 8 entries (oldest entries) from each bucket in the +routing table and starts sending Ping messages to the collected entries.

+
source

async fn do_refresh(self: Arc<Self>, entries: &[BucketEntry])

Iterates over the entries and spawns a new task for each entry to +initiate a connection attempt.

+
source

async fn refresh_entry(self: Arc<Self>, bucket_entry: BucketEntry)

Initiates refresh for a specific entry within the routing table. It +updates the routing table according to the result.

+
source

async fn connect(&self, entry: &Entry) -> Result<(), Error>

Initiates a UDP connection with the entry and attempts to send a Ping +message. If it fails, it retries according to the allowed retries +specified in the Config, with backoff between each retry.

+
source

async fn listen_loop( + self: Arc<Self>, + addr: Addr, + port: Port +) -> Result<(), Error>

Set up a UDP listener and start listening for Ping messages from other +peers.

+
source

async fn listen_to_ping_msg(&self, conn: &UdpConn) -> Result<(), Error>

Listen to receive a Ping message and respond with a Pong message.

+
source

async fn send_ping_msg(&self, conn: &UdpConn) -> Result<(), Error>

Sends a Ping msg and wait to receive the Pong message.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/discovery/sidebar-items.js b/karyon_p2p/discovery/sidebar-items.js new file mode 100644 index 00000000..bcf830a9 --- /dev/null +++ b/karyon_p2p/discovery/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["lookup","refresh"],"struct":["Discovery"],"type":["ArcDiscovery"]}; \ No newline at end of file diff --git a/karyon_p2p/discovery/struct.Discovery.html b/karyon_p2p/discovery/struct.Discovery.html new file mode 100644 index 00000000..49973d8f --- /dev/null +++ b/karyon_p2p/discovery/struct.Discovery.html @@ -0,0 +1,73 @@ +Discovery in karyon_p2p::discovery - Rust +
pub struct Discovery {
+    table: Arc<Mutex<RoutingTable>>,
+    lookup_service: Arc<LookupService>,
+    refresh_service: Arc<RefreshService>,
+    connector: Arc<Connector>,
+    listener: Arc<Listener>,
+    conn_queue: Arc<ConnQueue>,
+    pub(crate) inbound_slots: Arc<ConnectionSlots>,
+    pub(crate) outbound_slots: Arc<ConnectionSlots>,
+    task_group: TaskGroup<'static>,
+    config: Arc<Config>,
+}

Fields§

§table: Arc<Mutex<RoutingTable>>

Routing table

+
§lookup_service: Arc<LookupService>

Lookup Service

+
§refresh_service: Arc<RefreshService>

Refresh Service

+
§connector: Arc<Connector>

Connector

+
§listener: Arc<Listener>

Listener

+
§conn_queue: Arc<ConnQueue>

Connection queue

+
§inbound_slots: Arc<ConnectionSlots>

Inbound slots.

+
§outbound_slots: Arc<ConnectionSlots>

Outbound slots.

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+
§config: Arc<Config>

Holds the configuration for the P2P network.

+

Implementations§

source§

impl Discovery

source

pub fn new( + key_pair: &KeyPair, + peer_id: &PeerID, + conn_queue: Arc<ConnQueue>, + config: Arc<Config>, + monitor: Arc<Monitor>, + ex: GlobalExecutor +) -> Arc<Discovery>

Creates a new Discovery

+
source

pub async fn start(self: &Arc<Self>) -> Result<(), Error>

Start the Discovery

+
source

pub async fn shutdown(&self)

Shuts down the discovery

+
source

async fn start_listener( + self: &Arc<Self>, + endpoint: &Endpoint +) -> Result<Endpoint, Error>

Start a listener and on success, return the resolved endpoint.

+
source

async fn connect_loop(self: Arc<Self>) -> Result<(), Error>

This method will attempt to connect to a peer in the routing table. +If the routing table is empty, it will start the seeding process for +finding new peers.

+

This will perform a backoff to prevent getting stuck in the loop +if the seeding process couldn’t find any peers.

+
source

async fn connect(self: &Arc<Self>, endpoint: &Endpoint, pid: Option<PeerID>)

Connect to the given endpoint using the connector

+
source

async fn start_seeding(&self)

Starts seeding process.

+

This method randomly selects a peer from the routing table and +attempts to connect to that peer for the initial lookup. If the routing +table doesn’t have an available entry, it will connect to one of the +provided bootstrap endpoints in the Config and initiate the lookup.

+
source

async fn random_entry(&self, entry_flag: u16) -> Option<Entry>

Returns a random entry from routing table.

+
source

async fn update_entry(&self, pid: &PeerID, entry_flag: u16)

Update the entry status

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/discovery/type.ArcDiscovery.html b/karyon_p2p/discovery/type.ArcDiscovery.html new file mode 100644 index 00000000..aa557923 --- /dev/null +++ b/karyon_p2p/discovery/type.ArcDiscovery.html @@ -0,0 +1,6 @@ +ArcDiscovery in karyon_p2p::discovery - Rust +
pub type ArcDiscovery = Arc<Discovery>;

Aliased Type§

struct ArcDiscovery {
+    ptr: NonNull<ArcInner<Discovery>>,
+    phantom: PhantomData<ArcInner<Discovery>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Discovery>>§phantom: PhantomData<ArcInner<Discovery>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/enum.P2pError.html b/karyon_p2p/enum.P2pError.html new file mode 100644 index 00000000..072b5356 --- /dev/null +++ b/karyon_p2p/enum.P2pError.html @@ -0,0 +1,54 @@ +P2pError in karyon_p2p - Rust +

Enum karyon_p2p::P2pError

source ·
pub enum P2pError {
+
Show 25 variants IO(Error), + UnsupportedProtocol(String), + TryFromPublicKey(&'static str), + InvalidMsg(String), + IncompatiblePeer, + ParseIntError(ParseIntError), + ParseFloatError(ParseFloatError), + SemverError(Error), + ParseError(String), + IncompatibleVersion(String), + Config(String), + PeerShutdown, + InvalidPongMsg, + Discovery(&'static str), + Lookup(&'static str), + PeerAlreadyConnected, + Yasna(ASN1Error), + X509Parser(X509Error), + Rcgen(Error), + Rustls(Error), + InvalidDnsNameError(InvalidDnsNameError), + ChannelSend(String), + ChannelRecv(RecvError), + KaryonCore(Error), + KaryonNet(NetError), +
}
Expand description

Represents karyon’s p2p Error.

+

Variants§

§

IO(Error)

§

UnsupportedProtocol(String)

§

TryFromPublicKey(&'static str)

§

InvalidMsg(String)

§

IncompatiblePeer

§

ParseIntError(ParseIntError)

§

ParseFloatError(ParseFloatError)

§

SemverError(Error)

§

ParseError(String)

§

IncompatibleVersion(String)

§

Config(String)

§

PeerShutdown

§

InvalidPongMsg

§

Discovery(&'static str)

§

Lookup(&'static str)

§

PeerAlreadyConnected

§

Yasna(ASN1Error)

§

X509Parser(X509Error)

§

Rcgen(Error)

§

Rustls(Error)

§

InvalidDnsNameError(InvalidDnsNameError)

§

ChannelSend(String)

§

ChannelRecv(RecvError)

§

KaryonCore(Error)

§

KaryonNet(NetError)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<ASN1Error> for Error

source§

fn from(source: ASN1Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<InvalidDnsNameError> for Error

source§

fn from(source: InvalidDnsNameError) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: NetError) -> Self

Converts to this type from the input type.
source§

impl From<ParseFloatError> for Error

source§

fn from(source: ParseFloatError) -> Self

Converts to this type from the input type.
source§

impl From<ParseIntError> for Error

source§

fn from(source: ParseIntError) -> Self

Converts to this type from the input type.
source§

impl From<RecvError> for Error

source§

fn from(source: RecvError) -> Self

Converts to this type from the input type.
source§

impl<T> From<SendError<T>> for Error

source§

fn from(error: SendError<T>) -> Self

Converts to this type from the input type.
source§

impl From<X509Error> for Error

source§

fn from(source: X509Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/error/enum.Error.html b/karyon_p2p/error/enum.Error.html new file mode 100644 index 00000000..cdb7a65d --- /dev/null +++ b/karyon_p2p/error/enum.Error.html @@ -0,0 +1,54 @@ +Error in karyon_p2p::error - Rust +

Enum karyon_p2p::error::Error

source ·
pub enum Error {
+
Show 25 variants IO(Error), + UnsupportedProtocol(String), + TryFromPublicKey(&'static str), + InvalidMsg(String), + IncompatiblePeer, + ParseIntError(ParseIntError), + ParseFloatError(ParseFloatError), + SemverError(Error), + ParseError(String), + IncompatibleVersion(String), + Config(String), + PeerShutdown, + InvalidPongMsg, + Discovery(&'static str), + Lookup(&'static str), + PeerAlreadyConnected, + Yasna(ASN1Error), + X509Parser(X509Error), + Rcgen(Error), + Rustls(Error), + InvalidDnsNameError(InvalidDnsNameError), + ChannelSend(String), + ChannelRecv(RecvError), + KaryonCore(Error), + KaryonNet(NetError), +
}
Expand description

Represents karyon’s p2p Error.

+

Variants§

§

IO(Error)

§

UnsupportedProtocol(String)

§

TryFromPublicKey(&'static str)

§

InvalidMsg(String)

§

IncompatiblePeer

§

ParseIntError(ParseIntError)

§

ParseFloatError(ParseFloatError)

§

SemverError(Error)

§

ParseError(String)

§

IncompatibleVersion(String)

§

Config(String)

§

PeerShutdown

§

InvalidPongMsg

§

Discovery(&'static str)

§

Lookup(&'static str)

§

PeerAlreadyConnected

§

Yasna(ASN1Error)

§

X509Parser(X509Error)

§

Rcgen(Error)

§

Rustls(Error)

§

InvalidDnsNameError(InvalidDnsNameError)

§

ChannelSend(String)

§

ChannelRecv(RecvError)

§

KaryonCore(Error)

§

KaryonNet(NetError)

Trait Implementations§

source§

impl Debug for Error

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Error

source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Error for Error

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<ASN1Error> for Error

source§

fn from(source: ASN1Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: Error) -> Self

Converts to this type from the input type.
source§

impl From<InvalidDnsNameError> for Error

source§

fn from(source: InvalidDnsNameError) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(source: NetError) -> Self

Converts to this type from the input type.
source§

impl From<ParseFloatError> for Error

source§

fn from(source: ParseFloatError) -> Self

Converts to this type from the input type.
source§

impl From<ParseIntError> for Error

source§

fn from(source: ParseIntError) -> Self

Converts to this type from the input type.
source§

impl From<RecvError> for Error

source§

fn from(source: RecvError) -> Self

Converts to this type from the input type.
source§

impl<T> From<SendError<T>> for Error

source§

fn from(error: SendError<T>) -> Self

Converts to this type from the input type.
source§

impl From<X509Error> for Error

source§

fn from(source: X509Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/error/index.html b/karyon_p2p/error/index.html new file mode 100644 index 00000000..71d1ce89 --- /dev/null +++ b/karyon_p2p/error/index.html @@ -0,0 +1,2 @@ +karyon_p2p::error - Rust +

Module karyon_p2p::error

source ·

Enums

  • Represents karyon’s p2p Error.

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/error/sidebar-items.js b/karyon_p2p/error/sidebar-items.js new file mode 100644 index 00000000..c851f700 --- /dev/null +++ b/karyon_p2p/error/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["Error"],"type":["Result"]}; \ No newline at end of file diff --git a/karyon_p2p/error/type.Result.html b/karyon_p2p/error/type.Result.html new file mode 100644 index 00000000..71f09443 --- /dev/null +++ b/karyon_p2p/error/type.Result.html @@ -0,0 +1,7 @@ +Result in karyon_p2p::error - Rust +

Type Alias karyon_p2p::error::Result

source ·
pub type Result<T> = Result<T, Error>;

Aliased Type§

enum Result<T> {
+    Ok(T),
+    Err(Error),
+}

Variants§

§1.0.0

Ok(T)

Contains the success value

+
§1.0.0

Err(Error)

Contains the error value

+
\ No newline at end of file diff --git a/karyon_p2p/index.html b/karyon_p2p/index.html new file mode 100644 index 00000000..de75a7f0 --- /dev/null +++ b/karyon_p2p/index.html @@ -0,0 +1,39 @@ +karyon_p2p - Rust +

Crate karyon_p2p

source ·
Expand description

A lightweight, extensible, and customizable peer-to-peer (p2p) network stack.

+

Example

+
use std::sync::Arc;
+
+use easy_parallel::Parallel;
+use smol::{channel as smol_channel, future, Executor};
+
+use karyon_core::crypto::{KeyPair, KeyPairType};
+use karyon_p2p::{Backend, Config, PeerID};
+
+let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+
+// Create the configuration for the backend.
+let mut config = Config::default();
+
+// Create a new Executor
+let ex = Arc::new(Executor::new());
+
+// Create a new Backend
+let backend = Backend::new(&key_pair, config, ex.clone());
+
+let task = async {
+    // Run the backend
+    backend.run().await.unwrap();
+
+    // ....
+
+    // Shutdown the backend
+    backend.shutdown().await;
+};
+
+future::block_on(ex.run(task));
+
+

Modules

Structs

  • Backend serves as the central entry point for initiating and managing +the P2P network.
  • the Configuration for the P2P network.
  • Represents a unique identifier for a peer.
  • Represents the network version and protocol version used in karyon p2p.

Enums

  • Represents karyon’s p2p Error.

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/listener/index.html b/karyon_p2p/listener/index.html new file mode 100644 index 00000000..dbff0601 --- /dev/null +++ b/karyon_p2p/listener/index.html @@ -0,0 +1,2 @@ +karyon_p2p::listener - Rust +

Module karyon_p2p::listener

source ·

Structs

  • Responsible for creating inbound connections with other peers.
\ No newline at end of file diff --git a/karyon_p2p/listener/sidebar-items.js b/karyon_p2p/listener/sidebar-items.js new file mode 100644 index 00000000..ea6c5958 --- /dev/null +++ b/karyon_p2p/listener/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["Listener"]}; \ No newline at end of file diff --git a/karyon_p2p/listener/struct.Listener.html b/karyon_p2p/listener/struct.Listener.html new file mode 100644 index 00000000..4faa29b8 --- /dev/null +++ b/karyon_p2p/listener/struct.Listener.html @@ -0,0 +1,62 @@ +Listener in karyon_p2p::listener - Rust +
pub struct Listener {
+    key_pair: KeyPair,
+    task_group: TaskGroup<'static>,
+    connection_slots: Arc<ConnectionSlots>,
+    enable_tls: bool,
+    monitor: Arc<Monitor>,
+}
Expand description

Responsible for creating inbound connections with other peers.

+

Fields§

§key_pair: KeyPair

Identity Key pair

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+
§connection_slots: Arc<ConnectionSlots>

Manages available inbound slots.

+
§enable_tls: bool

Enables secure connection.

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+

Implementations§

source§

impl Listener

source

pub fn new( + key_pair: &KeyPair, + connection_slots: Arc<ConnectionSlots>, + enable_tls: bool, + monitor: Arc<Monitor>, + ex: GlobalExecutor +) -> Arc<Self>

Creates a new Listener

+
source

pub async fn start<Fut>( + self: &Arc<Self>, + endpoint: Endpoint, + callback: impl FnOnce(Conn) -> Fut + Clone + Send + 'static +) -> Result<Endpoint, Error>
where + Fut: Future<Output = Result<(), Error>> + Send + 'static,

Starts a listener on the given endpoint. For each incoming connection +that is accepted, it invokes the provided callback, and pass the +connection to the callback.

+

Returns the resloved listening endpoint.

+
source

pub async fn shutdown(&self)

Shuts down the listener

+
source

async fn listen_loop<Fut>( + self: Arc<Self>, + listener: Box<dyn ConnListener>, + callback: impl FnOnce(Conn) -> Fut + Clone + Send + 'static +)
where + Fut: Future<Output = Result<(), Error>> + Send + 'static,

source

async fn listend( + &self, + endpoint: &Endpoint +) -> Result<Box<dyn ConnListener>, Error>

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/message/constant.MAX_ALLOWED_MSG_SIZE.html b/karyon_p2p/message/constant.MAX_ALLOWED_MSG_SIZE.html new file mode 100644 index 00000000..2194e626 --- /dev/null +++ b/karyon_p2p/message/constant.MAX_ALLOWED_MSG_SIZE.html @@ -0,0 +1,3 @@ +MAX_ALLOWED_MSG_SIZE in karyon_p2p::message - Rust +
pub const MAX_ALLOWED_MSG_SIZE: u32 = _; // 1_048_576u32
Expand description

The maximum allowed size for a message in bytes.

+
\ No newline at end of file diff --git a/karyon_p2p/message/constant.MSG_HEADER_SIZE.html b/karyon_p2p/message/constant.MSG_HEADER_SIZE.html new file mode 100644 index 00000000..2d7fc9af --- /dev/null +++ b/karyon_p2p/message/constant.MSG_HEADER_SIZE.html @@ -0,0 +1,3 @@ +MSG_HEADER_SIZE in karyon_p2p::message - Rust +
pub const MSG_HEADER_SIZE: usize = 6;
Expand description

The size of the message header, in bytes.

+
\ No newline at end of file diff --git a/karyon_p2p/message/enum.NetMsgCmd.html b/karyon_p2p/message/enum.NetMsgCmd.html new file mode 100644 index 00000000..73c349b1 --- /dev/null +++ b/karyon_p2p/message/enum.NetMsgCmd.html @@ -0,0 +1,41 @@ +NetMsgCmd in karyon_p2p::message - Rust +
#[repr(u8)]
pub enum NetMsgCmd { + Version = 0, + Verack = 1, + Protocol = 2, + Shutdown = 3, + Ping = 4, + Pong = 5, + FindPeer = 6, + Peer = 7, + Peers = 8, +}
Expand description

Defines message commands.

+

Variants§

§

Version = 0

§

Verack = 1

§

Protocol = 2

§

Shutdown = 3

§

Ping = 4

§

Pong = 5

§

FindPeer = 6

§

Peer = 7

§

Peers = 8

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for NetMsgCmd

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for NetMsgCmd

source§

fn clone(&self) -> NetMsgCmd

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for NetMsgCmd

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for NetMsgCmd

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for NetMsgCmd

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/index.html b/karyon_p2p/message/index.html new file mode 100644 index 00000000..970102c4 --- /dev/null +++ b/karyon_p2p/message/index.html @@ -0,0 +1,4 @@ +karyon_p2p::message - Rust +

Module karyon_p2p::message

source ·

Macros

Structs

  • FindPeer message used to find a specific peer.
  • Defines the main message in the karyon p2p network.
  • Represents the header of a message.
  • PeerMsg containing information about a peer.
  • PeersMsg a list of PeerMsg.
  • Ping message with a nonce and version information.
  • Ping message with a nonce.
  • Defines a message related to a specific protocol.
  • Shutdown message.
  • VerAck message acknowledges the receipt of a Version message. The message +consists of the peer ID and an acknowledgment boolean value indicating +whether the version is accepted.
  • Version message, providing information about a peer’s capabilities.

Enums

Constants

\ No newline at end of file diff --git a/karyon_p2p/message/macro.get_msg_payload!.html b/karyon_p2p/message/macro.get_msg_payload!.html new file mode 100644 index 00000000..1f542474 --- /dev/null +++ b/karyon_p2p/message/macro.get_msg_payload!.html @@ -0,0 +1,11 @@ + + + + + Redirection + + +

Redirecting to macro.get_msg_payload.html...

+ + + \ No newline at end of file diff --git a/karyon_p2p/message/macro.get_msg_payload.html b/karyon_p2p/message/macro.get_msg_payload.html new file mode 100644 index 00000000..136adf36 --- /dev/null +++ b/karyon_p2p/message/macro.get_msg_payload.html @@ -0,0 +1,4 @@ +get_msg_payload in karyon_p2p::message - Rust +
macro_rules! get_msg_payload {
+    ($a:ident, $b:ident) => { ... };
+}
\ No newline at end of file diff --git a/karyon_p2p/message/sidebar-items.js b/karyon_p2p/message/sidebar-items.js new file mode 100644 index 00000000..a2ecefc9 --- /dev/null +++ b/karyon_p2p/message/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["MAX_ALLOWED_MSG_SIZE","MSG_HEADER_SIZE"],"enum":["NetMsgCmd"],"macro":["get_msg_payload"],"struct":["FindPeerMsg","NetMsg","NetMsgHeader","PeerMsg","PeersMsg","PingMsg","PongMsg","ProtocolMsg","ShutdownMsg","VerAckMsg","VerMsg"]}; \ No newline at end of file diff --git a/karyon_p2p/message/struct.FindPeerMsg.html b/karyon_p2p/message/struct.FindPeerMsg.html new file mode 100644 index 00000000..16df443a --- /dev/null +++ b/karyon_p2p/message/struct.FindPeerMsg.html @@ -0,0 +1,30 @@ +FindPeerMsg in karyon_p2p::message - Rust +
pub struct FindPeerMsg(pub PeerID);
Expand description

FindPeer message used to find a specific peer.

+

Tuple Fields§

§0: PeerID

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for FindPeerMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Debug for FindPeerMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for FindPeerMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for FindPeerMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.NetMsg.html b/karyon_p2p/message/struct.NetMsg.html new file mode 100644 index 00000000..bb21b9b7 --- /dev/null +++ b/karyon_p2p/message/struct.NetMsg.html @@ -0,0 +1,37 @@ +NetMsg in karyon_p2p::message - Rust +

Struct karyon_p2p::message::NetMsg

source ·
pub struct NetMsg {
+    pub header: NetMsgHeader,
+    pub payload: Vec<u8>,
+}
Expand description

Defines the main message in the karyon p2p network.

+

This message structure consists of a header and payload, where the header +typically contains essential information about the message, and the payload +contains the actual data being transmitted.

+

Fields§

§header: NetMsgHeader§payload: Vec<u8>

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for NetMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for NetMsg

source§

fn clone(&self) -> NetMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for NetMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for NetMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for NetMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.NetMsgHeader.html b/karyon_p2p/message/struct.NetMsgHeader.html new file mode 100644 index 00000000..4091772d --- /dev/null +++ b/karyon_p2p/message/struct.NetMsgHeader.html @@ -0,0 +1,34 @@ +NetMsgHeader in karyon_p2p::message - Rust +
pub struct NetMsgHeader {
+    pub command: NetMsgCmd,
+    pub payload_size: u32,
+}
Expand description

Represents the header of a message.

+

Fields§

§command: NetMsgCmd§payload_size: u32

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for NetMsgHeader

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for NetMsgHeader

source§

fn clone(&self) -> NetMsgHeader

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for NetMsgHeader

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for NetMsgHeader

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for NetMsgHeader

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.PeerMsg.html b/karyon_p2p/message/struct.PeerMsg.html new file mode 100644 index 00000000..e1024a7a --- /dev/null +++ b/karyon_p2p/message/struct.PeerMsg.html @@ -0,0 +1,38 @@ +PeerMsg in karyon_p2p::message - Rust +

Struct karyon_p2p::message::PeerMsg

source ·
pub struct PeerMsg {
+    pub peer_id: PeerID,
+    pub addr: Addr,
+    pub port: Port,
+    pub discovery_port: Port,
+}
Expand description

PeerMsg containing information about a peer.

+

Fields§

§peer_id: PeerID§addr: Addr§port: Port§discovery_port: Port

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PeerMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PeerMsg

source§

fn clone(&self) -> PeerMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PeerMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PeerMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PeerMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl From<Entry> for PeerMsg

source§

fn from(entry: Entry) -> PeerMsg

Converts to this type from the input type.
source§

impl From<PeerMsg> for Entry

source§

fn from(peer: PeerMsg) -> Entry

Converts to this type from the input type.
source§

impl PartialEq for PeerMsg

source§

fn eq(&self, other: &PeerMsg) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl Eq for PeerMsg

source§

impl StructuralEq for PeerMsg

source§

impl StructuralPartialEq for PeerMsg

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.PeersMsg.html b/karyon_p2p/message/struct.PeersMsg.html new file mode 100644 index 00000000..cb7244b8 --- /dev/null +++ b/karyon_p2p/message/struct.PeersMsg.html @@ -0,0 +1,30 @@ +PeersMsg in karyon_p2p::message - Rust +
pub struct PeersMsg(pub Vec<PeerMsg>);
Expand description

PeersMsg a list of PeerMsg.

+

Tuple Fields§

§0: Vec<PeerMsg>

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PeersMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Debug for PeersMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PeersMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PeersMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.PingMsg.html b/karyon_p2p/message/struct.PingMsg.html new file mode 100644 index 00000000..34647934 --- /dev/null +++ b/karyon_p2p/message/struct.PingMsg.html @@ -0,0 +1,34 @@ +PingMsg in karyon_p2p::message - Rust +

Struct karyon_p2p::message::PingMsg

source ·
pub struct PingMsg {
+    pub nonce: [u8; 32],
+    pub version: VersionInt,
+}
Expand description

Ping message with a nonce and version information.

+

Fields§

§nonce: [u8; 32]§version: VersionInt

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PingMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PingMsg

source§

fn clone(&self) -> PingMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PingMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PingMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PingMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.PongMsg.html b/karyon_p2p/message/struct.PongMsg.html new file mode 100644 index 00000000..4880ab53 --- /dev/null +++ b/karyon_p2p/message/struct.PongMsg.html @@ -0,0 +1,30 @@ +PongMsg in karyon_p2p::message - Rust +

Struct karyon_p2p::message::PongMsg

source ·
pub struct PongMsg(pub [u8; 32]);
Expand description

Ping message with a nonce.

+

Tuple Fields§

§0: [u8; 32]

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PongMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Debug for PongMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PongMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PongMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.ProtocolMsg.html b/karyon_p2p/message/struct.ProtocolMsg.html new file mode 100644 index 00000000..4382bfc1 --- /dev/null +++ b/karyon_p2p/message/struct.ProtocolMsg.html @@ -0,0 +1,34 @@ +ProtocolMsg in karyon_p2p::message - Rust +
pub struct ProtocolMsg {
+    pub protocol_id: ProtocolID,
+    pub payload: Vec<u8>,
+}
Expand description

Defines a message related to a specific protocol.

+

Fields§

§protocol_id: ProtocolID§payload: Vec<u8>

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for ProtocolMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for ProtocolMsg

source§

fn clone(&self) -> ProtocolMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ProtocolMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for ProtocolMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for ProtocolMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.ShutdownMsg.html b/karyon_p2p/message/struct.ShutdownMsg.html new file mode 100644 index 00000000..7d0bdd17 --- /dev/null +++ b/karyon_p2p/message/struct.ShutdownMsg.html @@ -0,0 +1,31 @@ +ShutdownMsg in karyon_p2p::message - Rust +
pub struct ShutdownMsg(pub u8);
Expand description

Shutdown message.

+

Tuple Fields§

§0: u8

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for ShutdownMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for ShutdownMsg

source§

fn clone(&self) -> ShutdownMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ShutdownMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for ShutdownMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for ShutdownMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.VerAckMsg.html b/karyon_p2p/message/struct.VerAckMsg.html new file mode 100644 index 00000000..5f82e831 --- /dev/null +++ b/karyon_p2p/message/struct.VerAckMsg.html @@ -0,0 +1,36 @@ +VerAckMsg in karyon_p2p::message - Rust +
pub struct VerAckMsg {
+    pub peer_id: PeerID,
+    pub ack: bool,
+}
Expand description

VerAck message acknowledges the receipt of a Version message. The message +consists of the peer ID and an acknowledgment boolean value indicating +whether the version is accepted.

+

Fields§

§peer_id: PeerID§ack: bool

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for VerAckMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for VerAckMsg

source§

fn clone(&self) -> VerAckMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for VerAckMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for VerAckMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for VerAckMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/message/struct.VerMsg.html b/karyon_p2p/message/struct.VerMsg.html new file mode 100644 index 00000000..2dbff5c3 --- /dev/null +++ b/karyon_p2p/message/struct.VerMsg.html @@ -0,0 +1,35 @@ +VerMsg in karyon_p2p::message - Rust +

Struct karyon_p2p::message::VerMsg

source ·
pub struct VerMsg {
+    pub peer_id: PeerID,
+    pub version: VersionInt,
+    pub protocols: HashMap<ProtocolID, VersionInt>,
+}
Expand description

Version message, providing information about a peer’s capabilities.

+

Fields§

§peer_id: PeerID§version: VersionInt§protocols: HashMap<ProtocolID, VersionInt>

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for VerMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for VerMsg

source§

fn clone(&self) -> VerMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for VerMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for VerMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for VerMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/monitor/enum.ConnEvent.html b/karyon_p2p/monitor/enum.ConnEvent.html new file mode 100644 index 00000000..99f5552d --- /dev/null +++ b/karyon_p2p/monitor/enum.ConnEvent.html @@ -0,0 +1,38 @@ +ConnEvent in karyon_p2p::monitor - Rust +
pub enum ConnEvent {
+    Connected(Endpoint),
+    ConnectRetried(Endpoint),
+    ConnectFailed(Endpoint),
+    Accepted(Endpoint),
+    AcceptFailed,
+    Disconnected(Endpoint),
+    Listening(Endpoint),
+    ListenFailed(Endpoint),
+}
Expand description

Defines connection-related events.

+

Variants§

§

Connected(Endpoint)

§

ConnectRetried(Endpoint)

§

ConnectFailed(Endpoint)

§

Accepted(Endpoint)

§

AcceptFailed

§

Disconnected(Endpoint)

§

Listening(Endpoint)

§

ListenFailed(Endpoint)

Trait Implementations§

source§

impl Clone for ConnEvent

source§

fn clone(&self) -> ConnEvent

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ConnEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for ConnEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<ConnEvent> for MonitorEvent

source§

fn from(val: ConnEvent) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/monitor/enum.DiscoveryEvent.html b/karyon_p2p/monitor/enum.DiscoveryEvent.html new file mode 100644 index 00000000..c1076669 --- /dev/null +++ b/karyon_p2p/monitor/enum.DiscoveryEvent.html @@ -0,0 +1,34 @@ +DiscoveryEvent in karyon_p2p::monitor - Rust +
pub enum DiscoveryEvent {
+    LookupStarted(Endpoint),
+    LookupFailed(Endpoint),
+    LookupSucceeded(Endpoint, usize),
+    RefreshStarted,
+}
Expand description

Defines Discovery events.

+

Variants§

§

LookupStarted(Endpoint)

§

LookupFailed(Endpoint)

§

LookupSucceeded(Endpoint, usize)

§

RefreshStarted

Trait Implementations§

source§

impl Clone for DiscoveryEvent

source§

fn clone(&self) -> DiscoveryEvent

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for DiscoveryEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for DiscoveryEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<DiscoveryEvent> for MonitorEvent

source§

fn from(val: DiscoveryEvent) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/monitor/enum.MonitorEvent.html b/karyon_p2p/monitor/enum.MonitorEvent.html new file mode 100644 index 00000000..e5b02ed3 --- /dev/null +++ b/karyon_p2p/monitor/enum.MonitorEvent.html @@ -0,0 +1,33 @@ +MonitorEvent in karyon_p2p::monitor - Rust +
pub enum MonitorEvent {
+    Conn(ConnEvent),
+    PeerPool(PeerPoolEvent),
+    Discovery(DiscoveryEvent),
+}
Expand description

Defines various type of event that can be monitored.

+

Variants§

Trait Implementations§

source§

impl Clone for MonitorEvent

source§

fn clone(&self) -> MonitorEvent

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for MonitorEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for MonitorEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<ConnEvent> for MonitorEvent

source§

fn from(val: ConnEvent) -> Self

Converts to this type from the input type.
source§

impl From<DiscoveryEvent> for MonitorEvent

source§

fn from(val: DiscoveryEvent) -> Self

Converts to this type from the input type.
source§

impl From<PeerPoolEvent> for MonitorEvent

source§

fn from(val: PeerPoolEvent) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/monitor/enum.PeerPoolEvent.html b/karyon_p2p/monitor/enum.PeerPoolEvent.html new file mode 100644 index 00000000..a4bb5aa8 --- /dev/null +++ b/karyon_p2p/monitor/enum.PeerPoolEvent.html @@ -0,0 +1,32 @@ +PeerPoolEvent in karyon_p2p::monitor - Rust +
pub enum PeerPoolEvent {
+    NewPeer(PeerID),
+    RemovePeer(PeerID),
+}
Expand description

Defines PeerPool events.

+

Variants§

§

NewPeer(PeerID)

§

RemovePeer(PeerID)

Trait Implementations§

source§

impl Clone for PeerPoolEvent

source§

fn clone(&self) -> PeerPoolEvent

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PeerPoolEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for PeerPoolEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<PeerPoolEvent> for MonitorEvent

source§

fn from(val: PeerPoolEvent) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/monitor/index.html b/karyon_p2p/monitor/index.html new file mode 100644 index 00000000..43dd4412 --- /dev/null +++ b/karyon_p2p/monitor/index.html @@ -0,0 +1,4 @@ +karyon_p2p::monitor - Rust +

Module karyon_p2p::monitor

source ·
Expand description

Responsible for network and system monitoring. +Read More

+

Structs

  • Responsible for network and system monitoring.

Enums

\ No newline at end of file diff --git a/karyon_p2p/monitor/sidebar-items.js b/karyon_p2p/monitor/sidebar-items.js new file mode 100644 index 00000000..9b3f3ac1 --- /dev/null +++ b/karyon_p2p/monitor/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["ConnEvent","DiscoveryEvent","MonitorEvent","PeerPoolEvent"],"struct":["Monitor"]}; \ No newline at end of file diff --git a/karyon_p2p/monitor/struct.Monitor.html b/karyon_p2p/monitor/struct.Monitor.html new file mode 100644 index 00000000..e6fabb14 --- /dev/null +++ b/karyon_p2p/monitor/struct.Monitor.html @@ -0,0 +1,53 @@ +Monitor in karyon_p2p::monitor - Rust +

Struct karyon_p2p::monitor::Monitor

source ·
pub struct Monitor {
+    inner: ArcPublisher<MonitorEvent>,
+}
Expand description

Responsible for network and system monitoring.

+

It use pub-sub pattern to notify the subscribers with new events.

+

Example

+
use std::sync::Arc;
+
+use smol::Executor;
+
+use karyon_core::crypto::{KeyPair, KeyPairType};
+use karyon_p2p::{Config, Backend, PeerID};
+
+async {
+     
+    // Create a new Executor
+    let ex = Arc::new(Executor::new());
+
+    let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+    let backend = Backend::new(&key_pair, Config::default(), ex);
+
+    // Create a new Subscription
+    let sub =  backend.monitor().await;
+     
+    let event = sub.recv().await;
+};
+

Fields§

§inner: ArcPublisher<MonitorEvent>

Implementations§

source§

impl Monitor

source

pub(crate) fn new() -> Monitor

Creates a new Monitor

+
source

pub async fn notify(&self, event: &MonitorEvent)

Sends a new monitor event to all subscribers.

+
source

pub async fn subscribe(&self) -> Subscription<MonitorEvent>

Subscribes to listen to new events.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/peer/index.html b/karyon_p2p/peer/index.html new file mode 100644 index 00000000..be580706 --- /dev/null +++ b/karyon_p2p/peer/index.html @@ -0,0 +1,2 @@ +karyon_p2p::peer - Rust +

Module karyon_p2p::peer

source ·

Re-exports

Modules

Structs

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/peer/peer_id/index.html b/karyon_p2p/peer/peer_id/index.html new file mode 100644 index 00000000..d81d4b43 --- /dev/null +++ b/karyon_p2p/peer/peer_id/index.html @@ -0,0 +1,2 @@ +karyon_p2p::peer::peer_id - Rust +

Module karyon_p2p::peer::peer_id

source ·

Structs

  • Represents a unique identifier for a peer.
\ No newline at end of file diff --git a/karyon_p2p/peer/peer_id/sidebar-items.js b/karyon_p2p/peer/peer_id/sidebar-items.js new file mode 100644 index 00000000..fb28b7da --- /dev/null +++ b/karyon_p2p/peer/peer_id/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["PeerID"]}; \ No newline at end of file diff --git a/karyon_p2p/peer/peer_id/struct.PeerID.html b/karyon_p2p/peer/peer_id/struct.PeerID.html new file mode 100644 index 00000000..1389cc18 --- /dev/null +++ b/karyon_p2p/peer/peer_id/struct.PeerID.html @@ -0,0 +1,38 @@ +PeerID in karyon_p2p::peer::peer_id - Rust +

Struct karyon_p2p::peer::peer_id::PeerID

source ·
pub struct PeerID(pub [u8; 32]);
Expand description

Represents a unique identifier for a peer.

+

Tuple Fields§

§0: [u8; 32]

Implementations§

source§

impl PeerID

source

pub fn new(src: &[u8]) -> Self

Creates a new PeerID.

+
source

pub fn random() -> Self

Generates a random PeerID.

+

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PeerID

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PeerID

source§

fn clone(&self) -> PeerID

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PeerID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PeerID

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Display for PeerID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encode for PeerID

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl From<[u8; 32]> for PeerID

source§

fn from(b: [u8; 32]) -> Self

Converts to this type from the input type.
source§

impl Hash for PeerID

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for PeerID

source§

fn eq(&self, other: &PeerID) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<PublicKey> for PeerID

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(pk: PublicKey) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl Eq for PeerID

source§

impl StructuralEq for PeerID

source§

impl StructuralPartialEq for PeerID

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/peer/sidebar-items.js b/karyon_p2p/peer/sidebar-items.js new file mode 100644 index 00000000..8f22bdab --- /dev/null +++ b/karyon_p2p/peer/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["peer_id"],"struct":["Peer"],"type":["ArcPeer"]}; \ No newline at end of file diff --git a/karyon_p2p/peer/struct.Peer.html b/karyon_p2p/peer/struct.Peer.html new file mode 100644 index 00000000..773c7e94 --- /dev/null +++ b/karyon_p2p/peer/struct.Peer.html @@ -0,0 +1,71 @@ +Peer in karyon_p2p::peer - Rust +

Struct karyon_p2p::peer::Peer

source ·
pub struct Peer {
+    id: PeerID,
+    peer_pool: Weak<PeerPool>,
+    codec: Codec,
+    remote_endpoint: Endpoint,
+    conn_direction: ConnDirection,
+    protocol_ids: RwLock<Vec<ProtocolID>>,
+    protocol_events: ArcEventSys<ProtocolID>,
+    stop_chan: (Sender<Result<(), Error>>, Receiver<Result<(), Error>>),
+    task_group: TaskGroup<'static>,
+}

Fields§

§id: PeerID

Peer’s ID

+
§peer_pool: Weak<PeerPool>

A weak pointer to PeerPool

+
§codec: Codec

Holds the Codec for the peer connection

+
§remote_endpoint: Endpoint

Remote endpoint for the peer

+
§conn_direction: ConnDirection

The direction of the connection, either Inbound or Outbound

+
§protocol_ids: RwLock<Vec<ProtocolID>>

A list of protocol IDs

+
§protocol_events: ArcEventSys<ProtocolID>

EventSys responsible for sending events to the protocols.

+
§stop_chan: (Sender<Result<(), Error>>, Receiver<Result<(), Error>>)

This channel is used to send a stop signal to the read loop.

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+

Implementations§

source§

impl Peer

source

pub fn new( + peer_pool: Weak<PeerPool>, + id: &PeerID, + codec: Codec, + remote_endpoint: Endpoint, + conn_direction: ConnDirection, + ex: GlobalExecutor +) -> ArcPeer

Creates a new peer

+
source

pub async fn run(self: Arc<Self>) -> Result<(), Error>

Run the peer

+
source

pub async fn send<T: CodecMsg>( + &self, + protocol_id: &ProtocolID, + msg: &T +) -> Result<(), Error>

Send a message to the peer connection using the specified protocol.

+
source

pub async fn broadcast<T: CodecMsg>(&self, protocol_id: &ProtocolID, msg: &T)

Broadcast a message to all connected peers using the specified protocol.

+
source

pub async fn shutdown(&self)

Shuts down the peer

+
source

pub fn is_inbound(&self) -> bool

Check if the connection is Inbound

+
source

pub fn direction(&self) -> &ConnDirection

Returns the direction of the connection, which can be either Inbound +or Outbound.

+
source

pub fn remote_endpoint(&self) -> &Endpoint

Returns the remote endpoint for the peer

+
source

pub fn id(&self) -> &PeerID

Return the peer’s ID

+
source

pub fn config(&self) -> Arc<Config>

Returns the Config instance.

+
source

pub async fn register_listener<P: Protocol>( + &self +) -> EventListener<ProtocolID, ProtocolEvent>

Registers a listener for the given Protocol P.

+
source

async fn read_loop(&self) -> Result<(), Error>

Start a read loop to handle incoming messages from the peer connection.

+
source

async fn start_protocols(self: &Arc<Self>)

Start running the protocols for this peer connection.

+
source

fn peer_pool(&self) -> Arc<PeerPool>

Auto Trait Implementations§

§

impl !RefUnwindSafe for Peer

§

impl Send for Peer

§

impl Sync for Peer

§

impl !Unpin for Peer

§

impl !UnwindSafe for Peer

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/peer/type.ArcPeer.html b/karyon_p2p/peer/type.ArcPeer.html new file mode 100644 index 00000000..05b3bdee --- /dev/null +++ b/karyon_p2p/peer/type.ArcPeer.html @@ -0,0 +1,6 @@ +ArcPeer in karyon_p2p::peer - Rust +

Type Alias karyon_p2p::peer::ArcPeer

source ·
pub type ArcPeer = Arc<Peer>;

Aliased Type§

struct ArcPeer {
+    ptr: NonNull<ArcInner<Peer>>,
+    phantom: PhantomData<ArcInner<Peer>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Peer>>§phantom: PhantomData<ArcInner<Peer>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/peer_pool/index.html b/karyon_p2p/peer_pool/index.html new file mode 100644 index 00000000..3ec7a7fd --- /dev/null +++ b/karyon_p2p/peer_pool/index.html @@ -0,0 +1,2 @@ +karyon_p2p::peer_pool - Rust +

Module karyon_p2p::peer_pool

source ·

Structs

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/peer_pool/sidebar-items.js b/karyon_p2p/peer_pool/sidebar-items.js new file mode 100644 index 00000000..57b8571d --- /dev/null +++ b/karyon_p2p/peer_pool/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["PeerPool"],"type":["ArcPeerPool","WeakPeerPool"]}; \ No newline at end of file diff --git a/karyon_p2p/peer_pool/struct.PeerPool.html b/karyon_p2p/peer_pool/struct.PeerPool.html new file mode 100644 index 00000000..1c7f0248 --- /dev/null +++ b/karyon_p2p/peer_pool/struct.PeerPool.html @@ -0,0 +1,84 @@ +PeerPool in karyon_p2p::peer_pool - Rust +
pub struct PeerPool {
+    pub id: PeerID,
+    conn_queue: Arc<ConnQueue>,
+    peers: Mutex<HashMap<PeerID, ArcPeer>>,
+    pub(crate) protocols: RwLock<HashMap<ProtocolID, Box<ProtocolConstructor>>>,
+    protocol_versions: Arc<RwLock<HashMap<ProtocolID, Version>>>,
+    task_group: TaskGroup<'static>,
+    executor: GlobalExecutor,
+    pub(crate) config: Arc<Config>,
+    monitor: Arc<Monitor>,
+}

Fields§

§id: PeerID

Peer’s ID

+
§conn_queue: Arc<ConnQueue>

Connection queue

+
§peers: Mutex<HashMap<PeerID, ArcPeer>>

Holds the running peers.

+
§protocols: RwLock<HashMap<ProtocolID, Box<ProtocolConstructor>>>

Hashmap contains protocol constructors.

+
§protocol_versions: Arc<RwLock<HashMap<ProtocolID, Version>>>

Hashmap contains protocol IDs and their versions.

+
§task_group: TaskGroup<'static>

Managing spawned tasks.

+
§executor: GlobalExecutor

A global Executor

+
§config: Arc<Config>

The Configuration for the P2P network.

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+

Implementations§

source§

impl PeerPool

source

pub fn new( + id: &PeerID, + conn_queue: Arc<ConnQueue>, + config: Arc<Config>, + monitor: Arc<Monitor>, + executor: GlobalExecutor +) -> Arc<Self>

Creates a new PeerPool

+
source

pub async fn start(self: &Arc<Self>) -> Result<(), Error>

Start

+
source

pub async fn listen_loop(self: Arc<Self>)

Listens to a new connection from the connection queue

+
source

pub async fn shutdown(&self)

Shuts down

+
source

pub async fn attach_protocol<P: Protocol>( + &self, + c: Box<ProtocolConstructor> +) -> Result<(), Error>

Attach a custom protocol to the network

+
source

pub async fn peers_len(&self) -> usize

Returns the number of currently connected peers.

+
source

pub async fn broadcast<T: CodecMsg>(&self, proto_id: &ProtocolID, msg: &T)

Broadcast a message to all connected peers using the specified protocol.

+
source

pub async fn new_peer( + self: &Arc<Self>, + conn: Conn, + conn_direction: &ConnDirection, + disconnect_signal: Sender<Result<(), Error>> +) -> Result<(), Error>

Add a new peer to the peer list.

+
source

pub async fn contains_peer(&self, pid: &PeerID) -> bool

Checks if the peer list contains a peer with the given peer id

+
source

async fn remove_peer(&self, pid: &PeerID) -> Result<(), Error>

Shuts down the peer and remove it from the peer list.

+
source

async fn setup_protocols(&self) -> Result<(), Error>

Attach the core protocols.

+
source

async fn do_handshake( + &self, + codec: &Codec, + conn_direction: &ConnDirection +) -> Result<PeerID, Error>

Initiate a handshake with a connection.

+
source

async fn send_vermsg(&self, codec: &Codec) -> Result<(), Error>

Send a Version message

+
source

async fn wait_vermsg(&self, codec: &Codec) -> Result<PeerID, Error>

Wait for a Version message

+

Returns the peer’s ID upon successfully receiving the Version message.

+
source

async fn send_verack(&self, codec: &Codec, ack: bool) -> Result<(), Error>

Send a Verack message

+
source

async fn wait_verack(&self, codec: &Codec) -> Result<PeerID, Error>

Wait for a Verack message

+

Returns the peer’s ID upon successfully receiving the Verack message.

+
source

async fn protocols_match( + &self, + protocols: &HashMap<ProtocolID, VersionInt> +) -> Result<(), Error>

Check if the new connection has compatible protocols.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/peer_pool/type.ArcPeerPool.html b/karyon_p2p/peer_pool/type.ArcPeerPool.html new file mode 100644 index 00000000..5850420c --- /dev/null +++ b/karyon_p2p/peer_pool/type.ArcPeerPool.html @@ -0,0 +1,6 @@ +ArcPeerPool in karyon_p2p::peer_pool - Rust +

Type Alias karyon_p2p::peer_pool::ArcPeerPool

source ·
pub type ArcPeerPool = Arc<PeerPool>;

Aliased Type§

struct ArcPeerPool {
+    ptr: NonNull<ArcInner<PeerPool>>,
+    phantom: PhantomData<ArcInner<PeerPool>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<PeerPool>>§phantom: PhantomData<ArcInner<PeerPool>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/peer_pool/type.WeakPeerPool.html b/karyon_p2p/peer_pool/type.WeakPeerPool.html new file mode 100644 index 00000000..644aa7ad --- /dev/null +++ b/karyon_p2p/peer_pool/type.WeakPeerPool.html @@ -0,0 +1,5 @@ +WeakPeerPool in karyon_p2p::peer_pool - Rust +
pub type WeakPeerPool = Weak<PeerPool>;

Aliased Type§

struct WeakPeerPool {
+    ptr: NonNull<ArcInner<PeerPool>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<PeerPool>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/protocol/enum.ProtocolEvent.html b/karyon_p2p/protocol/enum.ProtocolEvent.html new file mode 100644 index 00000000..5098835e --- /dev/null +++ b/karyon_p2p/protocol/enum.ProtocolEvent.html @@ -0,0 +1,33 @@ +ProtocolEvent in karyon_p2p::protocol - Rust +
pub enum ProtocolEvent {
+    Message(Vec<u8>),
+    Shutdown,
+}
Expand description

Protocol event

+

Variants§

§

Message(Vec<u8>)

Message event, contains a vector of bytes.

+
§

Shutdown

Shutdown event signals the protocol to gracefully shut down.

+

Trait Implementations§

source§

impl Clone for ProtocolEvent

source§

fn clone(&self) -> ProtocolEvent

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ProtocolEvent

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl EventValue for ProtocolEvent

source§

fn id() -> &'static str

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/protocol/index.html b/karyon_p2p/protocol/index.html new file mode 100644 index 00000000..3e23423f --- /dev/null +++ b/karyon_p2p/protocol/index.html @@ -0,0 +1,5 @@ +karyon_p2p::protocol - Rust +

Module karyon_p2p::protocol

source ·
Expand description

Defines the protocol trait. +Read More

+

Enums

Traits

  • The Protocol trait defines the interface for core protocols +and custom protocols.

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/protocol/sidebar-items.js b/karyon_p2p/protocol/sidebar-items.js new file mode 100644 index 00000000..81c3a283 --- /dev/null +++ b/karyon_p2p/protocol/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["ProtocolEvent"],"trait":["Protocol"],"type":["ArcProtocol","ProtocolConstructor","ProtocolID"]}; \ No newline at end of file diff --git a/karyon_p2p/protocol/trait.Protocol.html b/karyon_p2p/protocol/trait.Protocol.html new file mode 100644 index 00000000..59f7d794 --- /dev/null +++ b/karyon_p2p/protocol/trait.Protocol.html @@ -0,0 +1,90 @@ +Protocol in karyon_p2p::protocol - Rust +
pub trait Protocol: Send + Sync {
+    // Required methods
+    fn start<'async_trait>(
+        self: Arc<Self>
+    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
+       where Self: 'async_trait;
+    fn version() -> Result<Version, Error>
+       where Self: Sized;
+    fn id() -> ProtocolID
+       where Self: Sized;
+}
Expand description

The Protocol trait defines the interface for core protocols +and custom protocols.

+

Example

+
use std::sync::Arc;
+
+use async_trait::async_trait;
+use smol::Executor;
+
+use karyon_core::crypto::{KeyPair, KeyPairType};
+use karyon_p2p::{
+    protocol::{ArcProtocol, Protocol, ProtocolID, ProtocolEvent},
+    Backend, PeerID, Config, Version, P2pError, ArcPeer};
+
+pub struct NewProtocol {
+    peer: ArcPeer,
+}
+
+impl NewProtocol {
+    fn new(peer: ArcPeer) -> ArcProtocol {
+        Arc::new(Self {
+            peer,
+        })
+    }
+}
+
+#[async_trait]
+impl Protocol for NewProtocol {
+    async fn start(self: Arc<Self>) -> Result<(), P2pError> {
+        let listener = self.peer.register_listener::<Self>().await;
+        loop {
+            let event = listener.recv().await.unwrap();
+
+            match event {
+                ProtocolEvent::Message(msg) => {
+                    println!("{:?}", msg);
+                }
+                ProtocolEvent::Shutdown => {
+                    break;
+                }
+            }
+        }
+
+        listener.cancel().await;
+        Ok(())
+    }
+
+    fn version() -> Result<Version, P2pError> {
+        "0.2.0, >0.1.0".parse()
+    }
+
+    fn id() -> ProtocolID {
+        "NEWPROTOCOLID".into()
+    }
+}
+
+ async {
+    let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+    let config = Config::default();
+
+    // Create a new Executor
+    let ex = Arc::new(Executor::new());
+
+    // Create a new Backend
+    let backend = Backend::new(&key_pair, config, ex);
+
+    // Attach the NewProtocol
+    let c = move |peer| NewProtocol::new(peer);
+    backend.attach_protocol::<NewProtocol>(c).await.unwrap();
+ };
+
+

Required Methods§

source

fn start<'async_trait>( + self: Arc<Self> +) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where + Self: 'async_trait,

Start the protocol

+
source

fn version() -> Result<Version, Error>
where + Self: Sized,

Returns the version of the protocol.

+
source

fn id() -> ProtocolID
where + Self: Sized,

Returns the unique ProtocolID associated with the protocol.

+

Implementors§

\ No newline at end of file diff --git a/karyon_p2p/protocol/type.ArcProtocol.html b/karyon_p2p/protocol/type.ArcProtocol.html new file mode 100644 index 00000000..9cfb28dc --- /dev/null +++ b/karyon_p2p/protocol/type.ArcProtocol.html @@ -0,0 +1,6 @@ +ArcProtocol in karyon_p2p::protocol - Rust +

Type Alias karyon_p2p::protocol::ArcProtocol

source ·
pub type ArcProtocol = Arc<dyn Protocol>;

Aliased Type§

struct ArcProtocol {
+    ptr: NonNull<ArcInner<dyn Protocol>>,
+    phantom: PhantomData<ArcInner<dyn Protocol>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<dyn Protocol>>§phantom: PhantomData<ArcInner<dyn Protocol>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/protocol/type.ProtocolConstructor.html b/karyon_p2p/protocol/type.ProtocolConstructor.html new file mode 100644 index 00000000..0bd1ca6d --- /dev/null +++ b/karyon_p2p/protocol/type.ProtocolConstructor.html @@ -0,0 +1,2 @@ +ProtocolConstructor in karyon_p2p::protocol - Rust +
pub type ProtocolConstructor = dyn Fn(ArcPeer) -> Arc<dyn Protocol> + Send + Sync;
\ No newline at end of file diff --git a/karyon_p2p/protocol/type.ProtocolID.html b/karyon_p2p/protocol/type.ProtocolID.html new file mode 100644 index 00000000..c924bd63 --- /dev/null +++ b/karyon_p2p/protocol/type.ProtocolID.html @@ -0,0 +1,4 @@ +ProtocolID in karyon_p2p::protocol - Rust +

Type Alias karyon_p2p::protocol::ProtocolID

source ·
pub type ProtocolID = String;

Aliased Type§

struct ProtocolID {
+    vec: Vec<u8>,
+}

Fields§

§vec: Vec<u8>
\ No newline at end of file diff --git a/karyon_p2p/protocols/index.html b/karyon_p2p/protocols/index.html new file mode 100644 index 00000000..935fdec7 --- /dev/null +++ b/karyon_p2p/protocols/index.html @@ -0,0 +1,2 @@ +karyon_p2p::protocols - Rust +

Module karyon_p2p::protocols

source ·

Re-exports

Modules

\ No newline at end of file diff --git a/karyon_p2p/protocols/ping/constant.MAX_FAILUERS.html b/karyon_p2p/protocols/ping/constant.MAX_FAILUERS.html new file mode 100644 index 00000000..dd558c15 --- /dev/null +++ b/karyon_p2p/protocols/ping/constant.MAX_FAILUERS.html @@ -0,0 +1,2 @@ +MAX_FAILUERS in karyon_p2p::protocols::ping - Rust +
const MAX_FAILUERS: u32 = 3;
\ No newline at end of file diff --git a/karyon_p2p/protocols/ping/enum.PingProtocolMsg.html b/karyon_p2p/protocols/ping/enum.PingProtocolMsg.html new file mode 100644 index 00000000..4b05e818 --- /dev/null +++ b/karyon_p2p/protocols/ping/enum.PingProtocolMsg.html @@ -0,0 +1,33 @@ +PingProtocolMsg in karyon_p2p::protocols::ping - Rust +
enum PingProtocolMsg {
+    Ping([u8; 32]),
+    Pong([u8; 32]),
+}

Variants§

§

Ping([u8; 32])

§

Pong([u8; 32])

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PingProtocolMsg

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PingProtocolMsg

source§

fn clone(&self) -> PingProtocolMsg

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PingProtocolMsg

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PingProtocolMsg

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for PingProtocolMsg

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/protocols/ping/index.html b/karyon_p2p/protocols/ping/index.html new file mode 100644 index 00000000..3fa3a6b8 --- /dev/null +++ b/karyon_p2p/protocols/ping/index.html @@ -0,0 +1,2 @@ +karyon_p2p::protocols::ping - Rust +

Module karyon_p2p::protocols::ping

source ·

Structs

Enums

Constants

\ No newline at end of file diff --git a/karyon_p2p/protocols/ping/sidebar-items.js b/karyon_p2p/protocols/ping/sidebar-items.js new file mode 100644 index 00000000..e8381372 --- /dev/null +++ b/karyon_p2p/protocols/ping/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["MAX_FAILUERS"],"enum":["PingProtocolMsg"],"struct":["PingProtocol"]}; \ No newline at end of file diff --git a/karyon_p2p/protocols/ping/struct.PingProtocol.html b/karyon_p2p/protocols/ping/struct.PingProtocol.html new file mode 100644 index 00000000..2137dfd7 --- /dev/null +++ b/karyon_p2p/protocols/ping/struct.PingProtocol.html @@ -0,0 +1,40 @@ +PingProtocol in karyon_p2p::protocols::ping - Rust +
pub struct PingProtocol {
+    peer: ArcPeer,
+    ping_interval: u64,
+    ping_timeout: u64,
+    task_group: TaskGroup<'static>,
+}

Fields§

§peer: ArcPeer§ping_interval: u64§ping_timeout: u64§task_group: TaskGroup<'static>

Implementations§

source§

impl PingProtocol

source

pub fn new(peer: ArcPeer, executor: GlobalExecutor) -> ArcProtocol

source

async fn recv_loop( + &self, + listener: &EventListener<ProtocolID, ProtocolEvent>, + pong_chan: Sender<[u8; 32]> +) -> Result<(), Error>

source

async fn ping_loop( + self: Arc<Self>, + chan: Receiver<[u8; 32]> +) -> Result<(), Error>

Trait Implementations§

source§

impl Protocol for PingProtocol

source§

fn start<'async_trait>( + self: Arc<Self> +) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where + Self: 'async_trait,

Start the protocol
source§

fn version() -> Result<Version, Error>

Returns the version of the protocol.
source§

fn id() -> ProtocolID

Returns the unique ProtocolID associated with the protocol.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/protocols/sidebar-items.js b/karyon_p2p/protocols/sidebar-items.js new file mode 100644 index 00000000..37e433a2 --- /dev/null +++ b/karyon_p2p/protocols/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"mod":["ping"]}; \ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.ALL_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.ALL_ENTRY.html new file mode 100644 index 00000000..98af3e20 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.ALL_ENTRY.html @@ -0,0 +1,2 @@ +ALL_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const ALL_ENTRY: u16 = 0b111111;
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.BUCKET_SIZE.html b/karyon_p2p/routing_table/bucket/constant.BUCKET_SIZE.html new file mode 100644 index 00000000..786e4b70 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.BUCKET_SIZE.html @@ -0,0 +1,3 @@ +BUCKET_SIZE in karyon_p2p::routing_table::bucket - Rust +
pub const BUCKET_SIZE: usize = 20;
Expand description

The number of entries that can be stored within a single bucket.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.CONNECTED_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.CONNECTED_ENTRY.html new file mode 100644 index 00000000..c059e137 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.CONNECTED_ENTRY.html @@ -0,0 +1,3 @@ +CONNECTED_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const CONNECTED_ENTRY: u16 = 0b000001;
Expand description

The entry is connected.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.DISCONNECTED_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.DISCONNECTED_ENTRY.html new file mode 100644 index 00000000..56d3b050 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.DISCONNECTED_ENTRY.html @@ -0,0 +1,3 @@ +DISCONNECTED_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const DISCONNECTED_ENTRY: u16 = 0b000010;
Expand description

The entry is disconnected. This will increase the failure counter.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.INCOMPATIBLE_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.INCOMPATIBLE_ENTRY.html new file mode 100644 index 00000000..e0867365 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.INCOMPATIBLE_ENTRY.html @@ -0,0 +1,5 @@ +INCOMPATIBLE_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const INCOMPATIBLE_ENTRY: u16 = 0b100000;
Expand description

The entry is incompatible. This entry will not contribute to an increase in +failure attempts, instead, it will persist in the routing table for the +lookup process and will only be removed in the presence of a new entry.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.PENDING_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.PENDING_ENTRY.html new file mode 100644 index 00000000..bfe60b7a --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.PENDING_ENTRY.html @@ -0,0 +1,4 @@ +PENDING_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const PENDING_ENTRY: u16 = 0b000100;
Expand description

The entry is ready to reconnect, meaning it has either been added and +has no connection attempts, or it has been refreshed.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.UNREACHABLE_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.UNREACHABLE_ENTRY.html new file mode 100644 index 00000000..fa305c0d --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.UNREACHABLE_ENTRY.html @@ -0,0 +1,3 @@ +UNREACHABLE_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const UNREACHABLE_ENTRY: u16 = 0b001000;
Expand description

The entry is unreachable. This will increase the failure counter.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/constant.UNSTABLE_ENTRY.html b/karyon_p2p/routing_table/bucket/constant.UNSTABLE_ENTRY.html new file mode 100644 index 00000000..ef81e42e --- /dev/null +++ b/karyon_p2p/routing_table/bucket/constant.UNSTABLE_ENTRY.html @@ -0,0 +1,3 @@ +UNSTABLE_ENTRY in karyon_p2p::routing_table::bucket - Rust +
pub const UNSTABLE_ENTRY: u16 = 0b010000;
Expand description

The entry is unstable. This will increase the failure counter.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/index.html b/karyon_p2p/routing_table/bucket/index.html new file mode 100644 index 00000000..a9dd9d98 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/index.html @@ -0,0 +1,5 @@ +karyon_p2p::routing_table::bucket - Rust +

Structs

  • A Bucket represents a group of entries in the routing table.
  • A BucketEntry represents a peer in the routing table.

Constants

  • The number of entries that can be stored within a single bucket.
  • The entry is connected.
  • The entry is disconnected. This will increase the failure counter.
  • The entry is incompatible. This entry will not contribute to an increase in +failure attempts, instead, it will persist in the routing table for the +lookup process and will only be removed in the presence of a new entry.
  • The entry is ready to reconnect, meaning it has either been added and +has no connection attempts, or it has been refreshed.
  • The entry is unreachable. This will increase the failure counter.
  • The entry is unstable. This will increase the failure counter.

Type Aliases

\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/sidebar-items.js b/karyon_p2p/routing_table/bucket/sidebar-items.js new file mode 100644 index 00000000..33881959 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["ALL_ENTRY","BUCKET_SIZE","CONNECTED_ENTRY","DISCONNECTED_ENTRY","INCOMPATIBLE_ENTRY","PENDING_ENTRY","UNREACHABLE_ENTRY","UNSTABLE_ENTRY"],"struct":["Bucket","BucketEntry"],"type":["EntryStatusFlag"]}; \ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/struct.Bucket.html b/karyon_p2p/routing_table/bucket/struct.Bucket.html new file mode 100644 index 00000000..7384a9fe --- /dev/null +++ b/karyon_p2p/routing_table/bucket/struct.Bucket.html @@ -0,0 +1,41 @@ +Bucket in karyon_p2p::routing_table::bucket - Rust +
pub struct Bucket {
+    entries: Vec<BucketEntry>,
+}
Expand description

A Bucket represents a group of entries in the routing table.

+

Fields§

§entries: Vec<BucketEntry>

Implementations§

source§

impl Bucket

source

pub fn new() -> Self

Creates a new empty Bucket

+
source

pub fn add(&mut self, entry: &Entry)

Add an entry to the bucket.

+
source

pub fn len(&self) -> usize

Get the number of entries in the bucket.

+
source

pub fn iter(&self) -> impl Iterator<Item = &BucketEntry>

Returns an iterator over the entries in the bucket.

+
source

pub fn remove(&mut self, key: &[u8; 32])

Remove an entry.

+
source

pub fn random_iter(&self, amount: usize) -> impl Iterator<Item = &BucketEntry>

Returns an iterator of entries in random order.

+
source

pub fn update_entry(&mut self, key: &[u8; 32], entry_flag: u16)

Updates the status of an entry in the bucket identified by the given key.

+

If the key is not found in the bucket, no action is taken.

+

This will also update the last_seen field and increase the failures +counter for the bucket entry according to the new status.

+
source

pub fn contains_key(&self, key: &[u8; 32]) -> bool

Check if the bucket contains the given key.

+

Trait Implementations§

source§

impl Clone for Bucket

source§

fn clone(&self) -> Bucket

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Bucket

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/struct.BucketEntry.html b/karyon_p2p/routing_table/bucket/struct.BucketEntry.html new file mode 100644 index 00000000..210b9590 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/struct.BucketEntry.html @@ -0,0 +1,33 @@ +BucketEntry in karyon_p2p::routing_table::bucket - Rust +
pub struct BucketEntry {
+    pub status: u16,
+    pub entry: Entry,
+    pub failures: u32,
+    pub last_seen: i64,
+}
Expand description

A BucketEntry represents a peer in the routing table.

+

Fields§

§status: u16§entry: Entry§failures: u32§last_seen: i64

Implementations§

source§

impl BucketEntry

source

pub fn is_connected(&self) -> bool

source

pub fn is_incompatible(&self) -> bool

source

pub fn is_unreachable(&self) -> bool

source

pub fn is_unstable(&self) -> bool

Trait Implementations§

source§

impl Clone for BucketEntry

source§

fn clone(&self) -> BucketEntry

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for BucketEntry

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/routing_table/bucket/type.EntryStatusFlag.html b/karyon_p2p/routing_table/bucket/type.EntryStatusFlag.html new file mode 100644 index 00000000..eb67e2c2 --- /dev/null +++ b/karyon_p2p/routing_table/bucket/type.EntryStatusFlag.html @@ -0,0 +1,3 @@ +EntryStatusFlag in karyon_p2p::routing_table::bucket - Rust +
pub type EntryStatusFlag = u16;
Expand description

BITFLAGS represent the status of an Entry within a bucket.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/constant.DISTANCE_LIMIT.html b/karyon_p2p/routing_table/constant.DISTANCE_LIMIT.html new file mode 100644 index 00000000..4eadce83 --- /dev/null +++ b/karyon_p2p/routing_table/constant.DISTANCE_LIMIT.html @@ -0,0 +1,3 @@ +DISTANCE_LIMIT in karyon_p2p::routing_table - Rust +
const DISTANCE_LIMIT: usize = 32;
Expand description

The distance limit for the closest buckets.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_BUCKET.html b/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_BUCKET.html new file mode 100644 index 00000000..6cbd0d9b --- /dev/null +++ b/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_BUCKET.html @@ -0,0 +1,3 @@ +MAX_MATCHED_SUBNET_IN_BUCKET in karyon_p2p::routing_table - Rust +
const MAX_MATCHED_SUBNET_IN_BUCKET: usize = 1;
Expand description

The maximum number of matched subnets allowed within a single bucket.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_TABLE.html b/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_TABLE.html new file mode 100644 index 00000000..9dc48b8b --- /dev/null +++ b/karyon_p2p/routing_table/constant.MAX_MATCHED_SUBNET_IN_TABLE.html @@ -0,0 +1,3 @@ +MAX_MATCHED_SUBNET_IN_TABLE in karyon_p2p::routing_table - Rust +
const MAX_MATCHED_SUBNET_IN_TABLE: usize = 6;
Expand description

The maximum number of matched subnets across the entire routing table.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/constant.TABLE_SIZE.html b/karyon_p2p/routing_table/constant.TABLE_SIZE.html new file mode 100644 index 00000000..330deca8 --- /dev/null +++ b/karyon_p2p/routing_table/constant.TABLE_SIZE.html @@ -0,0 +1,3 @@ +TABLE_SIZE in karyon_p2p::routing_table - Rust +
const TABLE_SIZE: usize = 32;
Expand description

The total number of buckets in the routing table.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/constant.KEY_SIZE.html b/karyon_p2p/routing_table/entry/constant.KEY_SIZE.html new file mode 100644 index 00000000..6361413b --- /dev/null +++ b/karyon_p2p/routing_table/entry/constant.KEY_SIZE.html @@ -0,0 +1,3 @@ +KEY_SIZE in karyon_p2p::routing_table::entry - Rust +
pub const KEY_SIZE: usize = 32;
Expand description

Specifies the size of the key, in bytes.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/fn.xor_distance.html b/karyon_p2p/routing_table/entry/fn.xor_distance.html new file mode 100644 index 00000000..94af5bee --- /dev/null +++ b/karyon_p2p/routing_table/entry/fn.xor_distance.html @@ -0,0 +1,5 @@ +xor_distance in karyon_p2p::routing_table::entry - Rust +
pub fn xor_distance(key: &[u8; 32], other: &[u8; 32]) -> [u8; 32]
Expand description

Calculates the XOR distance between two provided keys.

+

The XOR distance is a metric used in Kademlia to measure the closeness +of keys.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/index.html b/karyon_p2p/routing_table/entry/index.html new file mode 100644 index 00000000..4fceb3dd --- /dev/null +++ b/karyon_p2p/routing_table/entry/index.html @@ -0,0 +1,2 @@ +karyon_p2p::routing_table::entry - Rust +

Structs

  • An Entry represents a peer in the routing table.

Constants

  • Specifies the size of the key, in bytes.

Functions

  • Calculates the XOR distance between two provided keys.

Type Aliases

  • The unique key identifying the peer.
\ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/sidebar-items.js b/karyon_p2p/routing_table/entry/sidebar-items.js new file mode 100644 index 00000000..8ca522da --- /dev/null +++ b/karyon_p2p/routing_table/entry/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["KEY_SIZE"],"fn":["xor_distance"],"struct":["Entry"],"type":["Key"]}; \ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/struct.Entry.html b/karyon_p2p/routing_table/entry/struct.Entry.html new file mode 100644 index 00000000..d5f8e130 --- /dev/null +++ b/karyon_p2p/routing_table/entry/struct.Entry.html @@ -0,0 +1,42 @@ +Entry in karyon_p2p::routing_table::entry - Rust +
pub struct Entry {
+    pub key: [u8; 32],
+    pub addr: Addr,
+    pub port: Port,
+    pub discovery_port: Port,
+}
Expand description

An Entry represents a peer in the routing table.

+

Fields§

§key: [u8; 32]

The unique key identifying the peer.

+
§addr: Addr

The IP address of the peer.

+
§port: Port

TCP port

+
§discovery_port: Port

UDP/TCP port

+

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for Entry

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for Entry

source§

fn clone(&self) -> Entry

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Entry

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for Entry

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Encode for Entry

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl From<Entry> for PeerMsg

source§

fn from(entry: Entry) -> PeerMsg

Converts to this type from the input type.
source§

impl From<PeerMsg> for Entry

source§

fn from(peer: PeerMsg) -> Entry

Converts to this type from the input type.
source§

impl PartialEq for Entry

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl RefUnwindSafe for Entry

§

impl Send for Entry

§

impl Sync for Entry

§

impl Unpin for Entry

§

impl UnwindSafe for Entry

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/routing_table/entry/type.Key.html b/karyon_p2p/routing_table/entry/type.Key.html new file mode 100644 index 00000000..73911ff8 --- /dev/null +++ b/karyon_p2p/routing_table/entry/type.Key.html @@ -0,0 +1,3 @@ +Key in karyon_p2p::routing_table::entry - Rust +

Type Alias karyon_p2p::routing_table::entry::Key

source ·
pub type Key = [u8; 32];
Expand description

The unique key identifying the peer.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/enum.AddEntryResult.html b/karyon_p2p/routing_table/enum.AddEntryResult.html new file mode 100644 index 00000000..8a45a716 --- /dev/null +++ b/karyon_p2p/routing_table/enum.AddEntryResult.html @@ -0,0 +1,36 @@ +AddEntryResult in karyon_p2p::routing_table - Rust +
pub enum AddEntryResult {
+    Added,
+    Exists,
+    Ignored,
+    Restricted,
+}
Expand description

Represents the possible result when adding a new entry.

+

Variants§

§

Added

The entry is added.

+
§

Exists

The entry is already exists.

+
§

Ignored

The entry is ignored.

+
§

Restricted

The entry is restricted and not allowed.

+

Trait Implementations§

source§

impl Debug for AddEntryResult

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/routing_table/fn.subnet_match.html b/karyon_p2p/routing_table/fn.subnet_match.html new file mode 100644 index 00000000..c9de5f0f --- /dev/null +++ b/karyon_p2p/routing_table/fn.subnet_match.html @@ -0,0 +1,3 @@ +subnet_match in karyon_p2p::routing_table - Rust +
pub fn subnet_match(addr: &Addr, other_addr: &Addr) -> bool
Expand description

Check if two addresses belong to the same subnet.

+
\ No newline at end of file diff --git a/karyon_p2p/routing_table/index.html b/karyon_p2p/routing_table/index.html new file mode 100644 index 00000000..edf96ac6 --- /dev/null +++ b/karyon_p2p/routing_table/index.html @@ -0,0 +1,3 @@ +karyon_p2p::routing_table - Rust +

Re-exports

Modules

Structs

Enums

Constants

Functions

  • Check if two addresses belong to the same subnet.
\ No newline at end of file diff --git a/karyon_p2p/routing_table/sidebar-items.js b/karyon_p2p/routing_table/sidebar-items.js new file mode 100644 index 00000000..2f552e33 --- /dev/null +++ b/karyon_p2p/routing_table/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["DISTANCE_LIMIT","MAX_MATCHED_SUBNET_IN_BUCKET","MAX_MATCHED_SUBNET_IN_TABLE","TABLE_SIZE"],"enum":["AddEntryResult"],"fn":["subnet_match"],"mod":["bucket","entry"],"struct":["RoutingTable"]}; \ No newline at end of file diff --git a/karyon_p2p/routing_table/struct.RoutingTable.html b/karyon_p2p/routing_table/struct.RoutingTable.html new file mode 100644 index 00000000..47bbf73e --- /dev/null +++ b/karyon_p2p/routing_table/struct.RoutingTable.html @@ -0,0 +1,54 @@ +RoutingTable in karyon_p2p::routing_table - Rust +
pub struct RoutingTable {
+    key: [u8; 32],
+    buckets: Vec<Bucket>,
+}
Expand description

This is a modified version of the Kademlia Distributed Hash Table (DHT). +https://en.wikipedia.org/wiki/Kademlia

+

Fields§

§key: [u8; 32]§buckets: Vec<Bucket>

Implementations§

source§

impl RoutingTable

source

pub fn new(key: [u8; 32]) -> Self

Creates a new RoutingTable

+
source

pub fn add_entry(&mut self, entry: Entry) -> AddEntryResult

Adds a new entry to the table and returns a result indicating success, +failure, or restrictions.

+
source

pub fn contains_key(&self, key: &[u8; 32]) -> bool

Check if the table contains the given key.

+
source

pub fn update_entry(&mut self, key: &[u8; 32], entry_flag: u16)

Updates the status of an entry in the routing table identified +by the given key.

+

If the key is not found, no action is taken.

+
source

pub fn bucket_indexes(&self, target_key: &[u8; 32]) -> Vec<usize>

Returns a list of bucket indexes that are closest to the given target key.

+
source

pub fn closest_entries( + &self, + target_key: &[u8; 32], + max_entries: usize +) -> Vec<Entry>

Returns a list of the closest entries to the given target key, limited by max_entries.

+
source

pub fn remove_entry(&mut self, key: &[u8; 32])

Removes an entry with the given key from the routing table, if it exists.

+
source

pub fn iter(&self) -> impl Iterator<Item = &Bucket>

Returns an iterator of entries.

+
source

pub fn random_entry(&self, entry_flag: u16) -> Option<&Entry>

Returns a random entry from the routing table.

+
source

fn bucket_index(&self, key: &[u8; 32]) -> Option<usize>

source

fn subnet_restricted(&self, idx: usize, entry: &Entry) -> bool

This function iterate through the routing table and counts how many +entries in the same subnet as the given Entry are already present.

+

If the number of matching entries in the same bucket exceeds a +threshold (MAX_MATCHED_SUBNET_IN_BUCKET), or if the total count of +matching entries in the entire table exceeds a threshold +(MAX_MATCHED_SUBNET_IN_TABLE), the addition of the Entry +is considered restricted and returns true.

+

Trait Implementations§

source§

impl Debug for RoutingTable

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/sidebar-items.js b/karyon_p2p/sidebar-items.js new file mode 100644 index 00000000..663551d9 --- /dev/null +++ b/karyon_p2p/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"enum":["P2pError"],"mod":["backend","codec","config","connection","connector","discovery","error","listener","message","monitor","peer","peer_pool","protocol","protocols","routing_table","slots","tls_config","version"],"struct":["Backend","Config","PeerID","Version"],"type":["ArcBackend","ArcPeer"]}; \ No newline at end of file diff --git a/karyon_p2p/slots/index.html b/karyon_p2p/slots/index.html new file mode 100644 index 00000000..644ee057 --- /dev/null +++ b/karyon_p2p/slots/index.html @@ -0,0 +1,2 @@ +karyon_p2p::slots - Rust +

Module karyon_p2p::slots

source ·

Structs

\ No newline at end of file diff --git a/karyon_p2p/slots/sidebar-items.js b/karyon_p2p/slots/sidebar-items.js new file mode 100644 index 00000000..d2e27410 --- /dev/null +++ b/karyon_p2p/slots/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"struct":["ConnectionSlots"]}; \ No newline at end of file diff --git a/karyon_p2p/slots/struct.ConnectionSlots.html b/karyon_p2p/slots/struct.ConnectionSlots.html new file mode 100644 index 00000000..abe5c7a7 --- /dev/null +++ b/karyon_p2p/slots/struct.ConnectionSlots.html @@ -0,0 +1,39 @@ +ConnectionSlots in karyon_p2p::slots - Rust +
pub struct ConnectionSlots {
+    signal: CondWait,
+    slots: AtomicUsize,
+    max_slots: usize,
+}
Expand description

Manages available inbound and outbound slots.

+

Fields§

§signal: CondWait

A condvar for notifying when a slot become available.

+
§slots: AtomicUsize

The number of occupied slots

+
§max_slots: usize

The maximum number of slots.

+

Implementations§

source§

impl ConnectionSlots

source

pub fn new(max_slots: usize) -> Self

Creates a new ConnectionSlots

+
source

pub fn load(&self) -> usize

Returns the number of occupied slots

+
source

pub fn add(&self)

Increases the occupied slots by one.

+
source

pub async fn remove(&self)

Decreases the occupied slots by one and notifies the waiting signal +to start accepting/connecting new connections.

+
source

pub async fn wait_for_slot(&self)

Waits for a slot to become available.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/struct.Backend.html b/karyon_p2p/struct.Backend.html new file mode 100644 index 00000000..c66f8f6d --- /dev/null +++ b/karyon_p2p/struct.Backend.html @@ -0,0 +1,51 @@ +Backend in karyon_p2p - Rust +

Struct karyon_p2p::Backend

source ·
pub struct Backend {
+    config: Arc<Config>,
+    key_pair: KeyPair,
+    monitor: Arc<Monitor>,
+    discovery: Arc<Discovery>,
+    peer_pool: Arc<PeerPool>,
+}
Expand description

Backend serves as the central entry point for initiating and managing +the P2P network.

+

Fields§

§config: Arc<Config>

The Configuration for the P2P network.

+
§key_pair: KeyPair

Identity Key pair

+
§monitor: Arc<Monitor>

Responsible for network and system monitoring.

+
§discovery: Arc<Discovery>

Discovery instance.

+
§peer_pool: Arc<PeerPool>

PeerPool instance.

+

Implementations§

source§

impl Backend

source

pub fn new(key_pair: &KeyPair, config: Config, ex: GlobalExecutor) -> ArcBackend

Creates a new Backend.

+
source

pub async fn run(self: &Arc<Self>) -> Result<(), Error>

Run the Backend, starting the PeerPool and Discovery instances.

+
source

pub async fn attach_protocol<P: Protocol>( + &self, + c: impl Fn(ArcPeer) -> ArcProtocol + Send + Sync + 'static +) -> Result<(), Error>

Attach a custom protocol to the network

+
source

pub async fn peers(&self) -> usize

Returns the number of currently connected peers.

+
source

pub fn config(&self) -> Arc<Config>

Returns the Config.

+
source

pub async fn key_pair(&self) -> &KeyPair

Returns the KeyPair.

+
source

pub fn inbound_slots(&self) -> usize

Returns the number of occupied inbound slots.

+
source

pub fn outbound_slots(&self) -> usize

Returns the number of occupied outbound slots.

+
source

pub async fn monitor(&self) -> Subscription<MonitorEvent>

Subscribes to the monitor to receive network events.

+
source

pub async fn shutdown(&self)

Shuts down the Backend.

+

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/struct.Config.html b/karyon_p2p/struct.Config.html new file mode 100644 index 00000000..6c3b127e --- /dev/null +++ b/karyon_p2p/struct.Config.html @@ -0,0 +1,80 @@ +Config in karyon_p2p - Rust +

Struct karyon_p2p::Config

source ·
pub struct Config {
Show 21 fields + pub version: Version, + pub handshake_timeout: u64, + pub ping_interval: u64, + pub ping_timeout: u64, + pub max_connect_retries: usize, + pub bootstrap_peers: Vec<Endpoint>, + pub listen_endpoint: Option<Endpoint>, + pub peer_endpoints: Vec<Endpoint>, + pub inbound_slots: usize, + pub outbound_slots: usize, + pub discovery_port: Port, + pub seeding_interval: u64, + pub lookup_inbound_slots: usize, + pub lookup_outbound_slots: usize, + pub lookup_response_timeout: u64, + pub lookup_connection_lifespan: u64, + pub lookup_connect_retries: usize, + pub refresh_interval: u64, + pub refresh_response_timeout: u64, + pub refresh_connect_retries: usize, + pub enable_tls: bool, +
}
Expand description

the Configuration for the P2P network.

+

Fields§

§version: Version

Represents the network version.

+
§handshake_timeout: u64

Timeout duration for the handshake with new peers, in seconds.

+
§ping_interval: u64

Interval at which the ping protocol sends ping messages to a peer to +maintain connections, in seconds.

+
§ping_timeout: u64

Timeout duration for receiving the pong message corresponding to the +sent ping message, in seconds.

+
§max_connect_retries: usize

The maximum number of retries for outbound connection establishment.

+
§bootstrap_peers: Vec<Endpoint>

A list of bootstrap peers for the seeding process.

+
§listen_endpoint: Option<Endpoint>

An optional listening endpoint to accept incoming connections.

+
§peer_endpoints: Vec<Endpoint>

A list of endpoints representing peers that the Discovery will +manually connect to.

+
§inbound_slots: usize

The number of available inbound slots for incoming connections.

+
§outbound_slots: usize

The number of available outbound slots for outgoing connections.

+
§discovery_port: Port

TCP/UDP port for lookup and refresh processes.

+
§seeding_interval: u64

Time interval, in seconds, at which the Discovery restarts the +seeding process.

+
§lookup_inbound_slots: usize

The number of available inbound slots for incoming connections during +the lookup process.

+
§lookup_outbound_slots: usize

The number of available outbound slots for outgoing connections during +the lookup process.

+
§lookup_response_timeout: u64

Timeout duration for a peer response during the lookup process, in +seconds.

+
§lookup_connection_lifespan: u64

Maximum allowable time for a live connection with a peer during the +lookup process, in seconds.

+
§lookup_connect_retries: usize

The maximum number of retries for outbound connection establishment +during the lookup process.

+
§refresh_interval: u64

Interval at which the table refreshes its entries, in seconds.

+
§refresh_response_timeout: u64

Timeout duration for a peer response during the table refresh process, +in seconds.

+
§refresh_connect_retries: usize

The maximum number of retries for outbound connection establishment +during the refresh process.

+
§enable_tls: bool

Enables TLS for all connections.

+

Trait Implementations§

source§

impl Default for Config

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/struct.PeerID.html b/karyon_p2p/struct.PeerID.html new file mode 100644 index 00000000..0559c25b --- /dev/null +++ b/karyon_p2p/struct.PeerID.html @@ -0,0 +1,38 @@ +PeerID in karyon_p2p - Rust +

Struct karyon_p2p::PeerID

source ·
pub struct PeerID(pub [u8; 32]);
Expand description

Represents a unique identifier for a peer.

+

Tuple Fields§

§0: [u8; 32]

Implementations§

source§

impl PeerID

source

pub fn new(src: &[u8]) -> Self

Creates a new PeerID.

+
source

pub fn random() -> Self

Generates a random PeerID.

+

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for PeerID

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for PeerID

source§

fn clone(&self) -> PeerID

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for PeerID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for PeerID

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Display for PeerID

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encode for PeerID

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl From<[u8; 32]> for PeerID

source§

fn from(b: [u8; 32]) -> Self

Converts to this type from the input type.
source§

impl Hash for PeerID

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where + H: Hasher, + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for PeerID

source§

fn eq(&self, other: &PeerID) -> bool

This method tests for self and other values to be equal, and is used +by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always +sufficient, and should not be overridden without very good reason.
source§

impl TryFrom<PublicKey> for PeerID

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(pk: PublicKey) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl Eq for PeerID

source§

impl StructuralEq for PeerID

source§

impl StructuralPartialEq for PeerID

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/karyon_p2p/struct.Version.html b/karyon_p2p/struct.Version.html new file mode 100644 index 00000000..618a9f0d --- /dev/null +++ b/karyon_p2p/struct.Version.html @@ -0,0 +1,39 @@ +Version in karyon_p2p - Rust +

Struct karyon_p2p::Version

source ·
pub struct Version {
+    pub v: VersionInt,
+    pub req: VersionReq,
+}
Expand description

Represents the network version and protocol version used in karyon p2p.

+

Example

+
use karyon_p2p::Version;
+
+let version: Version = "0.2.0, >0.1.0".parse().unwrap();
+
+let version: Version = "0.2.0".parse().unwrap();
+
+

Fields§

§v: VersionInt§req: VersionReq

Implementations§

source§

impl Version

source

pub fn new(v: VersionInt, req: VersionReq) -> Self

Creates a new Version

+

Trait Implementations§

source§

impl Clone for Version

source§

fn clone(&self) -> Version

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Version

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromStr for Version

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Error>

Parses a string s to return a value of this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/tls_config/constant.BAD_ENCODING_ERR.html b/karyon_p2p/tls_config/constant.BAD_ENCODING_ERR.html new file mode 100644 index 00000000..30fbdd1b --- /dev/null +++ b/karyon_p2p/tls_config/constant.BAD_ENCODING_ERR.html @@ -0,0 +1,2 @@ +BAD_ENCODING_ERR in karyon_p2p::tls_config - Rust +
const BAD_ENCODING_ERR: Error;
\ No newline at end of file diff --git a/karyon_p2p/tls_config/constant.BAD_SIGNATURE_ERR.html b/karyon_p2p/tls_config/constant.BAD_SIGNATURE_ERR.html new file mode 100644 index 00000000..cf9f14ef --- /dev/null +++ b/karyon_p2p/tls_config/constant.BAD_SIGNATURE_ERR.html @@ -0,0 +1,2 @@ +BAD_SIGNATURE_ERR in karyon_p2p::tls_config - Rust +
const BAD_SIGNATURE_ERR: Error;
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.generate_cert.html b/karyon_p2p/tls_config/fn.generate_cert.html new file mode 100644 index 00000000..8799b93e --- /dev/null +++ b/karyon_p2p/tls_config/fn.generate_cert.html @@ -0,0 +1,5 @@ +generate_cert in karyon_p2p::tls_config - Rust +
fn generate_cert<'a>(
+    key_pair: &KeyPair
+) -> Result<(CertificateDer<'a>, PrivateKeyDer<'a>), Error>
Expand description

Generates a certificate and returns both the certificate and the private key.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.parse_cert.html b/karyon_p2p/tls_config/fn.parse_cert.html new file mode 100644 index 00000000..3bb37e43 --- /dev/null +++ b/karyon_p2p/tls_config/fn.parse_cert.html @@ -0,0 +1,5 @@ +parse_cert in karyon_p2p::tls_config - Rust +
fn parse_cert<'a>(
+    end_entity: &'a CertificateDer<'a>
+) -> Result<X509Certificate<'a>, Error>
Expand description

Parses the given x509 certificate.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.tls_client_config.html b/karyon_p2p/tls_config/fn.tls_client_config.html new file mode 100644 index 00000000..4c570b73 --- /dev/null +++ b/karyon_p2p/tls_config/fn.tls_client_config.html @@ -0,0 +1,6 @@ +tls_client_config in karyon_p2p::tls_config - Rust +
pub fn tls_client_config(
+    key_pair: &KeyPair,
+    peer_id: Option<PeerID>
+) -> Result<ClientConfig, Error>
Expand description

Returns a TLS client configuration.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.tls_server_config.html b/karyon_p2p/tls_config/fn.tls_server_config.html new file mode 100644 index 00000000..0cee6dfd --- /dev/null +++ b/karyon_p2p/tls_config/fn.tls_server_config.html @@ -0,0 +1,3 @@ +tls_server_config in karyon_p2p::tls_config - Rust +
pub fn tls_server_config(key_pair: &KeyPair) -> Result<ServerConfig, Error>
Expand description

Returns a TLS server configuration.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.verify_cert.html b/karyon_p2p/tls_config/fn.verify_cert.html new file mode 100644 index 00000000..2854221d --- /dev/null +++ b/karyon_p2p/tls_config/fn.verify_cert.html @@ -0,0 +1,3 @@ +verify_cert in karyon_p2p::tls_config - Rust +
fn verify_cert(end_entity: &CertificateDer<'_>) -> Result<PeerID, Error>
Expand description

Verifies the given certification.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/fn.verify_cert_signature.html b/karyon_p2p/tls_config/fn.verify_cert_signature.html new file mode 100644 index 00000000..081b1592 --- /dev/null +++ b/karyon_p2p/tls_config/fn.verify_cert_signature.html @@ -0,0 +1,7 @@ +verify_cert_signature in karyon_p2p::tls_config - Rust +
fn verify_cert_signature(
+    cert: &X509Certificate<'_>,
+    message: &[u8],
+    signature: &[u8]
+) -> Result<(), Error>
Expand description

Verifies the signature of the given certificate.

+
\ No newline at end of file diff --git a/karyon_p2p/tls_config/index.html b/karyon_p2p/tls_config/index.html new file mode 100644 index 00000000..ab19a243 --- /dev/null +++ b/karyon_p2p/tls_config/index.html @@ -0,0 +1,2 @@ +karyon_p2p::tls_config - Rust +

Module karyon_p2p::tls_config

source ·

Structs

Constants

Statics

Functions

\ No newline at end of file diff --git a/karyon_p2p/tls_config/sidebar-items.js b/karyon_p2p/tls_config/sidebar-items.js new file mode 100644 index 00000000..82b73482 --- /dev/null +++ b/karyon_p2p/tls_config/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"constant":["BAD_ENCODING_ERR","BAD_SIGNATURE_ERR"],"fn":["generate_cert","parse_cert","tls_client_config","tls_server_config","verify_cert","verify_cert_signature"],"static":["CIPHER_SUITES","KX_GROUPS","PROTOCOL_VERSIONS","SIGNATURE_SCHEMES"],"struct":["CliCertVerifier","SrvrCertVerifier"]}; \ No newline at end of file diff --git a/karyon_p2p/tls_config/static.CIPHER_SUITES.html b/karyon_p2p/tls_config/static.CIPHER_SUITES.html new file mode 100644 index 00000000..348b8e21 --- /dev/null +++ b/karyon_p2p/tls_config/static.CIPHER_SUITES.html @@ -0,0 +1,2 @@ +CIPHER_SUITES in karyon_p2p::tls_config - Rust +
static CIPHER_SUITES: &[SupportedCipherSuite]
\ No newline at end of file diff --git a/karyon_p2p/tls_config/static.KX_GROUPS.html b/karyon_p2p/tls_config/static.KX_GROUPS.html new file mode 100644 index 00000000..08ef3fee --- /dev/null +++ b/karyon_p2p/tls_config/static.KX_GROUPS.html @@ -0,0 +1,2 @@ +KX_GROUPS in karyon_p2p::tls_config - Rust +
static KX_GROUPS: &[&dyn SupportedKxGroup]
\ No newline at end of file diff --git a/karyon_p2p/tls_config/static.PROTOCOL_VERSIONS.html b/karyon_p2p/tls_config/static.PROTOCOL_VERSIONS.html new file mode 100644 index 00000000..9ad42b5b --- /dev/null +++ b/karyon_p2p/tls_config/static.PROTOCOL_VERSIONS.html @@ -0,0 +1,2 @@ +PROTOCOL_VERSIONS in karyon_p2p::tls_config - Rust +
static PROTOCOL_VERSIONS: &[&SupportedProtocolVersion]
\ No newline at end of file diff --git a/karyon_p2p/tls_config/static.SIGNATURE_SCHEMES.html b/karyon_p2p/tls_config/static.SIGNATURE_SCHEMES.html new file mode 100644 index 00000000..6d1d5f89 --- /dev/null +++ b/karyon_p2p/tls_config/static.SIGNATURE_SCHEMES.html @@ -0,0 +1,2 @@ +SIGNATURE_SCHEMES in karyon_p2p::tls_config - Rust +
static SIGNATURE_SCHEMES: &[SignatureScheme]
\ No newline at end of file diff --git a/karyon_p2p/tls_config/struct.CliCertVerifier.html b/karyon_p2p/tls_config/struct.CliCertVerifier.html new file mode 100644 index 00000000..f8ff3379 --- /dev/null +++ b/karyon_p2p/tls_config/struct.CliCertVerifier.html @@ -0,0 +1,48 @@ +CliCertVerifier in karyon_p2p::tls_config - Rust +
struct CliCertVerifier {}

Trait Implementations§

source§

impl ClientCertVerifier for CliCertVerifier

source§

fn verify_client_cert( + &self, + end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _now: UnixTime +) -> Result<ClientCertVerified, Error>

Verify the end-entity certificate end_entity is valid, acceptable, +and chains to at least one of the trust anchors trusted by +this verifier. Read more
source§

fn root_hint_subjects(&self) -> &[DistinguishedName]

Returns the [DistinguishedName] subjects that the server will hint to clients to +identify acceptable authentication trust anchors. Read more
source§

fn verify_tls12_signature( + &self, + _message: &[u8], + _cert: &CertificateDer<'_>, + _dss: &DigitallySignedStruct +) -> Result<HandshakeSignatureValid, Error>

Verify a signature allegedly by the given client certificate. Read more
source§

fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct +) -> Result<HandshakeSignatureValid, Error>

Verify a signature allegedly by the given client certificate. Read more
source§

fn supported_verify_schemes(&self) -> Vec<SignatureScheme>

Return the list of SignatureSchemes that this verifier will handle, +in verify_tls12_signature and verify_tls13_signature calls. Read more
§

fn offer_client_auth(&self) -> bool

Returns true to enable the server to request a client certificate and +false to skip requesting a client certificate. Defaults to true.
§

fn client_auth_mandatory(&self) -> bool

Return true to require a client certificate and false to make +client authentication optional. +Defaults to self.offer_client_auth().
source§

impl Debug for CliCertVerifier

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/tls_config/struct.SrvrCertVerifier.html b/karyon_p2p/tls_config/struct.SrvrCertVerifier.html new file mode 100644 index 00000000..b9a69e04 --- /dev/null +++ b/karyon_p2p/tls_config/struct.SrvrCertVerifier.html @@ -0,0 +1,47 @@ +SrvrCertVerifier in karyon_p2p::tls_config - Rust +
struct SrvrCertVerifier {
+    peer_id: Option<PeerID>,
+}

Fields§

§peer_id: Option<PeerID>

Trait Implementations§

source§

impl Debug for SrvrCertVerifier

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl ServerCertVerifier for SrvrCertVerifier

source§

fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime +) -> Result<ServerCertVerified, Error>

Verify the end-entity certificate end_entity is valid for the +hostname dns_name and chains to at least one trust anchor. Read more
source§

fn verify_tls12_signature( + &self, + _message: &[u8], + _cert: &CertificateDer<'_>, + _dss: &DigitallySignedStruct +) -> Result<HandshakeSignatureValid, Error>

Verify a signature allegedly by the given server certificate. Read more
source§

fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct +) -> Result<HandshakeSignatureValid, Error>

Verify a signature allegedly by the given server certificate. Read more
source§

fn supported_verify_schemes(&self) -> Vec<SignatureScheme>

Return the list of SignatureSchemes that this verifier will handle, +in verify_tls12_signature and verify_tls13_signature calls. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/type.ArcBackend.html b/karyon_p2p/type.ArcBackend.html new file mode 100644 index 00000000..7b86b727 --- /dev/null +++ b/karyon_p2p/type.ArcBackend.html @@ -0,0 +1,6 @@ +ArcBackend in karyon_p2p - Rust +

Type Alias karyon_p2p::ArcBackend

source ·
pub type ArcBackend = Arc<Backend>;

Aliased Type§

struct ArcBackend {
+    ptr: NonNull<ArcInner<Backend>>,
+    phantom: PhantomData<ArcInner<Backend>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Backend>>§phantom: PhantomData<ArcInner<Backend>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/type.ArcPeer.html b/karyon_p2p/type.ArcPeer.html new file mode 100644 index 00000000..17106213 --- /dev/null +++ b/karyon_p2p/type.ArcPeer.html @@ -0,0 +1,6 @@ +ArcPeer in karyon_p2p - Rust +

Type Alias karyon_p2p::ArcPeer

source ·
pub type ArcPeer = Arc<Peer>;

Aliased Type§

struct ArcPeer {
+    ptr: NonNull<ArcInner<Peer>>,
+    phantom: PhantomData<ArcInner<Peer>>,
+    alloc: Global,
+}

Fields§

§ptr: NonNull<ArcInner<Peer>>§phantom: PhantomData<ArcInner<Peer>>§alloc: Global
\ No newline at end of file diff --git a/karyon_p2p/version/fn.version_match.html b/karyon_p2p/version/fn.version_match.html new file mode 100644 index 00000000..bb8c8dae --- /dev/null +++ b/karyon_p2p/version/fn.version_match.html @@ -0,0 +1,3 @@ +version_match in karyon_p2p::version - Rust +
pub fn version_match(version_req: &VersionReq, version: &VersionInt) -> bool
Expand description

Check if a version satisfies a version request.

+
\ No newline at end of file diff --git a/karyon_p2p/version/index.html b/karyon_p2p/version/index.html new file mode 100644 index 00000000..16edaa52 --- /dev/null +++ b/karyon_p2p/version/index.html @@ -0,0 +1,2 @@ +karyon_p2p::version - Rust +

Module karyon_p2p::version

source ·

Structs

  • Represents the network version and protocol version used in karyon p2p.

Functions

\ No newline at end of file diff --git a/karyon_p2p/version/sidebar-items.js b/karyon_p2p/version/sidebar-items.js new file mode 100644 index 00000000..453db48b --- /dev/null +++ b/karyon_p2p/version/sidebar-items.js @@ -0,0 +1 @@ +window.SIDEBAR_ITEMS = {"fn":["version_match"],"struct":["Version","VersionInt"]}; \ No newline at end of file diff --git a/karyon_p2p/version/struct.Version.html b/karyon_p2p/version/struct.Version.html new file mode 100644 index 00000000..99a34e7f --- /dev/null +++ b/karyon_p2p/version/struct.Version.html @@ -0,0 +1,39 @@ +Version in karyon_p2p::version - Rust +

Struct karyon_p2p::version::Version

source ·
pub struct Version {
+    pub v: VersionInt,
+    pub req: VersionReq,
+}
Expand description

Represents the network version and protocol version used in karyon p2p.

+

Example

+
use karyon_p2p::Version;
+
+let version: Version = "0.2.0, >0.1.0".parse().unwrap();
+
+let version: Version = "0.2.0".parse().unwrap();
+
+

Fields§

§v: VersionInt§req: VersionReq

Implementations§

source§

impl Version

source

pub fn new(v: VersionInt, req: VersionReq) -> Self

Creates a new Version

+

Trait Implementations§

source§

impl Clone for Version

source§

fn clone(&self) -> Version

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Version

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromStr for Version

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Error>

Parses a string s to return a value of this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
\ No newline at end of file diff --git a/karyon_p2p/version/struct.VersionInt.html b/karyon_p2p/version/struct.VersionInt.html new file mode 100644 index 00000000..8f977398 --- /dev/null +++ b/karyon_p2p/version/struct.VersionInt.html @@ -0,0 +1,35 @@ +VersionInt in karyon_p2p::version - Rust +
pub struct VersionInt {
+    major: u64,
+    minor: u64,
+    patch: u64,
+}

Fields§

§major: u64§minor: u64§patch: u64

Trait Implementations§

source§

impl<'__de> BorrowDecode<'__de> for VersionInt

source§

fn borrow_decode<__D: BorrowDecoder<'__de>>( + decoder: &mut __D +) -> Result<Self, DecodeError>

Attempt to decode this type with the given BorrowDecode.
source§

impl Clone for VersionInt

source§

fn clone(&self) -> VersionInt

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for VersionInt

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decode for VersionInt

source§

fn decode<__D: Decoder>(decoder: &mut __D) -> Result<Self, DecodeError>

Attempt to decode this type with the given Decode.
source§

impl Display for VersionInt

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encode for VersionInt

source§

fn encode<__E: Encoder>(&self, encoder: &mut __E) -> Result<(), EncodeError>

Encode a given type.
source§

impl From<VersionInt> for Version

source§

fn from(v: VersionInt) -> Self

Converts to this type from the input type.
source§

impl FromStr for VersionInt

§

type Err = Error

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Error>

Parses a string s to return a value of this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where + T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where + T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where + T: 'a,

§

fn implicit( + self, + class: Class, + constructed: bool, + tag: u32 +) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where + T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where + T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> EventValueAny for T
where + T: Send + Sync + Debug + Any,

source§

fn value_as_any(&self) -> &(dyn Any + 'static)

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

+
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an +Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an +Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where + U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

+

That is, this conversion is whatever the implementation of +From<T> for U chooses to do.

+
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where + T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where + T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where + U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where + U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where + V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where + S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a +[WithDispatch] wrapper. Read more
source§

impl<T> CodecMsg for T
where + T: Encode + Decode + Debug,

\ No newline at end of file diff --git a/search-index.js b/search-index.js new file mode 100644 index 00000000..da024115 --- /dev/null +++ b/search-index.js @@ -0,0 +1,8 @@ +var searchIndex = new Map(JSON.parse('[\ +["karyon_core",{"doc":"","t":"IIOOCCCCOOOOCCFPPFFGPPFGCOCOCOOOOCHOOCOCHOFONNNNONNONONNNNFFFNNNNNNNONNNNNNOOONNNNNNNNNNNNNNNNNNNNNNNNOFNNNONNNNNNNNNNONGPPFNNNNNNNNOONNNNHNNNNNNNNNNPPFFGNNNNNNNNOONNNNNNNNNNNNNOOONNNNNNNNNNNNNNHPPPGGGFCPPPFFGKGGKFMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNMNNMNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNPPPPPPGPPPIPPNNNNNNNNNNNNNNNNNNNIFFIFKKKIRIOOONNNNNNNNNONNNONONNNNNMONNNONNNOOOONONNNNMNONNNNNNNNNOMNNNNIFFIONNNNNNONNNNNOOONOONNNNNNNNNNNCHCHHHCHHHHHHHH","n":["Executor","GlobalExecutor","alloc","alloc","async_util","crypto","error","event","phantom","phantom","ptr","ptr","pubsub","util","Backoff","Cancelled","Completed","CondVar","CondWait","Either","Left","Right","TaskGroup","TaskResult","backoff","base_delay","condvar","condvar","condwait","executor","inner","max_delay","retries","select","select","stop","stop_signal","task_group","tasks","timeout","timeout","w","Backoff","base_delay","borrow","borrow_mut","from","into","max_delay","new","reset","retries","sleep","stop","try_from","try_into","type_id","vzip","CondVar","CondVarAwait","Wakers","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","broadcast","condvar","default","delete","drop","from","from","from","guard","id","inner","into","into","into","into_future","new","new","new","poll","put","signal","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","vzip","vzip","vzip","wait","wake","wakers","CondWait","borrow","borrow_mut","broadcast","condvar","default","from","into","new","reset","signal","try_from","try_into","type_id","vzip","w","wait","Either","Left","Right","Select","borrow","borrow","borrow_mut","borrow_mut","fmt","fmt","from","from","future1","future2","into","into","into_future","poll","select","try_from","try_from","try_into","try_into","type_id","type_id","value_as_any","value_as_any","vzip","vzip","Cancelled","Completed","TaskGroup","TaskHandler","TaskResult","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","cancel","cancel","cancel_flag","executor","fmt","fmt","from","from","from","into","into","into","is_empty","len","new","new","spawn","stop_signal","task","tasks","to_string","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","value_as_any","vzip","vzip","vzip","timeout","Ed25519","Ed25519","Ed25519","KeyPair","KeyPairType","PublicKey","SecretKey","key_pair","Ed25519","Ed25519","Ed25519","Ed25519KeyPair","Ed25519PublicKey","KeyPair","KeyPairExt","KeyPairType","PublicKey","PublicKeyExt","SecretKey","as_bytes","as_bytes","as_bytes","borrow","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","fmt","fmt","from","from","from","from","from","from","from_bytes","from_bytes","generate","generate","into","into","into","into","into","into","public","public","public","secret","secret","secret","sign","sign","sign","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","value_as_any","value_as_any","verify","verify","verify","vzip","vzip","vzip","vzip","vzip","vzip","BincodeDecode","BincodeEncode","ChannelRecv","ChannelSend","Ed25519","Err","Error","IO","Ok","PathNotFound","Result","Timeout","TryInto","borrow","borrow_mut","fmt","fmt","from","from","from","from","from","from","from","into","source","to_string","try_from","try_into","type_id","value_as_any","vzip","ArcEventSys","Event","EventListener","EventListenerID","EventSys","EventValue","EventValueAny","EventValueTopic","Listeners","Topic","WeakEventSys","alloc","alloc","base","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","cancel","clone","clone_into","created_at","emit","emit_by_topic","event_id","event_id","event_sys","event_sys","fmt","fmt","from","from","from","id","id","into","into","into","listeners","new","new","new","phantom","phantom","ptr","ptr","recv","recv_chan","register","remove","to_owned","to_string","topic","topic","topic","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","value","value_as_any","value_as_any","vzip","vzip","vzip","ArcPublisher","Publisher","Subscription","SubscriptionID","alloc","borrow","borrow","borrow_mut","borrow_mut","from","from","id","into","into","new","new","notify","phantom","ptr","publisher","recv","recv_chan","subs","subscribe","try_from","try_from","try_into","try_into","type_id","type_id","unsubscribe","unsubscribe","vzip","vzip","decode","decode","encode","encode","encode_into_slice","home_dir","path","random_16","random_32","tilde_expand","decode","encode","encode_into_slice","home_dir","tilde_expand"],"q":[[0,"karyon_core"],[14,"karyon_core::async_util"],[42,"karyon_core::async_util::backoff"],[58,"karyon_core::async_util::condvar"],[103,"karyon_core::async_util::condwait"],[120,"karyon_core::async_util::select"],[149,"karyon_core::async_util::task_group"],[194,"karyon_core::async_util::timeout"],[195,"karyon_core::crypto"],[203,"karyon_core::crypto::key_pair"],[291,"karyon_core::error"],[323,"karyon_core::event"],[395,"karyon_core::pubsub"],[429,"karyon_core::util"],[439,"karyon_core::util::decode"],[440,"karyon_core::util::encode"],[442,"karyon_core::util::path"],[444,"core::future::future"],[445,"core::time"],[446,"core::result"],[447,"core::any"],[448,"core::task::wake"],[449,"core::option"],[450,"async_lock::mutex"],[451,"core::pin"],[452,"core::task::wake"],[453,"core::fmt"],[454,"core::fmt"],[455,"core::marker"],[456,"core::marker"],[457,"alloc::string"],[458,"alloc::vec"],[459,"std::io::error"],[460,"async_channel"],[461,"bincode::error"],[462,"signature::error"],[463,"bincode::error"],[464,"core::hash"],[465,"core::cmp"],[466,"core::clone"],[467,"async_channel"],[468,"bincode::enc"],[469,"std::path"]],"d":["A pointer to an Executor","A Global Executor","","","A module containing async utilities that work with the smol…","Collects common cryptographic tools","Represents karyon’s Core Error.","event::EventSys implementation.","","","","","A simple publish-subscribe system Read More","A set of helper tools and functions.","Exponential backoff …","","","CondVar is an async version of …","CondWait is a wrapper struct for CondVar with a Mutex …","The return value from the select function, indicating …","","","TaskGroup is a group of spawned tasks.","The result of a spawned task.","","The base delay in milliseconds for the initial retry.","","The CondVar","","","","The max delay in milliseconds allowed for a retry.","Atomic counter","","Returns the result of the future that completes first, …","Stop flag","","","","","Waits for a future to complete or times out if it exceeds …","Boolean flag","Exponential backoff …","The base delay in milliseconds for the initial retry.","","","Returns the argument unchanged.","Calls U::from(self).","The max delay in milliseconds allowed for a retry.","Creates a new Backoff.","Reset the retry counter to 0.","Atomic counter","Sleep based on the current retry count and delay values. …","Stop flag","","","","","CondVar is an async version of …","","Wakers is a helper struct to store the task wakers","","","","","","","Wakes up all blocked tasks waiting on this condvar.","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Creates a new CondVar","","","","","Wakes up one blocked task waiting on this condvar.","","","","","","","","","","","","","Blocks the current task until this condition variable …","","","CondWait is a wrapper struct for CondVar with a Mutex …","","","Signal all waiting tasks.","The CondVar","","Returns the argument unchanged.","Calls U::from(self).","Creates a new CondWait.","Reset the boolean flag value to false.","Signal a waiting task.","","","","","Boolean flag","Waits for a signal or broadcast.","The return value from the select function, indicating …","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","","","Returns the result of the future that completes first, …","","","","","","","","","","","","","TaskGroup is a group of spawned tasks.","TaskHandler","The result of a spawned task.","","","","","","","Cancels all tasks in the group.","Cancels the task.","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Checks if the task group is empty.","Get the number of the tasks in the group.","Creates a new task group","Creates a new task handle","Spawns a new task and calls the callback after it has …","","","","","","","","","","","","","","","","","","Waits for a future to complete or times out if it exceeds …","","","","","key cryptography type","","A Secret key","","","","","","","","An extension trait, adding essential methods to all KeyPair…","key cryptography type","","An extension trait, adding essential methods to all …","A Secret key","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Generate a new random keypair.","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Get the public key of this keypair.","Get the public key of this keypair.","","Get the secret key of this keypair.","Get the secret key of this keypair.","","Sign a message using the private key.","Sign a message using the private key.","","","","","","","","","","","","","","","","","","","","","","","","Verify a signature on a message with this public key.","Verify a signature on a message with this public key.","","","","","","","","","","","","","Contains the error value","","","Contains the success value","","","","","","","","","","Returns the argument unchanged.","","","","","","Calls U::from(self).","","","","","","","","","An event within the EventSys.","EventListener listens for and receives events from the …","","EventSys supports event emission to registered listeners …","","","","","","","","","","","","","","","","Cancels the listener and removes it from the EventSys.","","","The time at which the event was created.","Emits an event to the listeners.","Emits an event to the listeners.","Returns the event id for this event listener.","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Creates a new EventSys","Create a new event listener.","Creates a new Event.","","","","","Receive the next event.","","Registers a new event listener for the given topic.","Removes the event listener attached to the given topic.","","","","Returns the topic for this event listener.","","","","","","","","","","","The value of the Event.","","","","","","","A simple publish-subscribe system.","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","Creates a new Publisher","Creates a new Subscription","Notify all subscribers","","","","Receive a message from the Publisher","","","Subscribe and return a Subscription","","","","","","","Unsubscribe from the Publisher","Unsubscribe from the Publisher","","","","Decodes a given type T from the given slice. returns the …","","Encode the given type T into a Vec<u8>.","Encode the given type T into the given slice..","Returns the user’s home directory as a PathBuf.","","Generates and returns a random u16 using rand::rngs::OsRng.","Generates and returns a random u32 using rand::rngs::OsRng.","Expands a tilde (~) in a path and returns the expanded …","Decodes a given type T from the given slice. returns the …","Encode the given type T into a Vec<u8>.","Encode the given type T into the given slice..","Returns the user’s home directory as a PathBuf.","Expands a tilde (~) in a path and returns the expanded …"],"i":[0,0,32,80,0,0,0,0,32,80,32,80,0,0,0,30,30,0,0,0,26,26,0,0,0,7,0,22,0,28,11,7,7,0,0,7,28,0,28,0,0,22,0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,0,0,0,11,16,12,11,16,12,11,16,11,12,16,11,16,12,16,16,11,11,16,12,16,11,16,12,16,12,11,11,16,12,11,16,12,11,16,12,11,16,12,11,12,12,0,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,0,26,26,0,1,26,1,26,1,26,1,26,1,1,1,26,1,1,0,1,26,1,26,1,26,1,26,1,26,30,30,0,0,0,28,29,30,28,29,30,28,29,29,28,30,30,28,29,30,28,29,30,28,28,28,29,28,28,29,28,30,28,29,30,28,29,30,28,29,30,30,28,29,30,0,45,43,41,0,0,0,0,0,45,43,41,0,0,0,0,0,0,0,0,38,41,42,45,47,43,44,41,42,45,47,43,44,41,42,43,44,43,44,41,42,45,47,43,44,41,42,41,42,43,44,45,47,43,44,41,42,46,43,44,46,43,44,46,43,44,43,44,45,47,43,44,41,42,45,47,43,44,41,42,45,47,43,44,41,42,41,42,38,41,42,45,47,43,44,41,42,49,49,49,49,49,5,0,49,5,49,0,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,0,0,0,0,0,0,0,0,0,66,0,67,70,81,64,57,63,64,57,63,57,63,63,63,64,64,57,57,57,57,63,63,64,57,63,62,57,64,57,63,64,64,57,63,67,57,67,70,57,57,64,64,63,63,66,57,57,64,57,63,64,57,63,64,57,63,63,61,63,64,57,63,0,0,0,0,72,75,74,75,74,75,74,74,75,74,75,74,75,72,72,74,74,74,75,75,75,74,75,74,75,74,75,74,75,74,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[-2,-4],[[1,[-2,-4]]],[],[[3,[],[[2,[-1]]]]],[],[[3,[],[[2,[-3]]]]]],0,0,0,0,0,[[4,-2],[[5,[-1]]],[],[[3,[],[[2,[-1]]]]]],0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-1,[]],[-1,-2,[],[]],0,[[6,6],7],[7,8],0,[7,6],0,[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,-2,[],[]],0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[11,8],0,[[],11],[[12,13],[[15,[[15,[14]]]]]],[[[16,[-1]]],8,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[],[]],[[],11],[[11,[17,[-1]]],[[16,[-1]]],[]],[[],12],[[[18,[[16,[-1]]]],19],[[20,[-2]]],[],[]],[[12,[15,[14]]],13],[11,8],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[11,[17,[-1]]],[[17,[-1]]],[]],[[12,21],8],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[22,8],0,[[],22],[-1,-1,[]],[-1,-2,[],[]],[[],22],[22,8],[22,8],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,-2,[],[]],0,[22,8],0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[[1,[-1,-2]],23],24,25,25],[[[26,[-1,-2]],23],24,25,25],[-1,-1,[]],[-1,-1,[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,[],[]],[[[18,[[1,[-2,-4]]]],19],[[20,[-5]]],[],[[3,[],[[2,[-1]]]]],[],[[3,[],[[2,[-3]]]]],[]],[[-2,-4],[[1,[-2,-4]]],[],[[3,[],[[2,[-1]]]]],[],[[3,[],[[2,[-3]]]]]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[-1,27,[]],[-1,27,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[28,8],[29,8],0,0,[[[30,[-1]],23],24,25],[[[30,[-1]],23],24,25],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[28,21],[28,31],[32,28],[[32,-2,-4,[33,[22]]],29,[34,35],[[3,[],[[2,[-1]]]],34],[[3,[],[[2,[8]]]],34],[[36,[[30,[-1]]],[[2,[-3]]]],34]],[[28,-2,-4],8,[34,35],[[3,[],[[2,[-1]]]],34],[[3,[],[[2,[8]]]],34],[[36,[[30,[-1]]],[[2,[-3]]]],34]],0,0,0,[-1,37,[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,27,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[4,-2],[[5,[-1]]],[],[[3,[],[[2,[-1]]]]]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[38,[[40,[39]]]],[41,[[40,[39]]]],[42,[[40,[39]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[43,43],[44,44],[[-1,-2],8,[],[]],[[-1,-2],8,[],[]],[[41,23],24],[[42,23],24],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[[45,[40,[39]]],[[5,[41]]]],[[[40,[39]]],[[5,[42]]]],[45,43],[[],44],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[46,41],[43,41],[44,41],[46,47],[43,47],[44,47],[[46,[40,[39]]],[[48,[39]]]],[[43,[40,[39]]],[[48,[39]]]],[[44,[40,[39]]],[[48,[39]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],[-1,27,[]],[-1,27,[]],[[38,[40,[39]],[40,[39]]],[[5,[8]]]],[[41,[40,[39]],[40,[39]]],[[5,[8]]]],[[42,[40,[39]],[40,[39]]],[[5,[8]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[49,23],24],[[49,23],24],[50,49],[-1,-1,[]],[[[51,[-1]]],49,[]],[52,49],[53,49],[54,49],[55,49],[-1,-2,[],[]],[49,[[15,[56]]]],[-1,37,[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,27,[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[[57,[-1,-2]]],8,[58,59,60,25],[61,60,62]],[63,63],[[-1,-2],8,[],[]],0,[[[64,[-1]],-2],8,[58,59,25,60],[[66,[],[[65,[-1]]]],60]],[[[64,[-1]],-1,-2],8,[58,59,25,60],[61,62,60]],[[[57,[-1,-2]]],37,[58,59,60,25],[61,60,62]],0,[[[57,[-1,-2]]],[[67,[-1]]],[58,59,60,25],[61,60,62]],0,[[63,23],24],[[63,23],24],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[[],68],0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,[[],[[67,[-1]]],[58,59,25,60]],[[69,[70,[-1]],[71,[63]],68,-1],[[57,[-1,-2]]],[58,59,60,25],[61,60,62]],[[[33,[61]]],63],0,0,0,0,[[[57,[-1,-2]]],[[5,[-2]]],[58,59,60,25],[61,60,62]],0,[[[33,[[64,[-1]]]],-1],[[57,[-1,-2]]],[58,59,25,60],[61,62,60]],[[[64,[-1]],-1,68,69],8,[58,59,25,60]],[-1,-2,[],[]],[-1,37,[]],[[],-1,[]],[[[57,[-1,-2]]],-1,[58,59,60,25],[61,60,62]],0,[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[-1,10,[]],0,[61,27],[-1,27,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-1,[]],[-1,-1,[]],0,[-1,-2,[],[]],[-1,-2,[],[]],[[],[[72,[-1]]],60],[[73,[72,[-1]],[71,[-1]]],[[74,[-1]]],60],[[[33,[[75,[-1]]]],-1],8,60],0,0,0,[[[74,[-1]]],[[5,[-1]]],60],0,0,[[[33,[[75,[-1]]]]],[[74,[-1]]],60],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,[[9,[-2]]],[],[]],[-1,10,[]],[-1,10,[]],[[[33,[[75,[-1]]]],73],8,60],[[[74,[-1]]],8,60],[-1,-2,[],[]],[-1,-2,[],[]],0,[[[40,[39]]],[[5,[[8,[-1,31]]]]],76],0,[-1,[[5,[[48,[39]]]]],77],[[-1,[40,[39]]],[[5,[8]]],77],[[],[[5,[78]]]],0,[[],13],[[],79],[68,[[5,[78]]]],[[[40,[39]]],[[5,[[8,[-1,31]]]]],76],[-1,[[5,[[48,[39]]]]],77],[[-1,[40,[39]]],[[5,[8]]],77],[[],[[5,[78]]]],[68,[[5,[78]]]]],"c":[],"p":[[5,"Select",120],[17,"Output"],[10,"Future",444],[5,"Duration",445],[8,"Result",291],[1,"u64"],[5,"Backoff",42],[1,"tuple"],[6,"Result",446],[5,"TypeId",447],[5,"CondVar",58],[5,"Wakers",58],[1,"u16"],[5,"Waker",448],[6,"Option",449],[5,"CondVarAwait",58],[5,"MutexGuard",450],[5,"Pin",451],[5,"Context",448],[6,"Poll",452],[1,"bool"],[5,"CondWait",103],[5,"Formatter",453],[8,"Result",453],[10,"Debug",453],[6,"Either",120],[10,"Any",447],[5,"TaskGroup",149],[5,"TaskHandler",149],[6,"TaskResult",149],[1,"usize"],[8,"Executor",0],[5,"Arc",454],[10,"Send",455],[10,"Sync",455],[10,"FnOnce",456],[5,"String",457],[10,"PublicKeyExt",203],[1,"u8"],[1,"slice"],[6,"PublicKey",203],[5,"Ed25519PublicKey",203],[6,"KeyPair",203],[5,"Ed25519KeyPair",203],[6,"KeyPairType",203],[10,"KeyPairExt",203],[5,"SecretKey",203],[5,"Vec",458],[6,"Error",291],[5,"Error",459],[5,"SendError",460],[6,"EncodeError",461],[5,"Error",462],[6,"DecodeError",461],[5,"RecvError",460],[10,"Error",463],[5,"EventListener",323],[10,"Hash",464],[10,"Eq",465],[10,"Clone",466],[10,"EventValueAny",323],[10,"EventValue",323],[5,"Event",323],[5,"EventSys",323],[17,"Topic"],[10,"EventValueTopic",323],[8,"ArcEventSys",323],[1,"str"],[8,"EventListenerID",323],[8,"WeakEventSys",323],[5,"Receiver",460],[8,"ArcPublisher",395],[8,"SubscriptionID",395],[5,"Subscription",395],[5,"Publisher",395],[10,"Decode",467],[10,"Encode",468],[5,"PathBuf",469],[1,"u32"],[8,"GlobalExecutor",0],[8,"Listeners",323]],"b":[[164,"impl-Display-for-TaskResult%3CT%3E"],[165,"impl-Debug-for-TaskResult%3CT%3E"],[306,"impl-Display-for-Error"],[307,"impl-Debug-for-Error"],[308,"impl-From%3CError%3E-for-Error"],[310,"impl-From%3CSendError%3CT%3E%3E-for-Error"],[311,"impl-From%3CEncodeError%3E-for-Error"],[312,"impl-From%3CError%3E-for-Error"],[313,"impl-From%3CDecodeError%3E-for-Error"],[314,"impl-From%3CRecvError%3E-for-Error"],[353,"impl-Debug-for-Event"],[354,"impl-Display-for-Event"]]}],\ +["karyon_jsonrpc",{"doc":"A fast and lightweight async implementation of JSON-RPC 2.0…","t":"PFFFGPPPPSGPPPIPKFFPPPPPNNNCNNCOOOOONCNNNNMNNOOCMNNNNNNQCCOOONNNNNNNFFNNNNNOONNNNNNONNNNNNNNFFSSNNNNNNOONONNNNONNNNNNNNNNNNNPPGPPPPPPPPPINNNNNNNNNNNNNNNNNFSSSSFSFFNNNNNNNNOONNNNONNNNNNNNNNNNOONNNNOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNSSSSFFNNNNNOONNNNNNNONNHONNONNNNNNNNIIKMM","n":["CallError","Client","ClientConfig","CodecConfig","Endpoint","IO","InvalidMsg","InvalidParams","InvalidRequest","JSONRPC_VERSION","JsonRPCError","KaryonCore","KaryonNet","ParseJSON","RPCMethod","RPCMethodError","RPCService","Server","ServerConfig","Tcp","Tls","Udp","Unix","Ws","addr","borrow","borrow_mut","client","clone","clone_into","codec","codec","codec_config","config","config","default_buffer_size","eq","error","fmt","fmt","from","from_str","get_method","hash","into","listener","max_allowed_buffer_size","message","name","new_tcp_addr","new_tls_addr","new_udp_addr","new_unix_addr","new_ws_addr","port","register_service","server","service","services","task_group","timeout","to_owned","to_string","try_from","try_into","type_id","value_as_any","vzip","Client","ClientConfig","borrow","borrow","borrow_mut","borrow_mut","call","codec","config","default","from","from","into","into","new","timeout","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip","Codec","CodecConfig","DEFAULT_BUFFER_SIZE","DEFAULT_MAX_ALLOWED_BUFFER_SIZE","borrow","borrow","borrow_mut","borrow_mut","clone","clone_into","config","conn","default","default_buffer_size","from","from","into","into","max_allowed_buffer_size","new","read_until","read_until_with_timeout","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip","write_all","CallError","Err","Error","IO","InvalidMsg","InvalidParams","InvalidRequest","KaryonCore","KaryonNet","Ok","ParseJSON","RPCMethodError","Result","borrow","borrow_mut","fmt","fmt","from","from","from","from","from","into","source","to_string","try_from","try_into","type_id","value_as_any","vzip","Error","INTERNAL_ERROR_CODE","INVALID_PARAMS_ERROR_CODE","INVALID_REQUEST_ERROR_CODE","METHOD_NOT_FOUND_ERROR_CODE","Notification","PARSE_ERROR_CODE","Request","Response","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","code","data","deserialize","deserialize","deserialize","deserialize","error","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","id","id","into","into","into","into","jsonrpc","jsonrpc","jsonrpc","message","method","method","params","params","result","serialize","serialize","serialize","serialize","to_string","to_string","to_string","to_string","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","value_as_any","value_as_any","value_as_any","value_as_any","vzip","vzip","vzip","vzip","FAILED_TO_PARSE_ERROR_MSG","INTERNAL_ERROR_MSG","INVALID_REQUEST_ERROR_MSG","METHOD_NOT_FOUND_ERROR_MSG","Server","ServerConfig","attach_service","borrow","borrow","borrow_mut","borrow_mut","codec_config","config","default","from","from","handle_conn","handle_request","into","into","listener","local_endpoint","new","pack_err_res","services","shutdown","start","task_group","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip","RPCMethod","RPCMethodOutput","RPCService","get_method","name"],"q":[[0,"karyon_jsonrpc"],[68,"karyon_jsonrpc::client"],[92,"karyon_jsonrpc::codec"],[124,"karyon_jsonrpc::error"],[154,"karyon_jsonrpc::message"],[233,"karyon_jsonrpc::server"],[269,"karyon_jsonrpc::service"],[274,"karyon_net::endpoint"],[275,"karyon_net::error"],[276,"core::result"],[277,"core::fmt"],[278,"core::fmt"],[279,"core::hash"],[280,"alloc::string"],[281,"core::net::socket_addr"],[282,"std::os::unix::net::addr"],[283,"core::any"],[284,"core::any"],[285,"serde::de"],[286,"karyon_net::connection"],[287,"karyon_net::connection"],[288,"core::fmt"],[289,"karyon_core::error"],[290,"std::io::error"],[291,"core::error"],[292,"serde::de"],[293,"karyon_core"],[294,"karyon_net::listener"],[295,"serde_json::value"]],"d":["","Represents an RPC client","Represents client config","Represents Codec config","Endpoint defines generic network endpoints for karyon.","","","","","","Represents karyon’s jsonrpc Error.","","","","Represents the RPC method","","Defines the interface for an RPC service.","Represents an RPC server","RPC server config","","","","","","Returns the Addr of the endpoint.","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","","Calls U::from(self).","","The maximum allowed buffer size to receive a message. If …","","","Creates a new TCP endpoint from a SocketAddr.","Creates a new TLS endpoint from a SocketAddr.","Creates a new UDP endpoint from a SocketAddr.","Creates a new Unix endpoint from a UnixSocketAddress.","Creates a new WS endpoint from a SocketAddr.","Returns the Port of the endpoint.","Implements the RPCService trait for a provided type.","","","","","","","","","","","","","Represents an RPC client","Represents client config","","","","","Calls the provided method, waits for the response, and …","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Creates a new RPC client by passing a Tcp, Unix, or Tls …","","","","","","","","","","","Represents Codec config","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","The maximum allowed buffer size to receive a message. If …","Creates a new Codec","Read all bytes into buffer until the 0x0A byte or EOF is …","","","","","","","","","","","Writes an entire buffer into the given connection.","","Contains the error value","Represents karyon’s jsonrpc Error.","","","","","","","Contains the success value","","","","","","","","Returns the argument unchanged.","","","","","Calls U::from(self).","","","","","","","","","Internal error: Internal JSON-RPC error.","Invalid params: Invalid method parameter(s).","Invalid request: The JSON sent is not a valid Request …","Method not found: The method does not exist / is not …","","Parse error: Invalid JSON was received by the server.","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Represents an RPC server","RPC server config","Attach a new service to the RPC server","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Handles a new connection","Handles a request","Calls U::from(self).","Calls U::from(self).","","Returns the local endpoint.","Creates a new RPC server by passing a listener. It …","","","Shuts down the RPC server","Starts the RPC server","","","","","","","","","","Represents the RPC method","","Defines the interface for an RPC service.","",""],"i":[21,0,0,0,0,21,21,21,21,0,0,21,21,21,0,21,0,0,0,1,1,1,1,1,1,1,1,0,1,1,0,20,46,20,45,26,1,0,1,1,1,1,10,1,1,45,26,0,10,1,1,1,1,1,1,0,0,0,45,45,24,1,1,1,1,1,1,1,0,0,20,24,20,24,20,20,20,24,20,24,20,24,20,24,20,24,20,24,20,24,20,24,0,0,0,0,28,26,28,26,26,26,28,28,26,26,28,26,28,26,26,28,28,28,26,28,26,28,26,28,26,28,26,28,21,52,0,21,21,21,21,21,21,52,21,21,0,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,0,0,0,0,0,0,0,0,0,39,41,42,43,39,41,42,43,42,42,39,41,42,43,41,39,39,41,41,42,42,43,43,39,41,42,43,39,41,39,41,42,43,39,41,43,42,39,43,39,43,41,39,41,42,43,39,41,42,43,39,41,42,43,39,41,42,43,39,41,42,43,39,41,42,43,39,41,42,43,0,0,0,0,0,0,45,45,46,45,46,46,45,46,45,46,45,45,45,46,45,45,45,0,45,45,45,45,45,46,45,46,45,46,45,46,0,0,0,10,10],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1,[[4,[2,3]]]],[-1,-2,[],[]],[-1,-2,[],[]],0,[1,1],[[-1,-2],5,[],[]],0,0,0,0,0,0,[[1,1],6],0,[[1,7],[[4,[5,8]]]],[[1,7],[[4,[5,8]]]],[-1,-1,[]],[9,[[4,[1]]]],[[10,9],[[12,[11]]]],[[1,-1],5,13],[-1,-2,[],[]],0,0,0,[10,14],[15,1],[15,1],[15,1],[16,1],[15,1],[1,[[4,[17,3]]]],0,0,0,0,0,0,[-1,-2,[],[]],[-1,14,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,19,[]],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[20,9,-1],[[4,[-2,21]]],[22,23],23],0,0,[[],24],[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],[[-1,24],20,25],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,18,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[26,26],[[-1,-2],5,[],[]],0,0,[[],26],0,[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,[[27,26],28],[[28,[30,[29]]],[[4,[31,21]]]],[[28,[30,[29]],32],[[4,[31,21]]]],[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,18,[]],[-1,-2,[],[]],[-1,-2,[],[]],[[28,[33,[29]]],[[4,[5,21]]]],0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[21,7],34],[[21,7],34],[-1,-1,[]],[3,21],[35,21],[36,21],[37,21],[-1,-2,[],[]],[21,[[12,[38]]]],[-1,14,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,19,[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,[-1,[[4,[39]]],40],[-1,[[4,[41]]],40],[-1,[[4,[42]]],40],[-1,[[4,[43]]],40],0,[[39,7],34],[[39,7],34],[[41,7],34],[[41,7],34],[[42,7],34],[[42,7],34],[[43,7],34],[[43,7],34],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,[[39,-1],4,44],[[41,-1],4,44],[[42,-1],4,44],[[43,-1],4,44],[-1,14,[]],[-1,14,[]],[-1,14,[]],[-1,14,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,18,[]],[-1,18,[]],[-1,18,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,[[45,-1],5,10],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,[[],46],[-1,-1,[]],[-1,-1,[]],[[[47,[45]],27],[[4,[5,21]]]],[[45,[33,[29]]],41],[-1,-2,[],[]],[-1,-2,[],[]],0,[45,[[4,[1,21]]]],[[-1,46,48],[[47,[45]]],49],[[50,9,[12,[51]]],41],0,[45,5],[[[47,[45]]],[[4,[5,21]]]],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,18,[]],[-1,18,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,[[10,9],[[12,[11]]]],[10,14]],"c":[],"p":[[6,"Endpoint",0],[6,"Addr",274],[6,"Error",275],[6,"Result",276],[1,"tuple"],[1,"bool"],[5,"Formatter",277],[5,"Error",277],[1,"str"],[10,"RPCService",269],[8,"RPCMethod",269],[6,"Option",278],[10,"Hasher",279],[5,"String",280],[6,"SocketAddr",281],[5,"SocketAddr",282],[1,"u16"],[5,"TypeId",283],[10,"Any",283],[5,"Client",68],[6,"Error",124],[10,"Serialize",284],[10,"DeserializeOwned",285],[5,"ClientConfig",68],[10,"ToConn",286],[5,"CodecConfig",92],[8,"Conn",286],[5,"Codec",92],[1,"u8"],[5,"Vec",287],[1,"usize"],[1,"u64"],[1,"slice"],[8,"Result",277],[5,"Error",288],[6,"Error",289],[5,"Error",290],[10,"Error",291],[5,"Request",154],[10,"Deserializer",285],[5,"Response",154],[5,"Error",154],[5,"Notification",154],[10,"Serializer",284],[5,"Server",233],[5,"ServerConfig",233],[5,"Arc",292],[8,"Executor",293],[10,"ToListener",294],[1,"i32"],[6,"Value",295],[8,"Result",124]],"b":[[38,"impl-Display-for-Endpoint"],[39,"impl-Debug-for-Endpoint"],[139,"impl-Debug-for-Error"],[140,"impl-Display-for-Error"],[142,"impl-From%3CNetError%3E-for-Error"],[143,"impl-From%3CError%3E-for-Error"],[144,"impl-From%3CError%3E-for-Error"],[145,"impl-From%3CError%3E-for-Error"],[178,"impl-Debug-for-Request"],[179,"impl-Display-for-Request"],[180,"impl-Display-for-Response"],[181,"impl-Debug-for-Response"],[182,"impl-Display-for-Error"],[183,"impl-Debug-for-Error"],[184,"impl-Debug-for-Notification"],[185,"impl-Display-for-Notification"]]}],\ +["karyon_net",{"doc":"","t":"GPPIKKPGPPPPPPPIGIPPIPPFPPKKPPFPFPMCHHHHCCOOOHHHHCMMMMOOCMMCMOOIKKHMMMMMGPGPIPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNPPPGPPPPPPPIPPPNNNNNNNNNNNNNNNNNNNKIKMHMMFFOHHOHOOOCCCCFNNHNONHNNNNONNNNNNOFFNONNNNHHNNONNHONNNNNONNNNNNNNNNNOFNNHNONHNNNNNNNNNNNNFNNHNONHNNNNONNNNNNO","n":["Addr","ChannelRecv","ChannelSend","Conn","ConnListener","Connection","Domain","Endpoint","Err","IO","InvalidAddress","InvalidDnsNameError","InvalidEndpoint","Ip","KaryonCore","Listener","NetError","NetResult","Ok","ParseEndpoint","Port","Rustls","Tcp","TcpConn","Timeout","Tls","ToConn","ToListener","TryFromEndpoint","Udp","UdpConn","Unix","UnixConn","Ws","accept","connection","dial","dial_tcp","dial_udp","dial_unix","endpoint","error","inner","inner","inner","listen","listen_tcp","listen_udp","listen_unix","listener","local_endpoint","local_endpoint","peer_endpoint","read","read","read","tls","to_conn","to_listener","transports","write","write","write","Conn","Connection","ToConn","dial","local_endpoint","peer_endpoint","read","to_conn","write","Addr","Domain","Endpoint","Ip","Port","Tcp","Tls","Udp","Unix","Ws","addr","borrow","borrow","borrow_decode","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","decode","encode","eq","eq","fmt","fmt","fmt","fmt","from","from","from_str","hash","hash","into","into","new_tcp_addr","new_tls_addr","new_udp_addr","new_unix_addr","new_ws_addr","port","to_owned","to_owned","to_string","to_string","try_from","try_from","try_into","try_into","type_id","type_id","value_as_any","value_as_any","vzip","vzip","ChannelRecv","ChannelSend","Err","Error","IO","InvalidAddress","InvalidDnsNameError","InvalidEndpoint","KaryonCore","Ok","ParseEndpoint","Result","Rustls","Timeout","TryFromEndpoint","borrow","borrow_mut","fmt","fmt","from","from","from","from","from","from","from","into","source","to_string","try_from","try_into","type_id","value_as_any","vzip","ConnListener","Listener","ToListener","accept","listen","local_endpoint","to_listener","TlsConn","TlsListener","acceptor","dial","dial_tls","inner","listen_tls","listener","read","write","tcp","tls","udp","unix","TcpConn","borrow","borrow_mut","dial_tcp","from","inner","into","listen_tcp","local_endpoint","new","peer_endpoint","read","read","to_conn","try_from","try_into","type_id","vzip","write","write","TlsConn","TlsListener","accept","acceptor","borrow","borrow","borrow_mut","borrow_mut","dial","dial_tls","from","from","inner","into","into","listen_tls","listener","local_endpoint","local_endpoint","new","peer_endpoint","read","read","to_conn","to_listener","try_from","try_from","try_into","try_into","type_id","type_id","vzip","vzip","write","write","UdpConn","borrow","borrow_mut","dial_udp","from","inner","into","listen_udp","local_endpoint","new","peer_endpoint","read","recv_from","send_to","to_conn","try_from","try_into","type_id","vzip","write","UnixConn","borrow","borrow_mut","dial_unix","from","inner","into","listen_unix","local_endpoint","new","peer_endpoint","read","read","to_conn","try_from","try_into","type_id","vzip","write","write"],"q":[[0,"karyon_net"],[63,"karyon_net::connection"],[72,"karyon_net::endpoint"],[127,"karyon_net::error"],[161,"karyon_net::listener"],[168,"karyon_net::tls"],[178,"karyon_net::transports"],[182,"karyon_net::transports::tcp"],[202,"karyon_net::transports::tls"],[237,"karyon_net::transports::udp"],[257,"karyon_net::transports::unix"],[277,"core::future::future"],[278,"alloc::boxed"],[279,"core::pin"],[280,"alloc::string"],[281,"async_net::tcp"],[282,"async_net::unix"],[283,"bincode::error"],[284,"core::result"],[285,"bincode::de"],[286,"bincode::de"],[287,"core::fmt"],[288,"core::fmt"],[289,"core::net::socket_addr"],[290,"std::os::unix::net::addr"],[291,"core::any"],[292,"core::any"],[293,"std::io::error"],[294,"async_channel"],[295,"async_channel"],[296,"rustls_pki_types::server_name"],[297,"core::error"],[298,"core::option"],[299,"rustls::client::client_conn"],[300,"rustls::server::server_conn"],[301,"async_net::tcp"],[302,"async_net::udp"],[303,"async_net::unix"]],"d":["Addr defines a type for an address, either IP or domain.","","","Alias for Box<dyn Connection>","ConnListener is a generic network listener.","Connection is a generic network connection interface for …","","Endpoint defines generic network endpoints for karyon.","Contains the error value","","","","","","","Alias for Box<dyn ConnListener>","Represents karyon’s Net Error","Represents karyon’s Net Result","Contains the success value","","Port defined as a u16.","","","TCP network connection implementation of the Connection …","","","A trait for objects which can be converted to Conn.","A trait for objects which can be converted to Listener.","","","UDP network connection implementation of the Connection …","","Unix domain socket implementation of the Connection trait.","","","","Connects to the provided endpoint.","Connects to the given TCP address and port.","Connects to the given UDP address and port.","Connects to the given Unix socket path.","","","","","","Listens to the provided endpoint.","Listens on the given TCP address and port.","Listens on the given UDP address and port.","Listens on the given Unix socket path.","","Returns the local socket endpoint of this connection","","Returns the remote peer endpoint of this connection","Reads data from this connection. ","","","","","","","Writes data to this connection","","","Alias for Box<dyn Connection>","Connection is a generic network connection interface for …","A trait for objects which can be converted to Conn.","Connects to the provided endpoint.","Returns the local socket endpoint of this connection","Returns the remote peer endpoint of this connection","Reads data from this connection. ","","Writes data to this connection","Addr defines a type for an address, either IP or domain.","","Endpoint defines generic network endpoints for karyon.","","Port defined as a u16.","","","","","","Returns the Addr of the endpoint.","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","","Calls U::from(self).","Calls U::from(self).","Creates a new TCP endpoint from a SocketAddr.","Creates a new TLS endpoint from a SocketAddr.","Creates a new UDP endpoint from a SocketAddr.","Creates a new Unix endpoint from a UnixSocketAddress.","Creates a new WS endpoint from a SocketAddr.","Returns the Port of the endpoint.","","","","","","","","","","","","","","","","","Contains the error value","","","","","","","Contains the success value","","","","","","","","","","","","","","","Returns the argument unchanged.","","Calls U::from(self).","","","","","","","","ConnListener is a generic network listener.","Alias for Box<dyn ConnListener>","A trait for objects which can be converted to Listener.","","Listens to the provided endpoint.","","","TLS network connection implementation of the Connection …","Tls network listener implementation of the Listener …","","Connects to the given TLS endpoint, returns Conn (…","Connects to the given TLS address and port.","","Listens on the given TLS address and port.","","","","","","","","TCP network connection implementation of the Connection …","","","Connects to the given TCP address and port.","Returns the argument unchanged.","","Calls U::from(self).","Listens on the given TCP address and port.","","Creates a new TcpConn","","","","","","","","","","","TLS network connection implementation of the Connection …","Tls network listener implementation of the Listener …","","","","","","","Connects to the given TLS endpoint, returns Conn (…","Connects to the given TLS address and port.","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","Listens on the given TLS address and port.","","","","Creates a new TlsConn","","","","","","","","","","","","","","","","UDP network connection implementation of the Connection …","","","Connects to the given UDP address and port.","Returns the argument unchanged.","","Calls U::from(self).","Listens on the given UDP address and port.","","Creates a new UdpConn","","","Receives a single datagram message. Returns the number of …","Sends data to the given address. Returns the number of …","","","","","","","Unix domain socket implementation of the Connection trait.","","","Connects to the given Unix socket path.","Returns the argument unchanged.","","Calls U::from(self).","Listens on the given Unix socket path.","","Creates a new UnixConn","","","","","","","","","",""],"i":[0,38,38,0,0,0,20,0,7,38,38,38,38,20,38,0,0,0,7,38,0,38,5,0,38,5,0,0,38,5,0,5,0,5,1,0,0,0,0,0,0,0,8,9,11,0,0,0,0,0,14,1,14,14,8,11,0,17,18,0,14,8,11,0,0,0,0,14,14,14,17,14,0,20,0,20,0,5,5,5,5,5,5,5,20,20,5,20,5,20,5,20,20,20,5,20,5,5,20,20,5,20,5,5,20,5,20,5,5,5,5,5,5,5,20,5,20,5,20,5,20,5,20,5,20,5,20,38,38,7,0,38,38,38,38,38,7,38,0,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,38,0,0,0,1,0,1,18,0,0,50,0,0,48,0,50,48,48,0,0,0,0,0,8,8,0,8,8,8,0,8,8,8,8,8,8,8,8,8,8,8,8,0,0,50,50,48,50,48,50,0,0,48,50,48,48,50,0,50,48,50,48,48,48,48,48,50,48,50,48,50,48,50,48,50,48,48,0,9,9,0,9,9,9,0,9,9,9,9,9,9,9,9,9,9,9,9,0,11,11,0,11,11,11,0,11,11,11,11,11,11,11,11,11,11,11,11],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1,[[4,[[3,[2]]]]]],0,[5,[[7,[6]]]],[5,[[7,[8]]]],[5,[[7,[9]]]],[10,[[7,[11]]]],0,0,0,0,0,[5,[[7,[[3,[1]]]]]],[5,[[7,[12]]]],[5,[[7,[9]]]],[10,[[7,[13]]]],0,[14,[[7,[5]]]],[1,[[7,[5]]]],[14,[[7,[5]]]],[[14,[16,[15]]],[[4,[[3,[2]]]]]],0,0,0,[17,6],[18,19],0,[[14,[16,[15]]],[[4,[[3,[2]]]]]],0,0,0,0,0,[5,[[7,[6]]]],[14,[[7,[5]]]],[14,[[7,[5]]]],[[14,[16,[15]]],[[4,[[3,[2]]]]]],[17,6],[[14,[16,[15]]],[[4,[[3,[2]]]]]],0,0,0,0,0,0,0,0,0,0,[5,[[7,[20]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[22,[20,21]]],23],[-1,-2,[],[]],[-1,-2,[],[]],[5,5],[20,20],[[-1,-2],24,[],[]],[[-1,-2],24,[],[]],[-1,[[22,[20,21]]],25],[[20,-1],[[22,[24,26]]],27],[[5,5],28],[[20,20],28],[[5,29],30],[[5,29],30],[[20,29],30],[[20,29],30],[-1,-1,[]],[-1,-1,[]],[31,[[22,[5,-1]]],[]],[[5,-1],24,32],[[20,-1],24,32],[-1,-2,[],[]],[-1,-2,[],[]],[33,5],[33,5],[33,5],[34,5],[33,5],[5,[[7,[35]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,10,[]],[-1,10,[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,36,[]],[-1,37,[]],[-1,37,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[38,29],30],[[38,29],30],[39,38],[40,38],[[[41,[-1]]],38,[]],[42,38],[43,38],[-1,-1,[]],[44,38],[-1,-2,[],[]],[38,[[46,[45]]]],[-1,10,[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,37,[]],[-1,-2,[],[]],0,0,0,[1,[[4,[[3,[2]]]]]],[5,[[7,[[3,[1]]]]]],[1,[[7,[5]]]],[18,19],0,0,0,[[5,47,31],[[7,[[3,[14]]]]]],[[5,47,31],[[7,[48]]]],0,[[5,49],[[7,[50]]]],0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[5,[[7,[8]]]],[-1,-1,[]],0,[-1,-2,[],[]],[5,[[7,[12]]]],[8,[[7,[5]]]],[51,8],[8,[[7,[5]]]],[[8,[16,[15]]],[[4,[[3,[2]]]]]],0,[8,[[3,[14]]]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,-2,[],[]],[[8,[16,[15]]],[[4,[[3,[2]]]]]],0,0,0,[50,[[4,[[3,[2]]]]]],0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[5,47,31],[[7,[[3,[14]]]]]],[[5,47,31],[[7,[48]]]],[-1,-1,[]],[-1,-1,[]],0,[-1,-2,[],[]],[-1,-2,[],[]],[[5,49],[[7,[50]]]],0,[48,[[7,[5]]]],[50,[[7,[5]]]],[[51,[52,[51]]],48],[48,[[7,[5]]]],[[48,[16,[15]]],[[4,[[3,[2]]]]]],0,[48,[[3,[14]]]],[50,[[3,[1]]]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],[[48,[16,[15]]],[[4,[[3,[2]]]]]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[5,[[7,[9]]]],[-1,-1,[]],0,[-1,-2,[],[]],[5,[[7,[9]]]],[9,[[7,[5]]]],[53,9],[9,[[7,[5]]]],[[9,[16,[15]]],[[4,[[3,[2]]]]]],[[9,[16,[15]]],[[7,[[24,[54,5]]]]]],[[9,[16,[15]],5],[[7,[54]]]],[9,[[3,[14]]]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,-2,[],[]],[[9,[16,[15]]],[[4,[[3,[2]]]]]],0,[-1,-2,[],[]],[-1,-2,[],[]],[10,[[7,[11]]]],[-1,-1,[]],0,[-1,-2,[],[]],[10,[[7,[13]]]],[11,[[7,[5]]]],[55,11],[11,[[7,[5]]]],[[11,[16,[15]]],[[4,[[3,[2]]]]]],0,[11,[[3,[14]]]],[-1,[[22,[-2]]],[],[]],[-1,[[22,[-2]]],[],[]],[-1,36,[]],[-1,-2,[],[]],[[11,[16,[15]]],[[4,[[3,[2]]]]]],0],"c":[],"p":[[10,"ConnListener",161],[10,"Future",277],[5,"Box",278],[5,"Pin",279],[6,"Endpoint",72],[8,"Conn",63],[8,"Result",127],[5,"TcpConn",182],[5,"UdpConn",237],[5,"String",280],[5,"UnixConn",257],[5,"TcpListener",281],[5,"UnixListener",282],[10,"Connection",63],[1,"u8"],[1,"slice"],[10,"ToConn",63],[10,"ToListener",161],[8,"Listener",161],[6,"Addr",72],[6,"DecodeError",283],[6,"Result",284],[10,"BorrowDecoder",285],[1,"tuple"],[10,"Decoder",285],[6,"EncodeError",283],[10,"Encoder",286],[1,"bool"],[5,"Formatter",287],[8,"Result",287],[1,"str"],[10,"Hasher",288],[6,"SocketAddr",289],[5,"SocketAddr",290],[8,"Port",72],[5,"TypeId",291],[10,"Any",291],[6,"Error",127],[6,"Error",292],[5,"Error",293],[5,"SendError",294],[5,"RecvError",294],[6,"Error",295],[5,"InvalidDnsNameError",296],[10,"Error",297],[6,"Option",298],[5,"ClientConfig",299],[5,"TlsConn",202],[5,"ServerConfig",300],[5,"TlsListener",202],[5,"TcpStream",281],[6,"TlsStream",301],[5,"UdpSocket",302],[1,"usize"],[5,"UnixStream",282]],"b":[[96,"impl-Display-for-Endpoint"],[97,"impl-Debug-for-Endpoint"],[98,"impl-Display-for-Addr"],[99,"impl-Debug-for-Addr"],[144,"impl-Display-for-Error"],[145,"impl-Debug-for-Error"],[146,"impl-From%3CError%3E-for-Error"],[147,"impl-From%3CError%3E-for-Error"],[148,"impl-From%3CSendError%3CT%3E%3E-for-Error"],[149,"impl-From%3CRecvError%3E-for-Error"],[150,"impl-From%3CError%3E-for-Error"],[152,"impl-From%3CInvalidDnsNameError%3E-for-Error"]]}],\ +["karyon_p2p",{"doc":"A lightweight, extensible, and customizable peer-to-peer …","t":"IIFPPFPPPPPPPPPPPGPPPPFPPPPPPFPPOOCOCCOCCCOOOCOOOOCOOOOOOCCOOCOCOOOOOCCOOOOOOCOCCOCOIFONNNNOONNNNONONNONOONNNNNNFKNNONNNNNNNNNNNNFONNNOONOONOOOOOOOOOOOOOOONNNONGFPFPNNNNNNNNOOOONNNNNNNNNNNONNNNNNNNNNNNNNNFJNNNNONONNOOONNONNNNIFONNOONNONONOCONOOONCONNNNOONNNNNFSNNONONNNONOOONONNNNNNNNNNNNNONNNNSSFFFNNNNNNNNNNONNNNNNONNNNNNNNONNONNNNNNNOONNNNNNNNNNNNNNNPPPPPGPPPPPPPPPPPPPPPPIPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNFNNOONNONNONNNONNNNPFSSFGFPFPFPFPFPFPFFFPPOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNQONNNNNNNNNNNNOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNPPPGPPPPPGPPPPPFGPPGPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNIFEONNNONONNNONNNCNOOOOONNNONNNNOONNNNFNNNNNNNNNNNNNNNNNNNNNNNNIFIOONNNNOONNONONNONNONOOONOONNNNNNONNNNNNIPKIGIPONNNNNNMNNOOMNNNNNOMNECSPFGPNNNNNNNNNNNNNNNNOONONNONNNNNNNNNNNGPEEEESEEPEPESSEPFSEENNNNNCNNONNCNNNNNNNONNNHNNNNNNNNNNNNESSFFSSISSSSNNNNNNNNNNOOONNNNNNNNNNNONNNNONNNNNNNNNNNNNFSIONNNNNNONNNNNNOONNNNNNHFNNNNNNONNOONNNNNSSJFJJJFNNNNNNNNHNNHONNNHHNNNNNNNNHHNNNNNNNNFFNNNNNNNNNNNNNNNNNNNNOONOONNNNNNNNNONNHNN","n":["ArcBackend","ArcPeer","Backend","ChannelRecv","ChannelSend","Config","Config","Discovery","IO","IncompatiblePeer","IncompatibleVersion","InvalidDnsNameError","InvalidMsg","InvalidPongMsg","KaryonCore","KaryonNet","Lookup","P2pError","ParseError","ParseFloatError","ParseIntError","PeerAlreadyConnected","PeerID","PeerShutdown","Rcgen","Rustls","SemverError","TryFromPublicKey","UnsupportedProtocol","Version","X509Parser","Yasna","alloc","alloc","backend","bootstrap_peers","codec","config","config","connection","connector","discovery","discovery","discovery_port","enable_tls","error","handshake_timeout","inbound_slots","key_pair","listen_endpoint","listener","lookup_connect_retries","lookup_connection_lifespan","lookup_inbound_slots","lookup_outbound_slots","lookup_response_timeout","max_connect_retries","message","monitor","monitor","outbound_slots","peer","peer_endpoints","peer_pool","peer_pool","phantom","phantom","ping_interval","ping_timeout","protocol","protocols","ptr","ptr","refresh_connect_retries","refresh_interval","refresh_response_timeout","req","routing_table","seeding_interval","slots","tls_config","v","version","version","ArcBackend","Backend","alloc","attach_protocol","borrow","borrow_mut","config","config","discovery","from","inbound_slots","into","key_pair","key_pair","monitor","monitor","new","outbound_slots","peer_pool","peers","phantom","ptr","run","shutdown","try_from","try_into","type_id","vzip","Codec","CodecMsg","borrow","borrow_mut","conn","from","into","new","read","read_exact","read_timeout","try_from","try_into","type_id","vzip","write","write_all","Config","bootstrap_peers","borrow","borrow_mut","default","discovery_port","enable_tls","from","handshake_timeout","inbound_slots","into","listen_endpoint","lookup_connect_retries","lookup_connection_lifespan","lookup_inbound_slots","lookup_outbound_slots","lookup_response_timeout","max_connect_retries","outbound_slots","peer_endpoints","ping_interval","ping_timeout","refresh_connect_retries","refresh_interval","refresh_response_timeout","seeding_interval","try_from","try_into","type_id","version","vzip","ConnDirection","ConnQueue","Inbound","NewConn","Outbound","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","clone","clone_into","conn","conn_available","direction","disconnect_signal","fmt","fmt","from","from","from","handle","into","into","into","new","next","queue","to_owned","to_string","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","value_as_any","vzip","vzip","vzip","Connector","DNS_NAME","borrow","borrow_mut","connect","connect_with_cback","connection_slots","dial","enable_tls","from","into","key_pair","max_retries","monitor","new","shutdown","task_group","try_from","try_into","type_id","vzip","ArcDiscovery","Discovery","alloc","borrow","borrow_mut","config","conn_queue","connect","connect_loop","connector","from","inbound_slots","into","listener","lookup","lookup_service","new","outbound_slots","phantom","ptr","random_entry","refresh","refresh_service","shutdown","start","start_listener","start_seeding","table","task_group","try_from","try_into","type_id","update_entry","vzip","LookupService","MAX_PEERS_IN_PEERSMSG","borrow","borrow_mut","config","connect","connector","from","handle_inbound","handle_outbound","id","into","listen_endpoint","listener","monitor","new","outbound_slots","random_lookup","self_lookup","send_findpeer_msg","send_peer_msg","send_peers_msg","send_ping_msg","send_pong_msg","send_shutdown_msg","set_listen_endpoint","shutdown","start","start_listener","start_lookup","table","try_from","try_into","type_id","vzip","MAX_FAILURES","PINGMSG_SIZE","PingMsg","PongMsg","RefreshService","borrow","borrow","borrow","borrow_decode","borrow_decode","borrow_mut","borrow_mut","borrow_mut","clone","clone_into","config","connect","decode","decode","do_refresh","encode","encode","executor","fmt","fmt","from","from","from","into","into","into","listen_endpoint","listen_loop","listen_to_ping_msg","monitor","new","refresh_entry","refresh_loop","send_ping_msg","set_listen_endpoint","shutdown","start","table","task_group","to_owned","try_from","try_from","try_from","try_into","try_into","try_into","type_id","type_id","type_id","value_as_any","value_as_any","vzip","vzip","vzip","ChannelRecv","ChannelSend","Config","Discovery","Err","Error","IO","IncompatiblePeer","IncompatibleVersion","InvalidDnsNameError","InvalidMsg","InvalidPongMsg","KaryonCore","KaryonNet","Lookup","Ok","ParseError","ParseFloatError","ParseIntError","PeerAlreadyConnected","PeerShutdown","Rcgen","Result","Rustls","SemverError","TryFromPublicKey","UnsupportedProtocol","X509Parser","Yasna","borrow","borrow_mut","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","from","into","source","to_string","try_from","try_into","type_id","value_as_any","vzip","Listener","borrow","borrow_mut","connection_slots","enable_tls","from","into","key_pair","listen_loop","listend","monitor","new","shutdown","start","task_group","try_from","try_into","type_id","vzip","FindPeer","FindPeerMsg","MAX_ALLOWED_MSG_SIZE","MSG_HEADER_SIZE","NetMsg","NetMsgCmd","NetMsgHeader","Peer","PeerMsg","Peers","PeersMsg","Ping","PingMsg","Pong","PongMsg","Protocol","ProtocolMsg","Shutdown","ShutdownMsg","VerAckMsg","VerMsg","Verack","Version","ack","addr","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_decode","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone","clone","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","clone_into","command","decode","decode","decode","decode","decode","decode","decode","decode","decode","decode","decode","decode","discovery_port","encode","encode","encode","encode","encode","encode","encode","encode","encode","encode","encode","encode","eq","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","from","from","from","from","from","get_msg_payload","header","into","into","into","into","into","into","into","into","into","into","into","into","nonce","payload","payload","payload_size","peer_id","peer_id","peer_id","port","protocol_id","protocols","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","to_owned","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","type_id","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","value_as_any","version","version","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","vzip","AcceptFailed","Accepted","Conn","ConnEvent","ConnectFailed","ConnectRetried","Connected","Disconnected","Discovery","DiscoveryEvent","ListenFailed","Listening","LookupFailed","LookupStarted","LookupSucceeded","Monitor","MonitorEvent","NewPeer","PeerPool","PeerPoolEvent","RefreshStarted","RemovePeer","borrow","borrow","borrow","borrow","borrow","borrow_mut","borrow_mut","borrow_mut","borrow_mut","borrow_mut","clone","clone","clone","clone","clone_into","clone_into","clone_into","clone_into","fmt","fmt","fmt","fmt","fmt","fmt","fmt","fmt","from","from","from","from","from","from","from","from","inner","into","into","into","into","into","new","notify","subscribe","to_owned","to_owned","to_owned","to_owned","to_string","to_string","to_string","to_string","try_from","try_from","try_from","try_from","try_from","try_into","try_into","try_into","try_into","try_into","type_id","type_id","type_id","type_id","type_id","value_as_any","value_as_any","value_as_any","value_as_any","vzip","vzip","vzip","vzip","vzip","ArcPeer","Peer","PeerID","alloc","borrow","borrow_mut","broadcast","codec","config","conn_direction","direction","from","id","id","into","is_inbound","new","peer_id","peer_pool","peer_pool","phantom","protocol_events","protocol_ids","ptr","read_loop","register_listener","remote_endpoint","remote_endpoint","run","send","shutdown","start_protocols","stop_chan","task_group","try_from","try_into","type_id","vzip","PeerID","borrow","borrow_decode","borrow_mut","clone","clone_into","decode","encode","eq","fmt","fmt","from","from","hash","into","new","random","to_owned","to_string","try_from","try_from","try_into","type_id","value_as_any","vzip","ArcPeerPool","PeerPool","WeakPeerPool","alloc","alloc","attach_protocol","borrow","borrow_mut","broadcast","config","conn_queue","contains_peer","do_handshake","executor","from","id","into","listen_loop","monitor","new","new_peer","peers","peers_len","phantom","protocol_versions","protocols","protocols_match","ptr","ptr","remove_peer","send_verack","send_vermsg","setup_protocols","shutdown","start","task_group","try_from","try_into","type_id","vzip","wait_verack","wait_vermsg","ArcProtocol","Message","Protocol","ProtocolConstructor","ProtocolEvent","ProtocolID","Shutdown","alloc","borrow","borrow_mut","clone","clone_into","fmt","from","id","id","into","phantom","ptr","start","to_owned","try_from","try_into","type_id","value_as_any","vec","version","vzip","PingProtocol","ping","MAX_FAILUERS","Ping","PingProtocol","PingProtocolMsg","Pong","borrow","borrow","borrow_decode","borrow_mut","borrow_mut","clone","clone_into","decode","encode","fmt","from","from","id","into","into","new","peer","ping_interval","ping_loop","ping_timeout","recv_loop","start","task_group","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","value_as_any","version","vzip","vzip","AddEntryResult","Added","Bucket","BucketEntry","CONNECTED_ENTRY","DISCONNECTED_ENTRY","DISTANCE_LIMIT","Entry","EntryStatusFlag","Exists","INCOMPATIBLE_ENTRY","Ignored","Key","MAX_MATCHED_SUBNET_IN_BUCKET","MAX_MATCHED_SUBNET_IN_TABLE","PENDING_ENTRY","Restricted","RoutingTable","TABLE_SIZE","UNREACHABLE_ENTRY","UNSTABLE_ENTRY","add_entry","borrow","borrow","borrow_mut","borrow_mut","bucket","bucket_index","bucket_indexes","buckets","closest_entries","contains_key","entry","fmt","fmt","from","from","into","into","iter","key","new","random_entry","remove_entry","subnet_match","subnet_restricted","try_from","try_from","try_into","try_into","type_id","type_id","update_entry","value_as_any","value_as_any","vzip","vzip","xor_distance","ALL_ENTRY","BUCKET_SIZE","Bucket","BucketEntry","CONNECTED_ENTRY","DISCONNECTED_ENTRY","EntryStatusFlag","INCOMPATIBLE_ENTRY","PENDING_ENTRY","UNREACHABLE_ENTRY","UNSTABLE_ENTRY","add","borrow","borrow","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","contains_key","entries","entry","failures","fmt","fmt","from","from","into","into","is_connected","is_incompatible","is_unreachable","is_unstable","iter","last_seen","len","new","random_iter","remove","status","to_owned","to_owned","try_from","try_from","try_into","try_into","type_id","type_id","update_entry","value_as_any","value_as_any","vzip","vzip","Entry","KEY_SIZE","Key","addr","borrow","borrow_decode","borrow_mut","clone","clone_into","decode","discovery_port","encode","eq","fmt","from","from","into","key","port","to_owned","try_from","try_into","type_id","value_as_any","vzip","xor_distance","ConnectionSlots","add","borrow","borrow_mut","from","into","load","max_slots","new","remove","signal","slots","try_from","try_into","type_id","vzip","wait_for_slot","BAD_ENCODING_ERR","BAD_SIGNATURE_ERR","CIPHER_SUITES","CliCertVerifier","KX_GROUPS","PROTOCOL_VERSIONS","SIGNATURE_SCHEMES","SrvrCertVerifier","borrow","borrow","borrow_mut","borrow_mut","fmt","fmt","from","from","generate_cert","into","into","parse_cert","peer_id","root_hint_subjects","supported_verify_schemes","supported_verify_schemes","tls_client_config","tls_server_config","try_from","try_from","try_into","try_into","type_id","type_id","value_as_any","value_as_any","verify_cert","verify_cert_signature","verify_client_cert","verify_server_cert","verify_tls12_signature","verify_tls12_signature","verify_tls13_signature","verify_tls13_signature","vzip","vzip","Version","VersionInt","borrow","borrow","borrow_decode","borrow_mut","borrow_mut","clone","clone","clone_into","clone_into","decode","encode","fmt","fmt","fmt","from","from","from_str","from_str","into","into","major","minor","new","patch","req","to_owned","to_owned","to_string","try_from","try_from","try_into","try_into","type_id","type_id","v","value_as_any","value_as_any","version_match","vzip","vzip"],"q":[[0,"karyon_p2p"],[84,"karyon_p2p::backend"],[112,"karyon_p2p::codec"],[129,"karyon_p2p::config"],[160,"karyon_p2p::connection"],[204,"karyon_p2p::connector"],[225,"karyon_p2p::discovery"],[259,"karyon_p2p::discovery::lookup"],[294,"karyon_p2p::discovery::refresh"],[353,"karyon_p2p::error"],[408,"karyon_p2p::listener"],[427,"karyon_p2p::message"],[653,"karyon_p2p::monitor"],[750,"karyon_p2p::peer"],[788,"karyon_p2p::peer::peer_id"],[813,"karyon_p2p::peer_pool"],[855,"karyon_p2p::protocol"],[883,"karyon_p2p::protocols"],[885,"karyon_p2p::protocols::ping"],[924,"karyon_p2p::routing_table"],[982,"karyon_p2p::routing_table::bucket"],[1036,"karyon_p2p::routing_table::entry"],[1062,"karyon_p2p::slots"],[1079,"karyon_p2p::tls_config"],[1123,"karyon_p2p::version"],[1165,"core::result"],[1166,"core::ops::function"],[1167,"core::marker"],[1168,"core::marker"],[1169,"karyon_core::crypto::key_pair"],[1170,"karyon_core::pubsub"],[1171,"karyon_core"],[1172,"core::any"],[1173,"karyon_net::connection"],[1174,"alloc::boxed"],[1175,"core::time"],[1176,"core::fmt"],[1177,"core::fmt"],[1178,"core::any"],[1179,"core::option"],[1180,"core::future::future"],[1181,"core::ops::function"],[1182,"async_lock::mutex"],[1183,"bincode::error"],[1184,"bincode::de"],[1185,"bincode::de"],[1186,"karyon_net::endpoint"],[1187,"rustls_pki_types::server_name"],[1188,"rcgen::error"],[1189,"std::io::error"],[1190,"semver::parse"],[1191,"async_channel"],[1192,"karyon_core::error"],[1193,"yasna::reader::error"],[1194,"x509_parser::error"],[1195,"async_channel"],[1196,"karyon_net::error"],[1197,"core::num::error"],[1198,"core::num::dec2flt"],[1199,"core::error"],[1200,"karyon_net::listener"],[1201,"core::clone"],[1202,"alloc::sync"],[1203,"core::hash"],[1204,"karyon_core::crypto::key_pair"],[1205,"core::pin"],[1206,"async_channel"],[1207,"rustls_pki_types"],[1208,"rustls_pki_types"],[1209,"rustls::msgs::handshake"],[1210,"rustls::enums"],[1211,"rustls::client::client_conn"],[1212,"rustls::server::server_conn"],[1213,"rustls_pki_types"],[1214,"rustls_pki_types::server_name"]],"d":["","","Backend serves as the central entry point for initiating …","","","the Configuration for the P2P network.","","","","","","","","","","","","Represents karyon’s p2p Error.","","","","","Represents a unique identifier for a peer.","","","","","","","Represents the network version and protocol version used …","","","","","","A list of bootstrap peers for the seeding process.","","","The Configuration for the P2P network.","","","","Discovery instance.","TCP/UDP port for lookup and refresh processes.","Enables TLS for all connections.","","Timeout duration for the handshake with new peers, in …","The number of available inbound slots for incoming …","Identity Key pair","An optional listening endpoint to accept incoming …","","The maximum number of retries for outbound connection …","Maximum allowable time for a live connection with a peer …","The number of available inbound slots for incoming …","The number of available outbound slots for outgoing …","Timeout duration for a peer response during the lookup …","The maximum number of retries for outbound connection …","","Responsible for network and system monitoring. Read More","Responsible for network and system monitoring.","The number of available outbound slots for outgoing …","","A list of endpoints representing peers that the Discovery …","","PeerPool instance.","","","Interval at which the ping protocol sends ping messages to …","Timeout duration for receiving the pong message …","Defines the protocol trait. Read More","","","","The maximum number of retries for outbound connection …","Interval at which the table refreshes its entries, in …","Timeout duration for a peer response during the table …","","","Time interval, in seconds, at which the Discovery restarts …","","","","","Represents the network version.","","Backend serves as the central entry point for initiating …","","Attach a custom protocol to the network","","","Returns the Config.","The Configuration for the P2P network.","Discovery instance.","Returns the argument unchanged.","Returns the number of occupied inbound slots.","Calls U::from(self).","Returns the KeyPair.","Identity Key pair","Subscribes to the monitor to receive network events.","Responsible for network and system monitoring.","Creates a new Backend.","Returns the number of occupied outbound slots.","PeerPool instance.","Returns the number of currently connected peers.","","","Run the Backend, starting the PeerPool and Discovery …","Shuts down the Backend.","","","","","A Codec working with generic network connections.","","","","","Returns the argument unchanged.","Calls U::from(self).","Creates a new Codec.","Reads a message of type NetMsg from the connection.","Reads the exact number of bytes required to fill buf.","Reads a message of type NetMsg with the given timeout.","","","","","Writes a message of type T to the connection.","Writes an entire buffer into the connection.","the Configuration for the P2P network.","A list of bootstrap peers for the seeding process.","","","","TCP/UDP port for lookup and refresh processes.","Enables TLS for all connections.","Returns the argument unchanged.","Timeout duration for the handshake with new peers, in …","The number of available inbound slots for incoming …","Calls U::from(self).","An optional listening endpoint to accept incoming …","The maximum number of retries for outbound connection …","Maximum allowable time for a live connection with a peer …","The number of available inbound slots for incoming …","The number of available outbound slots for outgoing …","Timeout duration for a peer response during the lookup …","The maximum number of retries for outbound connection …","The number of available outbound slots for outgoing …","A list of endpoints representing peers that the Discovery …","Interval at which the ping protocol sends ping messages to …","Timeout duration for receiving the pong message …","The maximum number of retries for outbound connection …","Interval at which the table refreshes its entries, in …","Timeout duration for a peer response during the table …","Time interval, in seconds, at which the Discovery restarts …","","","","Represents the network version.","","Defines the direction of a network connection.","Connection queue","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Push a connection into the queue and wait for the …","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","Receive the next connection in the queue","","","","","","","","","","","","","","","","","Responsible for creating outbound connections with other …","","","","Establish a connection to the specified endpoint. If the …","Establish a connection to the given endpoint. For each new …","Manages available outbound slots.","","Enables secure connection.","Returns the argument unchanged.","Calls U::from(self).","Identity Key pair","The maximum number of retries allowed before successfully …","Responsible for network and system monitoring.","Creates a new Connector","Shuts down the connector","Managing spawned tasks.","","","","","","","","","","Holds the configuration for the P2P network.","Connection queue","Connect to the given endpoint using the connector","This method will attempt to connect to a peer in the …","Connector","Returns the argument unchanged.","Inbound slots.","Calls U::from(self).","Listener","","Lookup Service","Creates a new Discovery","Outbound slots.","","","Returns a random entry from routing table.","","Refresh Service","Shuts down the discovery","Start the Discovery","Start a listener and on success, return the resolved …","Starts seeding process.","Routing table","Managing spawned tasks.","","","","Update the entry status ","","","Maximum number of peers that can be returned in a PeersMsg.","","","Holds the configuration for the P2P network.","Connects to the given endpoint and initiates a lookup …","Connector","Returns the argument unchanged.","Handles inbound connection","Handles outbound connection","Peer’s ID","Calls U::from(self).","Resolved listen endpoint","Listener","Responsible for network and system monitoring.","Creates a new lookup service","Outbound slots.","Starts a random lookup","Starts a self lookup","Sends a FindPeer msg and wait to receivet the Peers msg.","Sends a Peer msg.","Sends a Peers msg.","Sends a Ping msg and wait to receive the Pong message.","Sends a Pong msg","Sends a Shutdown msg.","Set the resolved listen endpoint.","Shuts down the lookup service.","Start the lookup service.","Start a listener.","Starts iterative lookup and populate the routing table.","Routing Table","","","","","Maximum failures for an entry before removing it from the …","Ping message size","","","","","","","","","","","","","","Holds the configuration for the P2P network.","Initiates a UDP connection with the entry and attempts to …","","","Iterates over the entries and spawns a new task for each …","","","A global executor","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Resolved listen endpoint","Set up a UDP listener and start listening for Ping …","Listen to receive a Ping message and respond with a Pong …","Responsible for network and system monitoring.","Creates a new refresh service","Initiates refresh for a specific entry within the routing …","Initiates periodic refreshing of the routing table. This …","Sends a Ping msg and wait to receive the Pong message.","Set the resolved listen endpoint.","Shuts down the refresh service","Start the refresh service","Routing table","Managing spawned tasks.","","","","","","","","","","","","","","","","","","","","Contains the error value","Represents karyon’s p2p Error.","","","","","","","","","","Contains the success value","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","","","","","","","","","","","","Calls U::from(self).","","","","","","","","Responsible for creating inbound connections with other …","","","Manages available inbound slots.","Enables secure connection.","Returns the argument unchanged.","Calls U::from(self).","Identity Key pair","","","Responsible for network and system monitoring.","Creates a new Listener","Shuts down the listener","Starts a listener on the given endpoint. For each incoming …","Managing spawned tasks.","","","","","","FindPeer message used to find a specific peer.","The maximum allowed size for a message in bytes.","The size of the message header, in bytes.","Defines the main message in the karyon p2p network.","Defines message commands.","Represents the header of a message.","","PeerMsg containing information about a peer.","","PeersMsg a list of PeerMsg.","","Ping message with a nonce and version information.","","Ping message with a nonce.","","Defines a message related to a specific protocol.","","Shutdown message.","VerAck message acknowledges the receipt of a Version …","Version message, providing information about a peer’s …","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Defines connection-related events.","","","","","","Defines Discovery events.","","","","","","Responsible for network and system monitoring.","Defines various type of event that can be monitored.","","","Defines PeerPool events.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","","","Returns the argument unchanged.","","Returns the argument unchanged.","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Calls U::from(self).","Creates a new Monitor","Sends a new monitor event to all subscribers.","Subscribes to listen to new events.","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Broadcast a message to all connected peers using the …","Holds the Codec for the peer connection","Returns the Config instance.","The direction of the connection, either Inbound or Outbound","Returns the direction of the connection, which can be …","Returns the argument unchanged.","Return the peer’s ID","Peer’s ID","Calls U::from(self).","Check if the connection is Inbound","Creates a new peer","","","A weak pointer to PeerPool","","EventSys responsible for sending events to the protocols.","A list of protocol IDs","","Start a read loop to handle incoming messages from the …","Registers a listener for the given Protocol P.","Returns the remote endpoint for the peer","Remote endpoint for the peer","Run the peer","Send a message to the peer connection using the specified …","Shuts down the peer","Start running the protocols for this peer connection.","This channel is used to send a stop signal to the read …","Managing spawned tasks.","","","","","Represents a unique identifier for a peer.","","","","","","","","","","","","Returns the argument unchanged.","","Calls U::from(self).","Creates a new PeerID.","Generates a random PeerID.","","","","","","","","","","","","","","Attach a custom protocol to the network","","","Broadcast a message to all connected peers using the …","The Configuration for the P2P network.","Connection queue","Checks if the peer list contains a peer with the given …","Initiate a handshake with a connection.","A global Executor","Returns the argument unchanged.","Peer’s ID","Calls U::from(self).","Listens to a new connection from the connection queue","Responsible for network and system monitoring.","Creates a new PeerPool","Add a new peer to the peer list.","Holds the running peers.","Returns the number of currently connected peers.","","Hashmap contains protocol IDs and their versions.","Hashmap contains protocol constructors.","Check if the new connection has compatible protocols.","","","Shuts down the peer and remove it from the peer list.","Send a Verack message","Send a Version message","Attach the core protocols.","Shuts down","Start","Managing spawned tasks.","","","","","Wait for a Verack message","Wait for a Version message","","Message event, contains a vector of bytes.","The Protocol trait defines the interface for core protocols","","Protocol event","","Shutdown event signals the protocol to gracefully shut …","","","","","","","Returns the argument unchanged.","Returns the unique ProtocolID associated with the protocol.","","Calls U::from(self).","","","Start the protocol","","","","","","","Returns the version of the protocol.","","","","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","Calls U::from(self).","Calls U::from(self).","","","","","","","","","","","","","","","","","","","","Represents the possible result when adding a new entry.","The entry is added.","","","","","The distance limit for the closest buckets.","","","The entry is already exists.","","The entry is ignored.","","The maximum number of matched subnets allowed within a …","The maximum number of matched subnets across the entire …","","The entry is restricted and not allowed.","This is a modified version of the Kademlia Distributed …","The total number of buckets in the routing table.","","","Adds a new entry to the table and returns a result …","","","","","","","Returns a list of bucket indexes that are closest to the …","","Returns a list of the closest entries to the given target …","Check if the table contains the given key.","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","Returns an iterator of entries.","","Creates a new RoutingTable","Returns a random entry from the routing table.","Removes an entry with the given key from the routing …","Check if two addresses belong to the same subnet.","This function iterate through the routing table and counts …","","","","","","","Updates the status of an entry in the routing table …","","","","","","","The number of entries that can be stored within a single …","A Bucket represents a group of entries in the routing …","A BucketEntry represents a peer in the routing table.","The entry is connected.","The entry is disconnected. This will increase the failure …","BITFLAGS represent the status of an Entry within a bucket.","The entry is incompatible. This entry will not contribute …","The entry is ready to reconnect, meaning it has either …","The entry is unreachable. This will increase the failure …","The entry is unstable. This will increase the failure …","Add an entry to the bucket.","","","","","","","","","Check if the bucket contains the given key.","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Calls U::from(self).","Calls U::from(self).","","","","","Returns an iterator over the entries in the bucket.","","Get the number of entries in the bucket.","Creates a new empty Bucket","Returns an iterator of entries in random order.","Remove an entry.","","","","","","","","","","Updates the status of an entry in the bucket identified by …","","","","","An Entry represents a peer in the routing table.","Specifies the size of the key, in bytes.","The unique key identifying the peer.","The IP address of the peer.","","","","","","","UDP/TCP port","","","","Returns the argument unchanged.","","Calls U::from(self).","The unique key identifying the peer.","TCP port","","","","","","","Calculates the XOR distance between two provided keys.","Manages available inbound and outbound slots.","Increases the occupied slots by one.","","","Returns the argument unchanged.","Calls U::from(self).","Returns the number of occupied slots","The maximum number of slots.","Creates a new ConnectionSlots","Decreases the occupied slots by one and notifies the …","A condvar for notifying when a slot become available.","The number of occupied slots","","","","","Waits for a slot to become available.","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","Generates a certificate and returns both the certificate …","Calls U::from(self).","Calls U::from(self).","Parses the given x509 certificate.","","","","","Returns a TLS client configuration.","Returns a TLS server configuration.","","","","","","","","","Verifies the given certification.","Verifies the signature of the given certificate.","","","","","","","","","Represents the network version and protocol version used …","","","","","","","","","","","","","","","","Returns the argument unchanged.","Returns the argument unchanged.","","","Calls U::from(self).","Calls U::from(self).","","","Creates a new Version","","","","","","","","","","","","","","","Check if a version satisfies a version request.","",""],"i":[0,0,0,3,3,0,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,18,5,0,11,0,0,1,0,0,0,1,11,11,0,11,11,1,11,0,11,11,11,11,11,11,0,0,1,11,0,11,0,1,18,5,11,11,0,0,18,5,11,11,11,111,0,11,0,0,111,0,11,0,0,18,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,18,18,1,1,1,1,1,1,0,0,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,0,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,0,0,29,0,29,34,32,29,34,32,29,29,29,34,32,34,34,29,29,34,32,29,32,34,32,29,32,32,32,29,29,34,32,29,34,32,29,34,32,29,29,34,32,29,0,0,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,37,0,0,135,46,46,46,46,46,46,46,46,46,46,46,0,46,46,46,135,135,46,0,46,46,46,46,46,46,46,46,46,46,46,46,0,0,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,49,0,0,0,0,0,60,56,59,56,59,60,56,59,56,56,60,60,56,59,60,56,59,60,56,59,60,56,59,60,56,59,60,60,60,60,60,60,60,60,60,60,60,60,60,56,60,56,59,60,56,59,60,56,59,56,59,60,56,59,3,3,3,3,136,0,3,3,3,3,3,3,3,3,3,136,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,27,0,0,0,0,0,0,27,0,27,0,27,0,27,0,27,0,27,0,0,0,27,27,88,50,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,50,23,85,27,86,87,88,89,90,50,85,23,85,27,86,87,88,89,90,91,92,50,54,50,23,85,27,86,87,88,89,90,91,92,50,54,50,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,50,54,0,23,23,85,27,86,87,88,89,90,91,92,50,54,90,23,86,85,87,88,50,50,86,87,23,85,27,86,87,88,89,90,50,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,54,23,85,27,86,87,88,89,90,91,92,50,54,87,90,23,85,27,86,87,88,89,90,91,92,50,54,93,93,15,0,93,93,93,93,15,0,93,93,95,95,95,0,0,94,15,0,95,94,45,15,93,94,95,45,15,93,94,95,15,93,94,95,15,93,94,95,15,15,93,93,94,94,95,95,45,15,15,15,15,93,94,95,45,45,15,93,94,95,45,45,45,15,93,94,95,15,93,94,95,45,15,93,94,95,45,15,93,94,95,45,15,93,94,95,15,93,94,95,45,15,93,94,95,0,0,0,5,96,96,96,96,96,96,96,96,96,96,96,96,96,0,96,96,5,96,96,5,96,96,96,96,96,96,96,96,96,96,96,96,96,96,0,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,39,0,0,0,137,138,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,98,137,98,98,98,137,138,98,98,98,98,98,98,98,98,98,98,98,98,98,0,100,0,0,0,0,100,7,100,100,100,100,100,100,109,100,100,7,7,109,100,100,100,100,100,97,109,100,0,0,0,112,0,0,112,113,112,112,113,112,112,112,112,112,112,113,112,113,113,112,113,113,113,113,113,113,113,113,112,113,112,113,112,113,112,112,113,113,112,0,115,0,0,0,0,0,0,0,115,0,115,0,0,0,0,115,0,0,0,0,52,115,52,115,52,0,52,52,52,52,52,0,115,52,115,52,115,52,52,52,52,52,52,0,52,115,52,115,52,115,52,52,115,52,115,52,0,0,0,0,0,0,0,0,0,0,0,0,117,62,117,62,117,62,117,62,117,117,117,62,62,62,117,62,117,62,117,62,62,62,62,117,62,117,117,117,117,62,62,117,62,117,62,117,62,117,117,62,117,62,117,0,0,0,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,0,0,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43,0,0,0,0,0,0,0,0,119,120,119,120,119,120,119,120,0,119,120,0,119,120,119,120,0,0,119,120,119,120,119,120,119,120,0,0,120,119,119,120,119,120,119,120,0,0,111,106,106,111,106,111,106,111,106,106,106,111,106,106,111,106,111,106,111,106,106,106,111,106,111,111,106,106,111,106,111,106,111,106,111,111,106,0,111,106],"f":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[1,-1],[[4,[2,3]]],[[8,[5],[[6,[7]]]],9,10]],[-1,-2,[],[]],[-1,-2,[],[]],[1,[[12,[11]]]],0,0,[-1,-1,[]],[1,13],[-1,-2,[],[]],[1,14],0,[1,[[16,[15]]]],0,[[14,11,17],18],[1,13],0,[1,13],0,0,[[[12,[1]]],[[4,[2,3]]]],[1,2],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],0,[-1,-1,[]],[-1,-2,[],[]],[[[21,[20]]],22],[22,[[4,[23,3]]]],[[22,[25,[24]]],[[4,[2,3]]]],[[22,26],[[4,[23,3]]]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],[[22,27,-1],[[4,[2,3]]],28],[[22,[25,[24]]],[[4,[2,3]]]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[],11],0,0,[-1,-1,[]],0,0,[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],0,[-1,-2,[],[]],0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[29,29],[[-1,-2],2,[],[]],0,0,0,0,[[29,30],31],[[29,30],31],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[[32,33,29],[[4,[2,3]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[],[[12,[32]]]],[32,34],0,[-1,-2,[],[]],[-1,35,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[37,38,[40,[39]]],[[4,[33,3]]]],[[[12,[37]],38,[40,[39]],-2],[[4,[2,3]]],[[41,[],[[6,[[4,[2,3]]]]]],9],[[42,[33],[[6,[-1]]]],9]],0,[[37,38,[40,[39]]],[[4,[33,3]]]],0,[-1,-1,[]],[-1,-2,[],[]],0,0,0,[[14,13,[12,[43]],44,[12,[45]],17],[[12,[37]]]],[37,2],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],0,0,[[[12,[46]],38,[40,[39]]],2],[[[12,[46]]],[[4,[2,3]]]],0,[-1,-1,[]],0,[-1,-2,[],[]],0,0,0,[[14,39,[12,[32]],[12,[11]],[12,[45]],17],[[12,[46]]]],0,0,0,[[46,47],[[40,[48]]]],0,0,[46,2],[[[12,[46]]],[[4,[2,3]]]],[[[12,[46]],38],[[4,[38,3]]]],[46,2],0,0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[[46,39,47],2],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],0,[[49,38,[40,[39]],39],[[4,[[51,[50]],3]]]],0,[-1,-1,[]],[[[12,[49]],33],[[4,[2,3]]]],[[49,22,39],[[4,[[51,[50]],3]]]],0,[-1,-2,[],[]],0,0,0,[[14,39,[12,[[53,[52]]]],[12,[11]],[12,[45]],17],49],0,[[49,38,[40,[39]],[51,[50]]],[[4,[2,3]]]],[[49,[51,[50]],[51,[50]]],2],[[49,22,39],[[4,[54,3]]]],[[49,22,38],[[4,[2,3]]]],[[49,39,22],[[4,[2,3]]]],[[49,22],[[4,[2,3]]]],[[49,[55,[24]],22],[[4,[2,3]]]],[[49,22],[[4,[2,3]]]],[[49,38],2],[49,2],[[[12,[49]]],[[4,[2,3]]]],[[[12,[49]]],[[4,[2,3]]]],[[49,38,[40,[39]]],[[4,[2,3]]]],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[56,57]]],58],[-1,[[4,[59,57]]],58],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[56,56],[[-1,-2],2,[],[]],0,[[60,48],[[4,[2,3]]]],[-1,[[4,[56,57]]],61],[-1,[[4,[59,57]]],61],[[[12,[60]],[25,[62]]],2],[[56,-1],[[4,[2,63]]],64],[[59,-1],[[4,[2,63]]],64],0,[[56,30],31],[[59,30],31],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,[[[12,[60]],65,66],[[4,[2,3]]]],[[60,67],[[4,[2,3]]]],0,[[[12,[11]],[12,[[53,[52]]]],[12,[45]],17],60],[[[12,[60]],62],2],[[[12,[60]]],[[4,[2,3]]]],[[60,67],[[4,[2,3]]]],[[60,38],2],[60,2],[[[12,[60]]],[[4,[2,3]]]],0,0,[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[3,30],31],[[3,30],31],[-1,-1,[]],[68,3],[69,3],[70,3],[71,3],[[[72,[-1]]],3,[]],[73,3],[74,3],[75,3],[76,3],[77,3],[78,3],[79,3],[80,3],[-1,-2,[],[]],[3,[[40,[81]]]],[-1,35,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,36,[]],[-1,-2,[],[]],0,[-1,-2,[],[]],[-1,-2,[],[]],0,0,[-1,-1,[]],[-1,-2,[],[]],0,[[[12,[82]],[21,[83]],-2],2,[[41,[],[[6,[[4,[2,3]]]]]],9],[[42,[33],[[6,[-1]]]],84,9]],[[82,38],[[4,[[21,[83]],3]]]],0,[[14,[12,[43]],44,[12,[45]],17],[[12,[82]]]],[82,2],[[[12,[82]],38,-2],[[4,[38,3]]],[[41,[],[[6,[[4,[2,3]]]]]],9],[[42,[33],[[6,[-1]]]],84,9]],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[23,57]]],58],[-1,[[4,[85,57]]],58],[-1,[[4,[27,57]]],58],[-1,[[4,[86,57]]],58],[-1,[[4,[87,57]]],58],[-1,[[4,[88,57]]],58],[-1,[[4,[89,57]]],58],[-1,[[4,[90,57]]],58],[-1,[[4,[91,57]]],58],[-1,[[4,[92,57]]],58],[-1,[[4,[50,57]]],58],[-1,[[4,[54,57]]],58],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[23,23],[85,85],[27,27],[86,86],[87,87],[88,88],[89,89],[90,90],[50,50],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],0,[-1,[[4,[23,57]]],61],[-1,[[4,[85,57]]],61],[-1,[[4,[27,57]]],61],[-1,[[4,[86,57]]],61],[-1,[[4,[87,57]]],61],[-1,[[4,[88,57]]],61],[-1,[[4,[89,57]]],61],[-1,[[4,[90,57]]],61],[-1,[[4,[91,57]]],61],[-1,[[4,[92,57]]],61],[-1,[[4,[50,57]]],61],[-1,[[4,[54,57]]],61],0,[[23,-1],[[4,[2,63]]],64],[[85,-1],[[4,[2,63]]],64],[[27,-1],[[4,[2,63]]],64],[[86,-1],[[4,[2,63]]],64],[[87,-1],[[4,[2,63]]],64],[[88,-1],[[4,[2,63]]],64],[[89,-1],[[4,[2,63]]],64],[[90,-1],[[4,[2,63]]],64],[[91,-1],[[4,[2,63]]],64],[[92,-1],[[4,[2,63]]],64],[[50,-1],[[4,[2,63]]],64],[[54,-1],[[4,[2,63]]],64],[[50,50],44],[[23,30],31],[[85,30],31],[[27,30],31],[[86,30],31],[[87,30],31],[[88,30],31],[[89,30],31],[[90,30],31],[[91,30],31],[[92,30],31],[[50,30],31],[[54,30],31],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],[48,50],[-1,-1,[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[15,15],[93,93],[94,94],[95,95],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[15,30],31],[[15,30],31],[[93,30],31],[[93,30],31],[[94,30],31],[[94,30],31],[[95,30],31],[[95,30],31],[-1,-1,[]],[93,15],[95,15],[-1,-1,[]],[94,15],[-1,-1,[]],[-1,-1,[]],[-1,-1,[]],0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[],45],[[45,15],2],[45,[[16,[15]]]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,35,[]],[-1,35,[]],[-1,35,[]],[-1,35,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[[96,97,-1],2,28],0,[96,[[12,[11]]]],0,[96,29],[-1,-1,[]],[96,39],0,[-1,-2,[],[]],[96,44],[[[99,[98]],39,22,38,29,17],5],0,[96,[[12,[98]]]],0,0,0,0,0,[96,[[4,[2,3]]]],[96,[[101,[97,100]]]],[96,38],0,[[[12,[96]]],[[4,[2,3]]]],[[96,97,-1],[[4,[2,3]]],28],[96,2],[[[12,[96]]],2],0,0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],0,[-1,-2,[],[]],[-1,[[4,[39,57]]],58],[-1,-2,[],[]],[39,39],[[-1,-2],2,[],[]],[-1,[[4,[39,57]]],61],[[39,-1],[[4,[2,63]]],64],[[39,39],44],[[39,30],31],[[39,30],31],[[[55,[24]]],39],[-1,-1,[]],[[39,-1],2,102],[-1,-2,[],[]],[[[25,[24]]],39],[[],39],[-1,-2,[],[]],[-1,35,[]],[-1,[[4,[-2]]],[],[]],[103,[[4,[39,-1]]],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,36,[]],[-1,-2,[],[]],0,0,0,0,0,[[98,[21,[104]]],[[4,[2,3]]]],[-1,-2,[],[]],[-1,-2,[],[]],[[98,97,-1],2,28],0,0,[[98,39],44],[[98,22,29],[[4,[39,3]]]],0,[-1,-1,[]],0,[-1,-2,[],[]],[[[12,[98]]],2],0,[[39,[12,[32]],[12,[11]],[12,[45]],17],[[12,[98]]]],[[[12,[98]],33,29,[105,[[4,[2,3]]]]],[[4,[2,3]]]],0,[98,13],0,0,0,[[98,[107,[97,106]]],[[4,[2,3]]]],0,0,[[98,39],[[4,[2,3]]]],[[98,22,44],[[4,[2,3]]]],[[98,22],[[4,[2,3]]]],[98,[[4,[2,3]]]],[98,2],[[[12,[98]]],[[4,[2,3]]]],0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],[[98,22],[[4,[39,3]]]],[[98,22],[[4,[39,3]]]],0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[100,100],[[-1,-2],2,[],[]],[[100,30],31],[-1,-1,[]],[[],97],[[],108],[-1,-2,[],[]],0,0,[[[12,[109]]],[[110,[[21,[41]]]]]],[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,36,[]],0,[[],[[4,[111,3]]]],[-1,-2,[],[]],0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[112,57]]],58],[-1,-2,[],[]],[-1,-2,[],[]],[112,112],[[-1,-2],2,[],[]],[-1,[[4,[112,57]]],61],[[112,-1],[[4,[2,63]]],64],[[112,30],31],[-1,-1,[]],[-1,-1,[]],[[],97],[-1,-2,[],[]],[-1,-2,[],[]],[[5,17],7],0,0,[[[12,[113]],[114,[[55,[24]]]]],[[4,[2,3]]]],0,[[113,[101,[97,100]],[105,[[55,[24]]]]],[[4,[2,3]]]],[[[12,[113]]],[[110,[[21,[41]]]]]],0,[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[[],[[4,[111,3]]]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[[52,48],115],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],0,[[52,[55,[24]]],[[40,[13]]]],[[52,[55,[24]]],[[51,[13]]]],0,[[52,[55,[24]],13],[[51,[48]]]],[[52,[55,[24]]],44],0,[[115,30],31],[[52,30],31],[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],[52,[[0,[[118,[],[[116,[117]]]]]]]],0,[[[55,[24]]],52],[[52,47],[[40,[48]]]],[[52,[55,[24]]],2],[[65,65],44],[[52,13,48],44],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[[52,[55,[24]],47],2],[-1,36,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,0,0,0,0,0,0,0,0,[[117,48],2],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[62,62],[117,117],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[[117,[55,[24]]],44],0,0,0,[[62,30],31],[[117,30],31],[-1,-1,[]],[-1,-1,[]],[-1,-2,[],[]],[-1,-2,[],[]],[62,44],[62,44],[62,44],[62,44],[117,[[0,[[118,[],[[116,[62]]]]]]]],0,[117,13],[[],117],[[117,13],[[0,[[118,[],[[116,[62]]]]]]]],[[117,[55,[24]]],2],0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[[117,[55,[24]],47],2],[-1,36,[]],[-1,36,[]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,0,0,[-1,-2,[],[]],[-1,[[4,[48,57]]],58],[-1,-2,[],[]],[48,48],[[-1,-2],2,[],[]],[-1,[[4,[48,57]]],61],0,[[48,-1],[[4,[2,63]]],64],[[48,48],44],[[48,30],31],[-1,-1,[]],[50,48],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,36,[]],[-1,-2,[],[]],[[[55,[24]],[55,[24]]],[[55,[24]]]],0,[43,2],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-1,[]],[-1,-2,[],[]],[43,13],0,[13,43],[43,2],0,0,[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,-2,[],[]],[43,2],0,0,0,0,0,0,0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[-1,-2,[],[]],[[119,30],31],[[120,30],31],[-1,-1,[]],[-1,-1,[]],[14,[[4,[[2,[121,122]],3]]]],[-1,-2,[],[]],[-1,-2,[],[]],[121,[[4,[123,77]]]],0,[120,[[25,[124]]]],[119,[[51,[125]]]],[120,[[51,[125]]]],[[14,[40,[39]]],[[4,[126,3]]]],[14,[[4,[127,3]]]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],[-1,36,[]],[-1,36,[]],[121,[[4,[39,77]]]],[[123,[25,[24]],[25,[24]]],[[4,[2,77]]]],[[120,121,[25,[121]],128],[[4,[129,77]]]],[[119,121,[25,[121]],130,[25,[24]],128],[[4,[131,77]]]],[[119,[25,[24]],121,132],[[4,[133,77]]]],[[120,[25,[24]],121,132],[[4,[133,77]]]],[[119,[25,[24]],121,132],[[4,[133,77]]]],[[120,[25,[24]],121,132],[[4,[133,77]]]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,[[4,[106,57]]],58],[-1,-2,[],[]],[-1,-2,[],[]],[111,111],[106,106],[[-1,-2],2,[],[]],[[-1,-2],2,[],[]],[-1,[[4,[106,57]]],61],[[106,-1],[[4,[2,63]]],64],[[111,30],31],[[106,30],31],[[106,30],31],[-1,-1,[]],[-1,-1,[]],[108,[[4,[111,3]]]],[108,[[4,[106,3]]]],[-1,-2,[],[]],[-1,-2,[],[]],0,0,[[106,134],111],0,0,[-1,-2,[],[]],[-1,-2,[],[]],[-1,35,[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,[[4,[-2]]],[],[]],[-1,19,[]],[-1,19,[]],0,[-1,36,[]],[-1,36,[]],[[134,106],44],[-1,-2,[],[]],[-1,-2,[],[]]],"c":[],"p":[[5,"Backend",84],[1,"tuple"],[6,"Error",353],[6,"Result",1165],[8,"ArcPeer",750],[17,"Output"],[8,"ArcProtocol",855],[10,"Fn",1166],[10,"Send",1167],[10,"Sync",1167],[5,"Config",129],[5,"Arc",1168],[1,"usize"],[6,"KeyPair",1169],[6,"MonitorEvent",653],[5,"Subscription",1170],[8,"GlobalExecutor",1171],[8,"ArcBackend",84],[5,"TypeId",1172],[10,"Connection",1173],[5,"Box",1174],[5,"Codec",112],[5,"NetMsg",427],[1,"u8"],[1,"slice"],[5,"Duration",1175],[6,"NetMsgCmd",427],[10,"CodecMsg",112],[6,"ConnDirection",160],[5,"Formatter",1176],[8,"Result",1176],[5,"ConnQueue",160],[8,"Conn",1173],[5,"NewConn",160],[5,"String",1177],[10,"Any",1172],[5,"Connector",204],[6,"Endpoint",1178],[5,"PeerID",788],[6,"Option",1179],[10,"Future",1180],[10,"FnOnce",1166],[5,"ConnectionSlots",1062],[1,"bool"],[5,"Monitor",653],[5,"Discovery",225],[1,"u16"],[5,"Entry",1036],[5,"LookupService",259],[5,"PeerMsg",427],[5,"Vec",1181],[5,"RoutingTable",924],[5,"Mutex",1182],[5,"PeersMsg",427],[1,"array"],[5,"PingMsg",294],[6,"DecodeError",1183],[10,"BorrowDecoder",1184],[5,"PongMsg",294],[5,"RefreshService",294],[10,"Decoder",1184],[5,"BucketEntry",982],[6,"EncodeError",1183],[10,"Encoder",1185],[6,"Addr",1178],[8,"Port",1178],[5,"UdpConn",1186],[5,"InvalidDnsNameError",1187],[6,"Error",1188],[5,"Error",1189],[5,"Error",1190],[5,"SendError",1191],[6,"Error",1192],[5,"ASN1Error",1193],[6,"X509Error",1194],[5,"RecvError",1191],[6,"Error",1195],[6,"Error",1196],[5,"ParseIntError",1197],[5,"ParseFloatError",1198],[10,"Error",1199],[5,"Listener",408],[10,"ConnListener",1200],[10,"Clone",1201],[5,"NetMsgHeader",427],[5,"ProtocolMsg",427],[5,"VerMsg",427],[5,"VerAckMsg",427],[5,"ShutdownMsg",427],[5,"PingMsg",427],[5,"PongMsg",427],[5,"FindPeerMsg",427],[6,"ConnEvent",653],[6,"PeerPoolEvent",653],[6,"DiscoveryEvent",653],[5,"Peer",750],[8,"ProtocolID",855],[5,"PeerPool",813],[5,"Weak",1168],[6,"ProtocolEvent",855],[5,"EventListener",1202],[10,"Hasher",1203],[6,"PublicKey",1169],[8,"ProtocolConstructor",855],[5,"Sender",1191],[5,"VersionInt",1123],[5,"HashMap",1204],[1,"str"],[10,"Protocol",855],[5,"Pin",1205],[5,"Version",1123],[6,"PingProtocolMsg",885],[5,"PingProtocol",885],[5,"Receiver",1191],[6,"AddEntryResult",924],[17,"Item"],[5,"Bucket",982],[10,"Iterator",1206],[5,"SrvrCertVerifier",1079],[5,"CliCertVerifier",1079],[5,"CertificateDer",1207],[6,"PrivateKeyDer",1207],[5,"X509Certificate",1208],[5,"DistinguishedName",1209],[6,"SignatureScheme",1210],[5,"ClientConfig",1211],[5,"ServerConfig",1212],[5,"UnixTime",1207],[5,"ClientCertVerified",1213],[6,"ServerName",1187],[5,"ServerCertVerified",1213],[5,"DigitallySignedStruct",1213],[5,"HandshakeSignatureValid",1213],[5,"VersionReq",1214],[8,"ArcDiscovery",225],[8,"Result",353],[8,"ArcPeerPool",813],[8,"WeakPeerPool",813]],"b":[[177,"impl-Debug-for-ConnDirection"],[178,"impl-Display-for-ConnDirection"],[384,"impl-Debug-for-Error"],[385,"impl-Display-for-Error"],[387,"impl-From%3CInvalidDnsNameError%3E-for-Error"],[388,"impl-From%3CError%3E-for-Error"],[389,"impl-From%3CError%3E-for-Error"],[390,"impl-From%3CError%3E-for-Error"],[391,"impl-From%3CSendError%3CT%3E%3E-for-Error"],[392,"impl-From%3CError%3E-for-Error"],[393,"impl-From%3CASN1Error%3E-for-Error"],[394,"impl-From%3CX509Error%3E-for-Error"],[395,"impl-From%3CRecvError%3E-for-Error"],[396,"impl-From%3CError%3E-for-Error"],[397,"impl-From%3CNetError%3E-for-Error"],[398,"impl-From%3CParseIntError%3E-for-Error"],[399,"impl-From%3CParseFloatError%3E-for-Error"],[693,"impl-Debug-for-MonitorEvent"],[694,"impl-Display-for-MonitorEvent"],[695,"impl-Display-for-ConnEvent"],[696,"impl-Debug-for-ConnEvent"],[697,"impl-Display-for-PeerPoolEvent"],[698,"impl-Debug-for-PeerPoolEvent"],[699,"impl-Display-for-DiscoveryEvent"],[700,"impl-Debug-for-DiscoveryEvent"],[702,"impl-From%3CConnEvent%3E-for-MonitorEvent"],[703,"impl-From%3CDiscoveryEvent%3E-for-MonitorEvent"],[705,"impl-From%3CPeerPoolEvent%3E-for-MonitorEvent"],[797,"impl-Debug-for-PeerID"],[798,"impl-Display-for-PeerID"],[1137,"impl-Display-for-VersionInt"],[1138,"impl-Debug-for-VersionInt"]]}]\ +]')); +if (typeof exports !== 'undefined') exports.searchIndex = searchIndex; +else if (window.initSearch) window.initSearch(searchIndex); diff --git a/settings.html b/settings.html new file mode 100644 index 00000000..02cfc46a --- /dev/null +++ b/settings.html @@ -0,0 +1,2 @@ +Settings +

Rustdoc settings

Back
\ No newline at end of file diff --git a/src-files.js b/src-files.js new file mode 100644 index 00000000..697b6df4 --- /dev/null +++ b/src-files.js @@ -0,0 +1,7 @@ +var srcIndex = new Map(JSON.parse('[\ +["karyon_core",["",[["async_util",[],["backoff.rs","condvar.rs","condwait.rs","mod.rs","select.rs","task_group.rs","timeout.rs"]],["crypto",[],["key_pair.rs","mod.rs"]],["util",[],["decode.rs","encode.rs","mod.rs","path.rs"]]],["error.rs","event.rs","lib.rs","pubsub.rs"]]],\ +["karyon_jsonrpc",["",[],["client.rs","codec.rs","error.rs","lib.rs","message.rs","server.rs","service.rs"]]],\ +["karyon_net",["",[["transports",[],["mod.rs","tcp.rs","tls.rs","udp.rs","unix.rs"]]],["connection.rs","endpoint.rs","error.rs","lib.rs","listener.rs"]]],\ +["karyon_p2p",["",[["discovery",[],["lookup.rs","mod.rs","refresh.rs"]],["peer",[],["mod.rs","peer_id.rs"]],["protocols",[],["mod.rs","ping.rs"]],["routing_table",[],["bucket.rs","entry.rs","mod.rs"]]],["backend.rs","codec.rs","config.rs","connection.rs","connector.rs","error.rs","lib.rs","listener.rs","message.rs","monitor.rs","peer_pool.rs","protocol.rs","slots.rs","tls_config.rs","version.rs"]]]\ +]')); +createSrcSidebar(); diff --git a/src/karyon_core/async_util/backoff.rs.html b/src/karyon_core/async_util/backoff.rs.html new file mode 100644 index 00000000..83bd3fe0 --- /dev/null +++ b/src/karyon_core/async_util/backoff.rs.html @@ -0,0 +1,232 @@ +backoff.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+
use std::{
+    cmp::min,
+    sync::atomic::{AtomicBool, AtomicU32, Ordering},
+    time::Duration,
+};
+
+use smol::Timer;
+
+/// Exponential backoff
+/// <https://en.wikipedia.org/wiki/Exponential_backoff>
+///
+/// # Examples
+///
+/// ```
+/// use karyon_core::async_util::Backoff;
+///
+///  async {
+///     let backoff = Backoff::new(300, 3000);
+///
+///     loop {
+///         backoff.sleep().await;
+///     
+///         // do something
+///         break;
+///     }
+///
+///     backoff.reset();
+///
+///     // ....
+///  };
+///
+/// ```
+///
+pub struct Backoff {
+    /// The base delay in milliseconds for the initial retry.
+    base_delay: u64,
+    /// The max delay in milliseconds allowed for a retry.
+    max_delay: u64,
+    /// Atomic counter
+    retries: AtomicU32,
+    /// Stop flag
+    stop: AtomicBool,
+}
+
+impl Backoff {
+    /// Creates a new Backoff.
+    pub fn new(base_delay: u64, max_delay: u64) -> Self {
+        Self {
+            base_delay,
+            max_delay,
+            retries: AtomicU32::new(0),
+            stop: AtomicBool::new(false),
+        }
+    }
+
+    /// Sleep based on the current retry count and delay values.
+    /// Retruns the delay value.
+    pub async fn sleep(&self) -> u64 {
+        if self.stop.load(Ordering::SeqCst) {
+            Timer::after(Duration::from_millis(self.max_delay)).await;
+            return self.max_delay;
+        }
+
+        let retries = self.retries.load(Ordering::SeqCst);
+        let delay = self.base_delay * (2_u64).pow(retries);
+        let delay = min(delay, self.max_delay);
+
+        if delay == self.max_delay {
+            self.stop.store(true, Ordering::SeqCst);
+        }
+
+        self.retries.store(retries + 1, Ordering::SeqCst);
+
+        Timer::after(Duration::from_millis(delay)).await;
+        delay
+    }
+
+    /// Reset the retry counter to 0.
+    pub fn reset(&self) {
+        self.retries.store(0, Ordering::SeqCst);
+        self.stop.store(false, Ordering::SeqCst);
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::sync::Arc;
+
+    #[test]
+    fn test_backoff() {
+        smol::block_on(async move {
+            let backoff = Arc::new(Backoff::new(5, 15));
+            let backoff_c = backoff.clone();
+            smol::spawn(async move {
+                let delay = backoff_c.sleep().await;
+                assert_eq!(delay, 5);
+
+                let delay = backoff_c.sleep().await;
+                assert_eq!(delay, 10);
+
+                let delay = backoff_c.sleep().await;
+                assert_eq!(delay, 15);
+            })
+            .await;
+
+            smol::spawn(async move {
+                backoff.reset();
+                let delay = backoff.sleep().await;
+                assert_eq!(delay, 5);
+            })
+            .await;
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/condvar.rs.html b/src/karyon_core/async_util/condvar.rs.html new file mode 100644 index 00000000..bc29df06 --- /dev/null +++ b/src/karyon_core/async_util/condvar.rs.html @@ -0,0 +1,776 @@ +condvar.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+
use std::{
+    collections::HashMap,
+    future::Future,
+    pin::Pin,
+    sync::Mutex,
+    task::{Context, Poll, Waker},
+};
+
+use smol::lock::MutexGuard;
+
+use crate::util::random_16;
+
+/// CondVar is an async version of <https://doc.rust-lang.org/std/sync/struct.Condvar.html>
+///
+/// # Example
+///
+///```
+/// use std::sync::Arc;
+///
+/// use smol::lock::Mutex;
+///
+/// use karyon_core::async_util::CondVar;
+///
+///  async {
+///     
+///     let val = Arc::new(Mutex::new(false));
+///     let condvar = Arc::new(CondVar::new());
+///
+///     let val_cloned = val.clone();
+///     let condvar_cloned = condvar.clone();
+///     smol::spawn(async move {
+///         let mut val = val_cloned.lock().await;
+///
+///         // While the boolean flag is false, wait for a signal.
+///         while !*val {
+///             val = condvar_cloned.wait(val).await;
+///         }
+///
+///         // ...
+///     });
+///
+///     let condvar_cloned = condvar.clone();
+///     smol::spawn(async move {
+///         let mut val = val.lock().await;
+///
+///         // While the boolean flag is false, wait for a signal.
+///         while !*val {
+///             val = condvar_cloned.wait(val).await;
+///         }
+///
+///         // ...
+///     });
+///     
+///     // Wake up all waiting tasks on this condvar
+///     condvar.broadcast();
+///  };
+///
+/// ```
+
+pub struct CondVar {
+    inner: Mutex<Wakers>,
+}
+
+impl CondVar {
+    /// Creates a new CondVar
+    pub fn new() -> Self {
+        Self {
+            inner: Mutex::new(Wakers::new()),
+        }
+    }
+
+    /// Blocks the current task until this condition variable receives a notification.
+    pub async fn wait<'a, T>(&self, g: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
+        let m = MutexGuard::source(&g);
+
+        CondVarAwait::new(self, g).await;
+
+        m.lock().await
+    }
+
+    /// Wakes up one blocked task waiting on this condvar.
+    pub fn signal(&self) {
+        self.inner.lock().unwrap().wake(true);
+    }
+
+    /// Wakes up all blocked tasks waiting on this condvar.
+    pub fn broadcast(&self) {
+        self.inner.lock().unwrap().wake(false);
+    }
+}
+
+impl Default for CondVar {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+struct CondVarAwait<'a, T> {
+    id: Option<u16>,
+    condvar: &'a CondVar,
+    guard: Option<MutexGuard<'a, T>>,
+}
+
+impl<'a, T> CondVarAwait<'a, T> {
+    fn new(condvar: &'a CondVar, guard: MutexGuard<'a, T>) -> Self {
+        Self {
+            condvar,
+            guard: Some(guard),
+            id: None,
+        }
+    }
+}
+
+impl<'a, T> Future for CondVarAwait<'a, T> {
+    type Output = ();
+
+    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let mut inner = self.condvar.inner.lock().unwrap();
+
+        match self.guard.take() {
+            Some(_) => {
+                // the first pooll will release the Mutexguard
+                self.id = Some(inner.put(Some(cx.waker().clone())));
+                Poll::Pending
+            }
+            None => {
+                // Return Ready if it has already been polled and removed
+                // from the waker list.
+                if self.id.is_none() {
+                    return Poll::Ready(());
+                }
+
+                let i = self.id.as_ref().unwrap();
+                match inner.wakers.get_mut(i).unwrap() {
+                    Some(wk) => {
+                        // This will prevent cloning again
+                        if !wk.will_wake(cx.waker()) {
+                            wk.clone_from(cx.waker());
+                        }
+                        Poll::Pending
+                    }
+                    None => {
+                        inner.delete(i);
+                        self.id = None;
+                        Poll::Ready(())
+                    }
+                }
+            }
+        }
+    }
+}
+
+impl<'a, T> Drop for CondVarAwait<'a, T> {
+    fn drop(&mut self) {
+        if let Some(id) = self.id {
+            let mut inner = self.condvar.inner.lock().unwrap();
+            if let Some(wk) = inner.wakers.get_mut(&id).unwrap().take() {
+                wk.wake()
+            }
+        }
+    }
+}
+
+/// Wakers is a helper struct to store the task wakers
+struct Wakers {
+    wakers: HashMap<u16, Option<Waker>>,
+}
+
+impl Wakers {
+    fn new() -> Self {
+        Self {
+            wakers: HashMap::new(),
+        }
+    }
+
+    fn put(&mut self, waker: Option<Waker>) -> u16 {
+        let mut id: u16;
+
+        id = random_16();
+        while self.wakers.contains_key(&id) {
+            id = random_16();
+        }
+
+        self.wakers.insert(id, waker);
+        id
+    }
+
+    fn delete(&mut self, id: &u16) -> Option<Option<Waker>> {
+        self.wakers.remove(id)
+    }
+
+    fn wake(&mut self, signal: bool) {
+        for (_, wk) in self.wakers.iter_mut() {
+            match wk.take() {
+                Some(w) => {
+                    w.wake();
+                    if signal {
+                        break;
+                    }
+                }
+                None => continue,
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use smol::lock::Mutex;
+    use std::{
+        collections::VecDeque,
+        sync::{
+            atomic::{AtomicUsize, Ordering},
+            Arc,
+        },
+    };
+
+    // The tests below demonstrate a solution to a problem in the Wikipedia
+    // explanation of condition variables:
+    // https://en.wikipedia.org/wiki/Monitor_(synchronization)#Solving_the_bounded_producer/consumer_problem.
+
+    struct Queue {
+        items: VecDeque<String>,
+        max_len: usize,
+    }
+    impl Queue {
+        fn new(max_len: usize) -> Self {
+            Self {
+                items: VecDeque::new(),
+                max_len,
+            }
+        }
+
+        fn is_full(&self) -> bool {
+            self.items.len() == self.max_len
+        }
+
+        fn is_empty(&self) -> bool {
+            self.items.is_empty()
+        }
+    }
+
+    #[test]
+    fn test_condvar_signal() {
+        smol::block_on(async {
+            let number_of_tasks = 30;
+
+            let queue = Arc::new(Mutex::new(Queue::new(5)));
+            let condvar_full = Arc::new(CondVar::new());
+            let condvar_empty = Arc::new(CondVar::new());
+
+            let queue_cloned = queue.clone();
+            let condvar_full_cloned = condvar_full.clone();
+            let condvar_empty_cloned = condvar_empty.clone();
+
+            let _producer1 = smol::spawn(async move {
+                for i in 1..number_of_tasks {
+                    // Lock queue mtuex
+                    let mut queue = queue_cloned.lock().await;
+
+                    // Check if the queue is non-full
+                    while queue.is_full() {
+                        // Release queue mutex and sleep
+                        queue = condvar_full_cloned.wait(queue).await;
+                    }
+
+                    queue.items.push_back(format!("task {i}"));
+
+                    // Wake up the consumer
+                    condvar_empty_cloned.signal();
+                }
+            });
+
+            let queue_cloned = queue.clone();
+            let task_consumed = Arc::new(AtomicUsize::new(0));
+            let task_consumed_ = task_consumed.clone();
+            let consumer = smol::spawn(async move {
+                for _ in 1..number_of_tasks {
+                    // Lock queue mtuex
+                    let mut queue = queue_cloned.lock().await;
+
+                    // Check if the queue is non-empty
+                    while queue.is_empty() {
+                        // Release queue mutex and sleep
+                        queue = condvar_empty.wait(queue).await;
+                    }
+
+                    let _ = queue.items.pop_front().unwrap();
+
+                    task_consumed_.fetch_add(1, Ordering::Relaxed);
+
+                    // Do something
+
+                    // Wake up the producer
+                    condvar_full.signal();
+                }
+            });
+
+            consumer.await;
+            assert!(queue.lock().await.is_empty());
+            assert_eq!(task_consumed.load(Ordering::Relaxed), 29);
+        });
+    }
+
+    #[test]
+    fn test_condvar_broadcast() {
+        smol::block_on(async {
+            let tasks = 30;
+
+            let queue = Arc::new(Mutex::new(Queue::new(5)));
+            let condvar = Arc::new(CondVar::new());
+
+            let queue_cloned = queue.clone();
+            let condvar_cloned = condvar.clone();
+            let _producer1 = smol::spawn(async move {
+                for i in 1..tasks {
+                    // Lock queue mtuex
+                    let mut queue = queue_cloned.lock().await;
+
+                    // Check if the queue is non-full
+                    while queue.is_full() {
+                        // Release queue mutex and sleep
+                        queue = condvar_cloned.wait(queue).await;
+                    }
+
+                    queue.items.push_back(format!("producer1: task {i}"));
+
+                    // Wake up all producer and consumer tasks
+                    condvar_cloned.broadcast();
+                }
+            });
+
+            let queue_cloned = queue.clone();
+            let condvar_cloned = condvar.clone();
+            let _producer2 = smol::spawn(async move {
+                for i in 1..tasks {
+                    // Lock queue mtuex
+                    let mut queue = queue_cloned.lock().await;
+
+                    // Check if the queue is non-full
+                    while queue.is_full() {
+                        // Release queue mutex and sleep
+                        queue = condvar_cloned.wait(queue).await;
+                    }
+
+                    queue.items.push_back(format!("producer2: task {i}"));
+
+                    // Wake up all producer and consumer tasks
+                    condvar_cloned.broadcast();
+                }
+            });
+
+            let queue_cloned = queue.clone();
+            let task_consumed = Arc::new(AtomicUsize::new(0));
+            let task_consumed_ = task_consumed.clone();
+
+            let consumer = smol::spawn(async move {
+                for _ in 1..((tasks * 2) - 1) {
+                    {
+                        // Lock queue mutex
+                        let mut queue = queue_cloned.lock().await;
+
+                        // Check if the queue is non-empty
+                        while queue.is_empty() {
+                            // Release queue mutex and sleep
+                            queue = condvar.wait(queue).await;
+                        }
+
+                        let _ = queue.items.pop_front().unwrap();
+
+                        task_consumed_.fetch_add(1, Ordering::Relaxed);
+
+                        // Do something
+
+                        // Wake up all producer and consumer tasks
+                        condvar.broadcast();
+                    }
+                }
+            });
+
+            consumer.await;
+            assert!(queue.lock().await.is_empty());
+            assert_eq!(task_consumed.load(Ordering::Relaxed), 58);
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/condwait.rs.html b/src/karyon_core/async_util/condwait.rs.html new file mode 100644 index 00000000..0a815a0b --- /dev/null +++ b/src/karyon_core/async_util/condwait.rs.html @@ -0,0 +1,268 @@ +condwait.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+
use smol::lock::Mutex;
+
+use super::CondVar;
+
+/// CondWait is a wrapper struct for CondVar with a Mutex boolean flag.
+///
+/// # Example
+///
+///```
+/// use std::sync::Arc;
+///
+/// use karyon_core::async_util::CondWait;
+///
+///  async {
+///     let cond_wait = Arc::new(CondWait::new());
+///     let cond_wait_cloned = cond_wait.clone();
+///     let task = smol::spawn(async move {
+///         cond_wait_cloned.wait().await;
+///         // ...
+///     });
+///
+///     cond_wait.signal().await;
+///  };
+///
+/// ```
+///
+pub struct CondWait {
+    /// The CondVar
+    condvar: CondVar,
+    /// Boolean flag
+    w: Mutex<bool>,
+}
+
+impl CondWait {
+    /// Creates a new CondWait.
+    pub fn new() -> Self {
+        Self {
+            condvar: CondVar::new(),
+            w: Mutex::new(false),
+        }
+    }
+
+    /// Waits for a signal or broadcast.
+    pub async fn wait(&self) {
+        let mut w = self.w.lock().await;
+
+        // While the boolean flag is false, wait for a signal.
+        while !*w {
+            w = self.condvar.wait(w).await;
+        }
+    }
+
+    /// Signal a waiting task.
+    pub async fn signal(&self) {
+        *self.w.lock().await = true;
+        self.condvar.signal();
+    }
+
+    /// Signal all waiting tasks.
+    pub async fn broadcast(&self) {
+        *self.w.lock().await = true;
+        self.condvar.broadcast();
+    }
+
+    /// Reset the boolean flag value to false.
+    pub async fn reset(&self) {
+        *self.w.lock().await = false;
+    }
+}
+
+impl Default for CondWait {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::sync::{
+        atomic::{AtomicUsize, Ordering},
+        Arc,
+    };
+
+    #[test]
+    fn test_cond_wait() {
+        smol::block_on(async {
+            let cond_wait = Arc::new(CondWait::new());
+            let count = Arc::new(AtomicUsize::new(0));
+
+            let cond_wait_cloned = cond_wait.clone();
+            let count_cloned = count.clone();
+            let task = smol::spawn(async move {
+                cond_wait_cloned.wait().await;
+                count_cloned.fetch_add(1, Ordering::Relaxed);
+                // do something
+            });
+
+            // Send a signal to the waiting task
+            cond_wait.signal().await;
+
+            task.await;
+
+            // Reset the boolean flag
+            cond_wait.reset().await;
+
+            assert_eq!(count.load(Ordering::Relaxed), 1);
+
+            let cond_wait_cloned = cond_wait.clone();
+            let count_cloned = count.clone();
+            let task1 = smol::spawn(async move {
+                cond_wait_cloned.wait().await;
+                count_cloned.fetch_add(1, Ordering::Relaxed);
+                // do something
+            });
+
+            let cond_wait_cloned = cond_wait.clone();
+            let count_cloned = count.clone();
+            let task2 = smol::spawn(async move {
+                cond_wait_cloned.wait().await;
+                count_cloned.fetch_add(1, Ordering::Relaxed);
+                // do something
+            });
+
+            // Broadcast a signal to all waiting tasks
+            cond_wait.broadcast().await;
+
+            task1.await;
+            task2.await;
+            assert_eq!(count.load(Ordering::Relaxed), 3);
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/mod.rs.html b/src/karyon_core/async_util/mod.rs.html new file mode 100644 index 00000000..d5d76ae1 --- /dev/null +++ b/src/karyon_core/async_util/mod.rs.html @@ -0,0 +1,28 @@ +mod.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+
mod backoff;
+mod condvar;
+mod condwait;
+mod select;
+mod task_group;
+mod timeout;
+
+pub use backoff::Backoff;
+pub use condvar::CondVar;
+pub use condwait::CondWait;
+pub use select::{select, Either};
+pub use task_group::{TaskGroup, TaskResult};
+pub use timeout::timeout;
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/select.rs.html b/src/karyon_core/async_util/select.rs.html new file mode 100644 index 00000000..af2016d7 --- /dev/null +++ b/src/karyon_core/async_util/select.rs.html @@ -0,0 +1,200 @@ +select.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+
use std::pin::Pin;
+use std::task::{Context, Poll};
+
+use pin_project_lite::pin_project;
+use smol::future::Future;
+
+/// Returns the result of the future that completes first, preferring future1
+/// if both are ready.
+///
+/// # Examples
+///
+/// ```
+/// use std::future;
+///
+/// use karyon_core::async_util::{select, Either};
+///
+///  async {
+///     let fut1 = future::pending::<String>();
+///     let fut2 = future::ready(0);
+///     let res = select(fut1, fut2).await;
+///     assert!(matches!(res, Either::Right(0)));
+///     // ....
+///  };
+///
+/// ```
+///
+pub fn select<T1, T2, F1, F2>(future1: F1, future2: F2) -> Select<F1, F2>
+where
+    F1: Future<Output = T1>,
+    F2: Future<Output = T2>,
+{
+    Select { future1, future2 }
+}
+
+pin_project! {
+    #[derive(Debug)]
+    pub struct Select<F1, F2> {
+        #[pin]
+        future1: F1,
+        #[pin]
+        future2: F2,
+    }
+}
+
+/// The return value from the [`select`] function, indicating which future
+/// completed first.
+#[derive(Debug)]
+pub enum Either<T1, T2> {
+    Left(T1),
+    Right(T2),
+}
+
+// Implement the Future trait for the Select struct.
+impl<T1, T2, F1, F2> Future for Select<F1, F2>
+where
+    F1: Future<Output = T1>,
+    F2: Future<Output = T2>,
+{
+    type Output = Either<T1, T2>;
+
+    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+        let this = self.project();
+
+        if let Poll::Ready(t) = this.future1.poll(cx) {
+            return Poll::Ready(Either::Left(t));
+        }
+
+        if let Poll::Ready(t) = this.future2.poll(cx) {
+            return Poll::Ready(Either::Right(t));
+        }
+
+        Poll::Pending
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::{select, Either};
+    use smol::Timer;
+    use std::future;
+
+    #[test]
+    fn test_async_select() {
+        smol::block_on(async move {
+            let fut = select(Timer::never(), future::ready(0 as u32)).await;
+            assert!(matches!(fut, Either::Right(0)));
+
+            let fut1 = future::pending::<String>();
+            let fut2 = future::ready(0);
+            let res = select(fut1, fut2).await;
+            assert!(matches!(res, Either::Right(0)));
+
+            let fut1 = future::ready(0);
+            let fut2 = future::pending::<String>();
+            let res = select(fut1, fut2).await;
+            assert!(matches!(res, Either::Left(_)));
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/task_group.rs.html b/src/karyon_core/async_util/task_group.rs.html new file mode 100644 index 00000000..ab88a4b3 --- /dev/null +++ b/src/karyon_core/async_util/task_group.rs.html @@ -0,0 +1,390 @@ +task_group.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+
use std::{future::Future, sync::Arc, sync::Mutex};
+
+use async_task::FallibleTask;
+
+use crate::Executor;
+
+use super::{select, CondWait, Either};
+
+/// TaskGroup is a group of spawned tasks.
+///
+/// # Example
+///
+/// ```
+///
+/// use std::sync::Arc;
+///
+/// use karyon_core::async_util::TaskGroup;
+///
+/// async {
+///
+///     let ex = Arc::new(smol::Executor::new());
+///     let group = TaskGroup::new(ex);
+///
+///     group.spawn(smol::Timer::never(), |_| async {});
+///
+///     group.cancel().await;
+///
+/// };
+///
+/// ```
+///
+pub struct TaskGroup<'a> {
+    tasks: Mutex<Vec<TaskHandler>>,
+    stop_signal: Arc<CondWait>,
+    executor: Executor<'a>,
+}
+
+impl<'a> TaskGroup<'a> {
+    /// Creates a new task group
+    pub fn new(executor: Executor<'a>) -> Self {
+        Self {
+            tasks: Mutex::new(Vec::new()),
+            stop_signal: Arc::new(CondWait::new()),
+            executor,
+        }
+    }
+
+    /// Spawns a new task and calls the callback after it has completed
+    /// or been canceled. The callback will have the `TaskResult` as a
+    /// parameter, indicating whether the task completed or was canceled.
+    pub fn spawn<T, Fut, CallbackF, CallbackFut>(&self, fut: Fut, callback: CallbackF)
+    where
+        T: Send + Sync + 'a,
+        Fut: Future<Output = T> + Send + 'a,
+        CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'a,
+        CallbackFut: Future<Output = ()> + Send + 'a,
+    {
+        let task = TaskHandler::new(
+            self.executor.clone(),
+            fut,
+            callback,
+            self.stop_signal.clone(),
+        );
+        self.tasks.lock().unwrap().push(task);
+    }
+
+    /// Checks if the task group is empty.
+    pub fn is_empty(&self) -> bool {
+        self.tasks.lock().unwrap().is_empty()
+    }
+
+    /// Get the number of the tasks in the group.
+    pub fn len(&self) -> usize {
+        self.tasks.lock().unwrap().len()
+    }
+
+    /// Cancels all tasks in the group.
+    pub async fn cancel(&self) {
+        self.stop_signal.broadcast().await;
+
+        loop {
+            let task = self.tasks.lock().unwrap().pop();
+            if let Some(t) = task {
+                t.cancel().await
+            } else {
+                break;
+            }
+        }
+    }
+}
+
+/// The result of a spawned task.
+#[derive(Debug)]
+pub enum TaskResult<T> {
+    Completed(T),
+    Cancelled,
+}
+
+impl<T: std::fmt::Debug> std::fmt::Display for TaskResult<T> {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            TaskResult::Cancelled => write!(f, "Task cancelled"),
+            TaskResult::Completed(res) => write!(f, "Task completed: {:?}", res),
+        }
+    }
+}
+
+/// TaskHandler
+pub struct TaskHandler {
+    task: FallibleTask<()>,
+    cancel_flag: Arc<CondWait>,
+}
+
+impl<'a> TaskHandler {
+    /// Creates a new task handle
+    fn new<T, Fut, CallbackF, CallbackFut>(
+        ex: Executor<'a>,
+        fut: Fut,
+        callback: CallbackF,
+        stop_signal: Arc<CondWait>,
+    ) -> TaskHandler
+    where
+        T: Send + Sync + 'a,
+        Fut: Future<Output = T> + Send + 'a,
+        CallbackF: FnOnce(TaskResult<T>) -> CallbackFut + Send + 'a,
+        CallbackFut: Future<Output = ()> + Send + 'a,
+    {
+        let cancel_flag = Arc::new(CondWait::new());
+        let cancel_flag_c = cancel_flag.clone();
+        let task = ex
+            .spawn(async move {
+                //start_signal.signal().await;
+                // Waits for either the stop signal or the task to complete.
+                let result = select(stop_signal.wait(), fut).await;
+
+                let result = match result {
+                    Either::Left(_) => TaskResult::Cancelled,
+                    Either::Right(res) => TaskResult::Completed(res),
+                };
+
+                // Call the callback with the result.
+                callback(result).await;
+
+                cancel_flag_c.signal().await;
+            })
+            .fallible();
+
+        TaskHandler { task, cancel_flag }
+    }
+
+    /// Cancels the task.
+    async fn cancel(self) {
+        self.cancel_flag.wait().await;
+        self.task.cancel().await;
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::{future, sync::Arc};
+
+    #[test]
+    fn test_task_group() {
+        let ex = Arc::new(smol::Executor::new());
+        smol::block_on(ex.clone().run(async move {
+            let group = Arc::new(TaskGroup::new(ex));
+
+            group.spawn(future::ready(0), |res| async move {
+                assert!(matches!(res, TaskResult::Completed(0)));
+            });
+
+            group.spawn(future::pending::<()>(), |res| async move {
+                assert!(matches!(res, TaskResult::Cancelled));
+            });
+
+            let groupc = group.clone();
+            group.spawn(
+                async move {
+                    groupc.spawn(future::pending::<()>(), |res| async move {
+                        assert!(matches!(res, TaskResult::Cancelled));
+                    });
+                },
+                |res| async move {
+                    assert!(matches!(res, TaskResult::Completed(_)));
+                },
+            );
+
+            // Do something
+            smol::Timer::after(std::time::Duration::from_millis(50)).await;
+            group.cancel().await;
+        }));
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/async_util/timeout.rs.html b/src/karyon_core/async_util/timeout.rs.html new file mode 100644 index 00000000..3d461632 --- /dev/null +++ b/src/karyon_core/async_util/timeout.rs.html @@ -0,0 +1,106 @@ +timeout.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+
use std::{future::Future, time::Duration};
+
+use smol::Timer;
+
+use super::{select, Either};
+use crate::{error::Error, Result};
+
+/// Waits for a future to complete or times out if it exceeds a specified
+/// duration.
+///
+/// # Example
+///
+/// ```
+/// use std::{future, time::Duration};
+///
+/// use karyon_core::async_util::timeout;
+///
+/// async {
+///     let fut = future::pending::<()>();
+///     assert!(timeout(Duration::from_millis(100), fut).await.is_err());
+/// };
+///
+/// ```
+///
+pub async fn timeout<T, F>(delay: Duration, future1: F) -> Result<T>
+where
+    F: Future<Output = T>,
+{
+    let result = select(Timer::after(delay), future1).await;
+
+    match result {
+        Either::Left(_) => Err(Error::Timeout),
+        Either::Right(res) => Ok(res),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::{future, time::Duration};
+
+    #[test]
+    fn test_timeout() {
+        smol::block_on(async move {
+            let fut = future::pending::<()>();
+            assert!(timeout(Duration::from_millis(10), fut).await.is_err());
+
+            let fut = smol::Timer::after(Duration::from_millis(10));
+            assert!(timeout(Duration::from_millis(50), fut).await.is_ok())
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/crypto/key_pair.rs.html b/src/karyon_core/crypto/key_pair.rs.html new file mode 100644 index 00000000..d18346cf --- /dev/null +++ b/src/karyon_core/crypto/key_pair.rs.html @@ -0,0 +1,290 @@ +key_pair.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+
use ed25519_dalek::{Signer as _, Verifier as _};
+use rand::rngs::OsRng;
+
+use crate::{error::Error, Result};
+
+/// key cryptography type
+pub enum KeyPairType {
+    Ed25519,
+}
+
+/// A Secret key
+pub struct SecretKey(Vec<u8>);
+
+#[derive(Clone)]
+pub enum KeyPair {
+    Ed25519(Ed25519KeyPair),
+}
+
+impl KeyPair {
+    /// Generate a new random keypair.
+    pub fn generate(kp_type: &KeyPairType) -> Self {
+        match kp_type {
+            KeyPairType::Ed25519 => Self::Ed25519(Ed25519KeyPair::generate()),
+        }
+    }
+
+    /// Sign a message using the private key.
+    pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
+        match self {
+            KeyPair::Ed25519(kp) => kp.sign(msg),
+        }
+    }
+
+    /// Get the public key of this keypair.
+    pub fn public(&self) -> PublicKey {
+        match self {
+            KeyPair::Ed25519(kp) => kp.public(),
+        }
+    }
+
+    /// Get the secret key of this keypair.
+    pub fn secret(&self) -> SecretKey {
+        match self {
+            KeyPair::Ed25519(kp) => kp.secret(),
+        }
+    }
+}
+
+/// An extension trait, adding essential methods to all [`KeyPair`] types.
+trait KeyPairExt {
+    /// Sign a message using the private key.
+    fn sign(&self, msg: &[u8]) -> Vec<u8>;
+
+    /// Get the public key of this keypair.
+    fn public(&self) -> PublicKey;
+
+    /// Get the secret key of this keypair.
+    fn secret(&self) -> SecretKey;
+}
+
+#[derive(Clone)]
+pub struct Ed25519KeyPair(ed25519_dalek::SigningKey);
+
+impl Ed25519KeyPair {
+    fn generate() -> Self {
+        Self(ed25519_dalek::SigningKey::generate(&mut OsRng))
+    }
+}
+
+impl KeyPairExt for Ed25519KeyPair {
+    fn sign(&self, msg: &[u8]) -> Vec<u8> {
+        self.0.sign(msg).to_bytes().to_vec()
+    }
+
+    fn public(&self) -> PublicKey {
+        PublicKey::Ed25519(Ed25519PublicKey(self.0.verifying_key()))
+    }
+
+    fn secret(&self) -> SecretKey {
+        SecretKey(self.0.to_bytes().to_vec())
+    }
+}
+
+#[derive(Debug)]
+pub enum PublicKey {
+    Ed25519(Ed25519PublicKey),
+}
+
+impl PublicKey {
+    pub fn from_bytes(kp_type: &KeyPairType, pk: &[u8]) -> Result<Self> {
+        match kp_type {
+            KeyPairType::Ed25519 => Ok(Self::Ed25519(Ed25519PublicKey::from_bytes(pk)?)),
+        }
+    }
+
+    pub fn as_bytes(&self) -> &[u8] {
+        match self {
+            Self::Ed25519(pk) => pk.as_bytes(),
+        }
+    }
+
+    /// Verify a signature on a message with this public key.
+    pub fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> {
+        match self {
+            Self::Ed25519(pk) => pk.verify(msg, signature),
+        }
+    }
+}
+
+/// An extension trait, adding essential methods to all [`PublicKey`] types.
+trait PublicKeyExt {
+    fn as_bytes(&self) -> &[u8];
+
+    /// Verify a signature on a message with this public key.
+    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()>;
+}
+
+#[derive(Debug)]
+pub struct Ed25519PublicKey(ed25519_dalek::VerifyingKey);
+
+impl Ed25519PublicKey {
+    pub fn from_bytes(pk: &[u8]) -> Result<Self> {
+        let pk_bytes: [u8; 32] = pk
+            .try_into()
+            .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 32]"))?;
+
+        Ok(Self(ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)?))
+    }
+}
+
+impl PublicKeyExt for Ed25519PublicKey {
+    fn as_bytes(&self) -> &[u8] {
+        self.0.as_bytes()
+    }
+
+    fn verify(&self, msg: &[u8], signature: &[u8]) -> Result<()> {
+        let sig_bytes: [u8; 64] = signature
+            .try_into()
+            .map_err(|_| Error::TryInto("Failed to convert slice to [u8; 64]"))?;
+        self.0
+            .verify(msg, &ed25519_dalek::Signature::from_bytes(&sig_bytes))?;
+        Ok(())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/crypto/mod.rs.html b/src/karyon_core/crypto/mod.rs.html new file mode 100644 index 00000000..bbe62ccf --- /dev/null +++ b/src/karyon_core/crypto/mod.rs.html @@ -0,0 +1,8 @@ +mod.rs - source +
1
+2
+3
+
mod key_pair;
+
+pub use key_pair::{KeyPair, KeyPairType, PublicKey, SecretKey};
+
\ No newline at end of file diff --git a/src/karyon_core/error.rs.html b/src/karyon_core/error.rs.html new file mode 100644 index 00000000..9ee2c4b8 --- /dev/null +++ b/src/karyon_core/error.rs.html @@ -0,0 +1,82 @@ +error.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+
use thiserror::Error as ThisError;
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(ThisError, Debug)]
+pub enum Error {
+    #[error(transparent)]
+    IO(#[from] std::io::Error),
+
+    #[error("TryInto Error: {0}")]
+    TryInto(&'static str),
+
+    #[error("Timeout Error")]
+    Timeout,
+
+    #[error("Path Not Found Error: {0}")]
+    PathNotFound(&'static str),
+
+    #[cfg(feature = "crypto")]
+    #[error(transparent)]
+    Ed25519(#[from] ed25519_dalek::ed25519::Error),
+
+    #[error("Channel Send Error: {0}")]
+    ChannelSend(String),
+
+    #[error(transparent)]
+    ChannelRecv(#[from] smol::channel::RecvError),
+
+    #[error(transparent)]
+    BincodeDecode(#[from] bincode::error::DecodeError),
+
+    #[error(transparent)]
+    BincodeEncode(#[from] bincode::error::EncodeError),
+}
+
+impl<T> From<smol::channel::SendError<T>> for Error {
+    fn from(error: smol::channel::SendError<T>) -> Self {
+        Error::ChannelSend(error.to_string())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/event.rs.html b/src/karyon_core/event.rs.html new file mode 100644 index 00000000..7605fb85 --- /dev/null +++ b/src/karyon_core/event.rs.html @@ -0,0 +1,904 @@ +event.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+
use std::{
+    any::Any,
+    collections::HashMap,
+    marker::PhantomData,
+    sync::{Arc, Weak},
+};
+
+use chrono::{DateTime, Utc};
+use log::{error, trace};
+use smol::{
+    channel::{Receiver, Sender},
+    lock::Mutex,
+};
+
+use crate::{util::random_16, Result};
+
+pub type ArcEventSys<T> = Arc<EventSys<T>>;
+pub type WeakEventSys<T> = Weak<EventSys<T>>;
+pub type EventListenerID = u16;
+
+type Listeners<T> = HashMap<T, HashMap<String, HashMap<EventListenerID, Sender<Event>>>>;
+
+/// EventSys supports event emission to registered listeners based on topics.
+/// # Example
+///
+/// ```
+/// use karyon_core::event::{EventSys, EventValueTopic, EventValue};
+///
+///  async {
+///     let event_sys = EventSys::new();
+///
+///     #[derive(Hash, PartialEq, Eq, Debug, Clone)]
+///     enum Topic {
+///         TopicA,
+///         TopicB,
+///     }
+///
+///     #[derive(Clone, Debug, PartialEq)]
+///     struct A(usize);
+///
+///    impl EventValue for A {
+///         fn id() -> &'static str {
+///             "A"
+///         }
+///     }
+///
+///     let listener = event_sys.register::<A>(&Topic::TopicA).await;
+///
+///     event_sys.emit_by_topic(&Topic::TopicA, &A(3)) .await;
+///     let msg: A = listener.recv().await.unwrap();
+///
+///     #[derive(Clone, Debug, PartialEq)]
+///     struct B(usize);
+///
+///     impl EventValue for B {
+///         fn id() -> &'static str {
+///             "B"
+///         }
+///     }
+///
+///     impl EventValueTopic for B {
+///         type Topic = Topic;
+///         fn topic() -> Self::Topic{
+///             Topic::TopicB
+///         }
+///     }
+///
+///     let listener = event_sys.register::<B>(&Topic::TopicB).await;
+///
+///     event_sys.emit(&B(3)) .await;
+///     let msg: B = listener.recv().await.unwrap();
+///
+///     // ....
+///  };
+///
+/// ```
+///
+pub struct EventSys<T> {
+    listeners: Mutex<Listeners<T>>,
+}
+
+impl<T> EventSys<T>
+where
+    T: std::hash::Hash + Eq + std::fmt::Debug + Clone,
+{
+    /// Creates a new `EventSys`
+    pub fn new() -> ArcEventSys<T> {
+        Arc::new(Self {
+            listeners: Mutex::new(HashMap::new()),
+        })
+    }
+
+    /// Emits an event to the listeners.
+    ///
+    /// The event must implement the `EventValueTopic` trait to indicate the
+    /// topic of the event. Otherwise, you can use `emit_by_topic()`.
+    pub async fn emit<E: EventValueTopic<Topic = T> + Clone>(&self, value: &E) {
+        let topic = E::topic();
+        self.emit_by_topic(&topic, value).await;
+    }
+
+    /// Emits an event to the listeners.
+    pub async fn emit_by_topic<E: EventValueAny + EventValue + Clone>(&self, topic: &T, value: &E) {
+        let value: Arc<dyn EventValueAny> = Arc::new(value.clone());
+        let event = Event::new(value);
+
+        let mut topics = self.listeners.lock().await;
+
+        if !topics.contains_key(topic) {
+            error!("Failed to emit an event to a non-existent topic");
+            return;
+        }
+
+        let event_ids = topics.get_mut(topic).unwrap();
+        let event_id = E::id().to_string();
+
+        if !event_ids.contains_key(&event_id) {
+            error!("Failed to emit an event to a non-existent event id");
+            return;
+        }
+
+        let mut failed_listeners = vec![];
+
+        let listeners = event_ids.get_mut(&event_id).unwrap();
+        for (listener_id, listener) in listeners.iter() {
+            if let Err(err) = listener.send(event.clone()).await {
+                trace!("Failed to emit event for topic {:?}: {}", topic, err);
+                failed_listeners.push(*listener_id);
+            }
+        }
+
+        for listener_id in failed_listeners.iter() {
+            listeners.remove(listener_id);
+        }
+    }
+
+    /// Registers a new event listener for the given topic.
+    pub async fn register<E: EventValueAny + EventValue + Clone>(
+        self: &Arc<Self>,
+        topic: &T,
+    ) -> EventListener<T, E> {
+        let chan = smol::channel::unbounded();
+
+        let topics = &mut self.listeners.lock().await;
+
+        if !topics.contains_key(topic) {
+            topics.insert(topic.clone(), HashMap::new());
+        }
+
+        let event_ids = topics.get_mut(topic).unwrap();
+        let event_id = E::id().to_string();
+
+        if !event_ids.contains_key(&event_id) {
+            event_ids.insert(event_id.clone(), HashMap::new());
+        }
+
+        let listeners = event_ids.get_mut(&event_id).unwrap();
+
+        let mut listener_id = random_16();
+        while listeners.contains_key(&listener_id) {
+            listener_id = random_16();
+        }
+
+        let listener =
+            EventListener::new(listener_id, Arc::downgrade(self), chan.1, &event_id, topic);
+
+        listeners.insert(listener_id, chan.0);
+
+        listener
+    }
+
+    /// Removes the event listener attached to the given topic.
+    async fn remove(&self, topic: &T, event_id: &str, listener_id: &EventListenerID) {
+        let topics = &mut self.listeners.lock().await;
+        if !topics.contains_key(topic) {
+            error!("Failed to remove a non-existent topic");
+            return;
+        }
+
+        let event_ids = topics.get_mut(topic).unwrap();
+        if !event_ids.contains_key(event_id) {
+            error!("Failed to remove a non-existent event id");
+            return;
+        }
+
+        let listeners = event_ids.get_mut(event_id).unwrap();
+        if listeners.remove(listener_id).is_none() {
+            error!("Failed to remove a non-existent event listener");
+        }
+    }
+}
+
+/// EventListener listens for and receives events from the [`EventSys`].
+pub struct EventListener<T, E> {
+    id: EventListenerID,
+    recv_chan: Receiver<Event>,
+    event_sys: WeakEventSys<T>,
+    event_id: String,
+    topic: T,
+    phantom: PhantomData<E>,
+}
+
+impl<T, E> EventListener<T, E>
+where
+    T: std::hash::Hash + Eq + Clone + std::fmt::Debug,
+    E: EventValueAny + Clone + EventValue,
+{
+    /// Create a new event listener.
+    fn new(
+        id: EventListenerID,
+        event_sys: WeakEventSys<T>,
+        recv_chan: Receiver<Event>,
+        event_id: &str,
+        topic: &T,
+    ) -> EventListener<T, E> {
+        Self {
+            id,
+            recv_chan,
+            event_sys,
+            event_id: event_id.to_string(),
+            topic: topic.clone(),
+            phantom: PhantomData,
+        }
+    }
+
+    /// Receive the next event.
+    pub async fn recv(&self) -> Result<E> {
+        match self.recv_chan.recv().await {
+            Ok(event) => match ((*event.value).value_as_any()).downcast_ref::<E>() {
+                Some(v) => Ok(v.clone()),
+                None => unreachable!("Error when attempting to downcast the event value."),
+            },
+            Err(err) => {
+                error!("Failed to receive new event: {err}");
+                self.cancel().await;
+                Err(err.into())
+            }
+        }
+    }
+
+    /// Cancels the listener and removes it from the `EventSys`.
+    pub async fn cancel(&self) {
+        self.event_sys()
+            .remove(&self.topic, &self.event_id, &self.id)
+            .await;
+    }
+
+    /// Returns the topic for this event listener.
+    pub async fn topic(&self) -> &T {
+        &self.topic
+    }
+
+    /// Returns the event id for this event listener.
+    pub async fn event_id(&self) -> &String {
+        &self.event_id
+    }
+
+    fn event_sys(&self) -> ArcEventSys<T> {
+        self.event_sys.upgrade().unwrap()
+    }
+}
+
+/// An event within the [`EventSys`].
+#[derive(Clone, Debug)]
+pub struct Event {
+    /// The time at which the event was created.
+    created_at: DateTime<Utc>,
+    /// The value of the Event.
+    value: Arc<dyn EventValueAny>,
+}
+
+impl Event {
+    /// Creates a new Event.
+    pub fn new(value: Arc<dyn EventValueAny>) -> Self {
+        Self {
+            created_at: Utc::now(),
+            value,
+        }
+    }
+}
+
+impl std::fmt::Display for Event {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        write!(f, "{}: {:?}", self.created_at, self.value)
+    }
+}
+
+pub trait EventValueAny: Any + Send + Sync + std::fmt::Debug {
+    fn value_as_any(&self) -> &dyn Any;
+}
+
+impl<T: Send + Sync + std::fmt::Debug + Any> EventValueAny for T {
+    fn value_as_any(&self) -> &dyn Any {
+        self
+    }
+}
+
+pub trait EventValue: EventValueAny {
+    fn id() -> &'static str
+    where
+        Self: Sized;
+}
+
+pub trait EventValueTopic: EventValueAny + EventValue {
+    type Topic;
+    fn topic() -> Self::Topic
+    where
+        Self: Sized;
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[derive(Hash, PartialEq, Eq, Debug, Clone)]
+    enum Topic {
+        TopicA,
+        TopicB,
+        TopicC,
+        TopicD,
+        TopicE,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct A {
+        a_value: usize,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct B {
+        b_value: usize,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct C {
+        c_value: usize,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct D {
+        d_value: usize,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct E {
+        e_value: usize,
+    }
+
+    #[derive(Clone, Debug, PartialEq)]
+    struct F {
+        f_value: usize,
+    }
+
+    impl EventValue for A {
+        fn id() -> &'static str {
+            "A"
+        }
+    }
+
+    impl EventValue for B {
+        fn id() -> &'static str {
+            "B"
+        }
+    }
+
+    impl EventValue for C {
+        fn id() -> &'static str {
+            "C"
+        }
+    }
+
+    impl EventValue for D {
+        fn id() -> &'static str {
+            "D"
+        }
+    }
+
+    impl EventValue for E {
+        fn id() -> &'static str {
+            "E"
+        }
+    }
+
+    impl EventValue for F {
+        fn id() -> &'static str {
+            "F"
+        }
+    }
+
+    impl EventValueTopic for C {
+        type Topic = Topic;
+        fn topic() -> Self::Topic {
+            Topic::TopicC
+        }
+    }
+
+    #[test]
+    fn test_event_sys() {
+        smol::block_on(async move {
+            let event_sys = EventSys::<Topic>::new();
+
+            let a_listener = event_sys.register::<A>(&Topic::TopicA).await;
+            let b_listener = event_sys.register::<B>(&Topic::TopicB).await;
+
+            event_sys
+                .emit_by_topic(&Topic::TopicA, &A { a_value: 3 })
+                .await;
+            event_sys
+                .emit_by_topic(&Topic::TopicB, &B { b_value: 5 })
+                .await;
+
+            let msg = a_listener.recv().await.unwrap();
+            assert_eq!(msg, A { a_value: 3 });
+
+            let msg = b_listener.recv().await.unwrap();
+            assert_eq!(msg, B { b_value: 5 });
+
+            // register the same event type to different topics
+            let c_listener = event_sys.register::<C>(&Topic::TopicC).await;
+            let d_listener = event_sys.register::<C>(&Topic::TopicD).await;
+
+            event_sys.emit(&C { c_value: 10 }).await;
+            let msg = c_listener.recv().await.unwrap();
+            assert_eq!(msg, C { c_value: 10 });
+
+            event_sys
+                .emit_by_topic(&Topic::TopicD, &C { c_value: 10 })
+                .await;
+            let msg = d_listener.recv().await.unwrap();
+            assert_eq!(msg, C { c_value: 10 });
+
+            // register different event types to the same topic
+            let e_listener = event_sys.register::<E>(&Topic::TopicE).await;
+            let f_listener = event_sys.register::<F>(&Topic::TopicE).await;
+
+            event_sys
+                .emit_by_topic(&Topic::TopicE, &E { e_value: 5 })
+                .await;
+
+            let msg = e_listener.recv().await.unwrap();
+            assert_eq!(msg, E { e_value: 5 });
+
+            event_sys
+                .emit_by_topic(&Topic::TopicE, &F { f_value: 5 })
+                .await;
+
+            let msg = f_listener.recv().await.unwrap();
+            assert_eq!(msg, F { f_value: 5 });
+        });
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/lib.rs.html b/src/karyon_core/lib.rs.html new file mode 100644 index 00000000..f6ac0848 --- /dev/null +++ b/src/karyon_core/lib.rs.html @@ -0,0 +1,62 @@ +lib.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+
/// A set of helper tools and functions.
+pub mod util;
+
+/// A module containing async utilities that work with the
+/// [`smol`](https://github.com/smol-rs/smol) async runtime.
+pub mod async_util;
+
+/// Represents karyon's Core Error.
+pub mod error;
+
+/// [`event::EventSys`] implementation.
+pub mod event;
+
+/// A simple publish-subscribe system [`Read More`](./pubsub/struct.Publisher.html)
+pub mod pubsub;
+
+#[cfg(feature = "crypto")]
+/// Collects common cryptographic tools
+pub mod crypto;
+
+use smol::Executor as SmolEx;
+use std::sync::Arc;
+
+/// A pointer to an Executor
+pub type Executor<'a> = Arc<SmolEx<'a>>;
+
+/// A Global Executor
+pub type GlobalExecutor = Arc<SmolEx<'static>>;
+
+use error::Result;
+
\ No newline at end of file diff --git a/src/karyon_core/pubsub.rs.html b/src/karyon_core/pubsub.rs.html new file mode 100644 index 00000000..2ce568bc --- /dev/null +++ b/src/karyon_core/pubsub.rs.html @@ -0,0 +1,232 @@ +pubsub.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+
use std::{collections::HashMap, sync::Arc};
+
+use log::error;
+use smol::lock::Mutex;
+
+use crate::{util::random_16, Result};
+
+pub type ArcPublisher<T> = Arc<Publisher<T>>;
+pub type SubscriptionID = u16;
+
+/// A simple publish-subscribe system.
+// # Example
+///
+/// ```
+/// use karyon_core::pubsub::{Publisher};
+///
+///  async {
+///     let publisher = Publisher::new();
+///     
+///     let sub = publisher.subscribe().await;
+///     
+///     publisher.notify(&String::from("MESSAGE")).await;
+///
+///     let msg = sub.recv().await;
+///
+///     // ....
+///  };
+///  
+/// ```
+pub struct Publisher<T> {
+    subs: Mutex<HashMap<SubscriptionID, smol::channel::Sender<T>>>,
+}
+
+impl<T: Clone> Publisher<T> {
+    /// Creates a new Publisher
+    pub fn new() -> ArcPublisher<T> {
+        Arc::new(Self {
+            subs: Mutex::new(HashMap::new()),
+        })
+    }
+
+    /// Subscribe and return a Subscription
+    pub async fn subscribe(self: &Arc<Self>) -> Subscription<T> {
+        let mut subs = self.subs.lock().await;
+
+        let chan = smol::channel::unbounded();
+
+        let mut sub_id = random_16();
+
+        // While the SubscriptionID already exists, generate a new one
+        while subs.contains_key(&sub_id) {
+            sub_id = random_16();
+        }
+
+        let sub = Subscription::new(sub_id, self.clone(), chan.1);
+        subs.insert(sub_id, chan.0);
+
+        sub
+    }
+
+    /// Unsubscribe from the Publisher
+    pub async fn unsubscribe(self: &Arc<Self>, id: &SubscriptionID) {
+        self.subs.lock().await.remove(id);
+    }
+
+    /// Notify all subscribers
+    pub async fn notify(self: &Arc<Self>, value: &T) {
+        let mut subs = self.subs.lock().await;
+        let mut closed_subs = vec![];
+
+        for (sub_id, sub) in subs.iter() {
+            if let Err(err) = sub.send(value.clone()).await {
+                error!("failed to notify {}: {}", sub_id, err);
+                closed_subs.push(*sub_id);
+            }
+        }
+
+        for sub_id in closed_subs.iter() {
+            subs.remove(sub_id);
+        }
+    }
+}
+
+// Subscription
+pub struct Subscription<T> {
+    id: SubscriptionID,
+    recv_chan: smol::channel::Receiver<T>,
+    publisher: ArcPublisher<T>,
+}
+
+impl<T: Clone> Subscription<T> {
+    /// Creates a new Subscription
+    pub fn new(
+        id: SubscriptionID,
+        publisher: ArcPublisher<T>,
+        recv_chan: smol::channel::Receiver<T>,
+    ) -> Subscription<T> {
+        Self {
+            id,
+            recv_chan,
+            publisher,
+        }
+    }
+
+    /// Receive a message from the Publisher
+    pub async fn recv(&self) -> Result<T> {
+        let msg = self.recv_chan.recv().await?;
+        Ok(msg)
+    }
+
+    /// Unsubscribe from the Publisher
+    pub async fn unsubscribe(&self) {
+        self.publisher.unsubscribe(&self.id).await;
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_core/util/decode.rs.html b/src/karyon_core/util/decode.rs.html new file mode 100644 index 00000000..e1ab47c3 --- /dev/null +++ b/src/karyon_core/util/decode.rs.html @@ -0,0 +1,22 @@ +decode.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+
use bincode::Decode;
+
+use crate::Result;
+
+/// Decodes a given type `T` from the given slice. returns the decoded value
+/// along with the number of bytes read.
+pub fn decode<T: Decode>(src: &[u8]) -> Result<(T, usize)> {
+    let (result, bytes_read) = bincode::decode_from_slice(src, bincode::config::standard())?;
+    Ok((result, bytes_read))
+}
+
\ No newline at end of file diff --git a/src/karyon_core/util/encode.rs.html b/src/karyon_core/util/encode.rs.html new file mode 100644 index 00000000..71bc6668 --- /dev/null +++ b/src/karyon_core/util/encode.rs.html @@ -0,0 +1,32 @@ +encode.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+
use bincode::Encode;
+
+use crate::Result;
+
+/// Encode the given type `T` into a `Vec<u8>`.
+pub fn encode<T: Encode>(msg: &T) -> Result<Vec<u8>> {
+    let vec = bincode::encode_to_vec(msg, bincode::config::standard())?;
+    Ok(vec)
+}
+
+/// Encode the given type `T` into the given slice..
+pub fn encode_into_slice<T: Encode>(msg: &T, dst: &mut [u8]) -> Result<()> {
+    bincode::encode_into_slice(msg, dst, bincode::config::standard())?;
+    Ok(())
+}
+
\ No newline at end of file diff --git a/src/karyon_core/util/mod.rs.html b/src/karyon_core/util/mod.rs.html new file mode 100644 index 00000000..5800a60a --- /dev/null +++ b/src/karyon_core/util/mod.rs.html @@ -0,0 +1,40 @@ +mod.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+
mod decode;
+mod encode;
+mod path;
+
+pub use decode::decode;
+pub use encode::{encode, encode_into_slice};
+pub use path::{home_dir, tilde_expand};
+
+use rand::{rngs::OsRng, Rng};
+
+/// Generates and returns a random u32 using `rand::rngs::OsRng`.
+pub fn random_32() -> u32 {
+    OsRng.gen()
+}
+
+/// Generates and returns a random u16 using `rand::rngs::OsRng`.
+pub fn random_16() -> u16 {
+    OsRng.gen()
+}
+
\ No newline at end of file diff --git a/src/karyon_core/util/path.rs.html b/src/karyon_core/util/path.rs.html new file mode 100644 index 00000000..3c45c9c1 --- /dev/null +++ b/src/karyon_core/util/path.rs.html @@ -0,0 +1,80 @@ +path.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+
use std::path::PathBuf;
+
+use crate::{error::Error, Result};
+
+/// Returns the user's home directory as a `PathBuf`.
+#[allow(dead_code)]
+pub fn home_dir() -> Result<PathBuf> {
+    dirs::home_dir().ok_or(Error::PathNotFound("Home dir not found"))
+}
+
+/// Expands a tilde (~) in a path and returns the expanded `PathBuf`.
+#[allow(dead_code)]
+pub fn tilde_expand(path: &str) -> Result<PathBuf> {
+    match path {
+        "~" => home_dir(),
+        p if p.starts_with("~/") => Ok(home_dir()?.join(&path[2..])),
+        _ => Ok(PathBuf::from(path)),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_tilde_expand() {
+        let path = "~/src";
+        let expanded_path = dirs::home_dir().unwrap().join("src");
+        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
+
+        let path = "~";
+        let expanded_path = dirs::home_dir().unwrap();
+        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
+
+        let path = "";
+        let expanded_path = PathBuf::from("");
+        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/client.rs.html b/src/karyon_jsonrpc/client.rs.html new file mode 100644 index 00000000..4cc3bea8 --- /dev/null +++ b/src/karyon_jsonrpc/client.rs.html @@ -0,0 +1,158 @@ +client.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+
use log::debug;
+use serde::{de::DeserializeOwned, Serialize};
+
+use karyon_core::util::random_32;
+use karyon_net::ToConn;
+
+use crate::{
+    codec::{Codec, CodecConfig},
+    message, Error, Result, JSONRPC_VERSION,
+};
+
+/// Represents client config
+#[derive(Default)]
+pub struct ClientConfig {
+    pub timeout: Option<u64>,
+}
+
+/// Represents an RPC client
+pub struct Client {
+    codec: Codec,
+    config: ClientConfig,
+}
+
+impl Client {
+    /// Creates a new RPC client by passing a Tcp, Unix, or Tls connection.
+    pub fn new<C: ToConn>(conn: C, config: ClientConfig) -> Self {
+        let codec_config = CodecConfig {
+            max_allowed_buffer_size: 0,
+            ..Default::default()
+        };
+        let codec = Codec::new(conn.to_conn(), codec_config);
+        Self { codec, config }
+    }
+
+    /// Calls the provided method, waits for the response, and returns the result.
+    pub async fn call<T: Serialize + DeserializeOwned, V: DeserializeOwned>(
+        &self,
+        method: &str,
+        params: T,
+    ) -> Result<V> {
+        let id = serde_json::json!(random_32());
+
+        let request = message::Request {
+            jsonrpc: JSONRPC_VERSION.to_string(),
+            id,
+            method: method.to_string(),
+            params: serde_json::json!(params),
+        };
+
+        let mut payload = serde_json::to_vec(&request)?;
+        payload.push(b'\n');
+        self.codec.write_all(&payload).await?;
+        debug!("--> {request}");
+
+        let mut buffer = vec![];
+        if let Some(t) = self.config.timeout {
+            self.codec.read_until_with_timeout(&mut buffer, t).await?;
+        } else {
+            self.codec.read_until(&mut buffer).await?;
+        };
+
+        let response = serde_json::from_slice::<message::Response>(&buffer)?;
+        debug!("<-- {response}");
+
+        if let Some(error) = response.error {
+            return Err(Error::CallError(error.code, error.message));
+        }
+
+        if response.id.is_none() || response.id.unwrap() != request.id {
+            return Err(Error::InvalidMsg("Invalid response id"));
+        }
+
+        match response.result {
+            Some(result) => Ok(serde_json::from_value::<V>(result)?),
+            None => Err(Error::InvalidMsg("Invalid response result")),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/codec.rs.html b/src/karyon_jsonrpc/codec.rs.html new file mode 100644 index 00000000..bf84ab13 --- /dev/null +++ b/src/karyon_jsonrpc/codec.rs.html @@ -0,0 +1,202 @@ +codec.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+
use memchr::memchr;
+
+use karyon_core::async_util::timeout;
+use karyon_net::Conn;
+
+use crate::{Error, Result};
+
+const DEFAULT_BUFFER_SIZE: usize = 1024;
+const DEFAULT_MAX_ALLOWED_BUFFER_SIZE: usize = 1024 * 1024; // 1MB
+
+// TODO: Add unit tests for Codec's functions.
+
+/// Represents Codec config
+#[derive(Clone)]
+pub struct CodecConfig {
+    pub default_buffer_size: usize,
+    /// The maximum allowed buffer size to receive a message. If set to zero,
+    /// there will be no size limit.
+    pub max_allowed_buffer_size: usize,
+}
+
+impl Default for CodecConfig {
+    fn default() -> Self {
+        Self {
+            default_buffer_size: DEFAULT_BUFFER_SIZE,
+            max_allowed_buffer_size: DEFAULT_MAX_ALLOWED_BUFFER_SIZE,
+        }
+    }
+}
+
+pub struct Codec {
+    conn: Conn,
+    config: CodecConfig,
+}
+
+impl Codec {
+    /// Creates a new Codec
+    pub fn new(conn: Conn, config: CodecConfig) -> Self {
+        Self { conn, config }
+    }
+
+    /// Read all bytes into `buffer` until the `0x0A` byte or EOF is
+    /// reached.
+    ///
+    /// If successful, this function will return the total number of bytes read.
+    pub async fn read_until(&self, buffer: &mut Vec<u8>) -> Result<usize> {
+        let delim = b'\n';
+
+        let mut read = 0;
+
+        loop {
+            let mut tmp_buf = vec![0; self.config.default_buffer_size];
+            let n = self.conn.read(&mut tmp_buf).await?;
+            if n == 0 {
+                return Err(Error::IO(std::io::ErrorKind::UnexpectedEof.into()));
+            }
+
+            match memchr(delim, &tmp_buf) {
+                Some(i) => {
+                    buffer.extend_from_slice(&tmp_buf[..=i]);
+                    read += i + 1;
+                    break;
+                }
+                None => {
+                    buffer.extend_from_slice(&tmp_buf);
+                    read += tmp_buf.len();
+                }
+            }
+
+            if self.config.max_allowed_buffer_size != 0
+                && buffer.len() == self.config.max_allowed_buffer_size
+            {
+                return Err(Error::InvalidMsg(
+                    "Message exceeds the maximum allowed size",
+                ));
+            }
+        }
+
+        Ok(read)
+    }
+
+    /// Writes an entire buffer into the given connection.
+    pub async fn write_all(&self, mut buf: &[u8]) -> Result<()> {
+        while !buf.is_empty() {
+            let n = self.conn.write(buf).await?;
+            let (_, rest) = std::mem::take(&mut buf).split_at(n);
+            buf = rest;
+
+            if n == 0 {
+                return Err(Error::IO(std::io::ErrorKind::UnexpectedEof.into()));
+            }
+        }
+
+        Ok(())
+    }
+
+    pub async fn read_until_with_timeout(&self, buffer: &mut Vec<u8>, t: u64) -> Result<usize> {
+        timeout(std::time::Duration::from_secs(t), self.read_until(buffer)).await?
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/error.rs.html b/src/karyon_jsonrpc/error.rs.html new file mode 100644 index 00000000..883cb630 --- /dev/null +++ b/src/karyon_jsonrpc/error.rs.html @@ -0,0 +1,70 @@ +error.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+
use thiserror::Error as ThisError;
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Represents karyon's jsonrpc Error.
+#[derive(ThisError, Debug)]
+pub enum Error {
+    #[error(transparent)]
+    IO(#[from] std::io::Error),
+
+    #[error("Call Error: code: {0} msg: {1}")]
+    CallError(i32, String),
+
+    #[error("RPC Method Error:  code: {0} msg: {1}")]
+    RPCMethodError(i32, &'static str),
+
+    #[error("Invalid Params: {0}")]
+    InvalidParams(&'static str),
+
+    #[error("Invalid Request: {0}")]
+    InvalidRequest(&'static str),
+
+    #[error(transparent)]
+    ParseJSON(#[from] serde_json::Error),
+
+    #[error("Invalid Message Error: {0}")]
+    InvalidMsg(&'static str),
+
+    #[error(transparent)]
+    KaryonCore(#[from] karyon_core::error::Error),
+
+    #[error(transparent)]
+    KaryonNet(#[from] karyon_net::NetError),
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/lib.rs.html b/src/karyon_jsonrpc/lib.rs.html new file mode 100644 index 00000000..18adf87f --- /dev/null +++ b/src/karyon_jsonrpc/lib.rs.html @@ -0,0 +1,156 @@ +lib.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+
//! A fast and lightweight async implementation of [JSON-RPC
+//! 2.0](https://www.jsonrpc.org/specification), supporting the Tcp and Unix protocols.
+//!
+//! # Example
+//!
+//! ```
+//! use std::sync::Arc;
+//!
+//! use serde_json::Value;
+//! use smol::net::{TcpStream, TcpListener};
+//!
+//! use karyon_jsonrpc::{JsonRPCError, Server, Client, register_service, ServerConfig, ClientConfig};
+//!
+//! struct HelloWorld {}
+//!
+//! impl HelloWorld {
+//!     async fn say_hello(&self, params: Value) -> Result<Value, JsonRPCError> {
+//!         let msg: String = serde_json::from_value(params)?;
+//!         Ok(serde_json::json!(format!("Hello {msg}!")))
+//!     }
+//!
+//!     async fn foo(&self, params: Value) -> Result<Value, JsonRPCError> {
+//!         Ok(serde_json::json!("foo!"))
+//!     }
+//!
+//!     async fn bar(&self, params: Value) -> Result<Value, JsonRPCError> {
+//!         Ok(serde_json::json!("bar!"))
+//!     }
+//! }
+//!
+//! // Server
+//! async {
+//!     let ex = Arc::new(smol::Executor::new());
+//!
+//!     // Creates a new server
+//!     let listener = TcpListener::bind("127.0.0.1:60000").await.unwrap();
+//!     let config = ServerConfig::default();
+//!     let server = Server::new(listener, config, ex.clone());
+//!
+//!     // Register the HelloWorld service
+//!     register_service!(HelloWorld, say_hello, foo, bar);
+//!     server.attach_service(HelloWorld{});
+//!
+//!     // Starts the server
+//!     ex.run(server.start());
+//! };
+//!
+//! // Client
+//! async {
+//!
+//!     // Creates a new client
+//!     let conn = TcpStream::connect("127.0.0.1:60000").await.unwrap();
+//!     let config = ClientConfig::default();
+//!     let client = Client::new(conn, config);
+//!
+//!     let result: String = client.call("HelloWorld.say_hello", "world".to_string()).await.unwrap();
+//! };
+//!
+//! ```
+
+mod client;
+mod codec;
+mod error;
+pub mod message;
+mod server;
+mod service;
+
+pub use client::{Client, ClientConfig};
+pub use codec::CodecConfig;
+pub use error::Error as JsonRPCError;
+pub use server::{Server, ServerConfig};
+pub use service::{RPCMethod, RPCService};
+
+pub use karyon_net::Endpoint;
+
+const JSONRPC_VERSION: &str = "2.0";
+use error::{Error, Result};
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/message.rs.html b/src/karyon_jsonrpc/message.rs.html new file mode 100644 index 00000000..479e658c --- /dev/null +++ b/src/karyon_jsonrpc/message.rs.html @@ -0,0 +1,184 @@ +message.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+
use serde::{Deserialize, Serialize};
+
+/// Parse error: Invalid JSON was received by the server.
+pub const PARSE_ERROR_CODE: i32 = -32700;
+
+/// Invalid request: The JSON sent is not a valid Request object.
+pub const INVALID_REQUEST_ERROR_CODE: i32 = -32600;
+
+/// Method not found: The method does not exist / is not available.
+pub const METHOD_NOT_FOUND_ERROR_CODE: i32 = -32601;
+
+/// Invalid params: Invalid method parameter(s).
+pub const INVALID_PARAMS_ERROR_CODE: i32 = -32602;
+
+/// Internal error: Internal JSON-RPC error.
+pub const INTERNAL_ERROR_CODE: i32 = -32603;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Request {
+    pub jsonrpc: String,
+    pub method: String,
+    pub params: serde_json::Value,
+    pub id: serde_json::Value,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Response {
+    pub jsonrpc: String,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub result: Option<serde_json::Value>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub error: Option<Error>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub id: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Error {
+    pub code: i32,
+    pub message: String,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub data: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Notification {
+    pub jsonrpc: String,
+    pub method: String,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub params: Option<serde_json::Value>,
+}
+
+impl std::fmt::Display for Request {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "{{jsonrpc: {}, method: {}, params: {:?}, id: {:?}}}",
+            self.jsonrpc, self.method, self.params, self.id
+        )
+    }
+}
+
+impl std::fmt::Display for Response {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "{{jsonrpc: {}, result': {:?}, error: {:?} , id: {:?}}}",
+            self.jsonrpc, self.result, self.error, self.id
+        )
+    }
+}
+
+impl std::fmt::Display for Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "RpcError {{ code: {}, message: {}, data: {:?} }} ",
+            self.code, self.message, self.data
+        )
+    }
+}
+
+impl std::fmt::Display for Notification {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(
+            f,
+            "{{jsonrpc: {}, method: {}, params: {:?}}}",
+            self.jsonrpc, self.method, self.params
+        )
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/server.rs.html b/src/karyon_jsonrpc/server.rs.html new file mode 100644 index 00000000..33ebc8e7 --- /dev/null +++ b/src/karyon_jsonrpc/server.rs.html @@ -0,0 +1,418 @@ +server.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+
use std::{collections::HashMap, sync::Arc};
+
+use log::{debug, error, warn};
+use smol::lock::RwLock;
+
+use karyon_core::{
+    async_util::{TaskGroup, TaskResult},
+    Executor,
+};
+
+use karyon_net::{Conn, Listener, ToListener};
+
+use crate::{
+    codec::{Codec, CodecConfig},
+    message,
+    service::RPCService,
+    Endpoint, Error, Result, JSONRPC_VERSION,
+};
+
+pub const INVALID_REQUEST_ERROR_MSG: &str = "Invalid request";
+pub const FAILED_TO_PARSE_ERROR_MSG: &str = "Failed to parse";
+pub const METHOD_NOT_FOUND_ERROR_MSG: &str = "Method not found";
+pub const INTERNAL_ERROR_MSG: &str = "Internal error";
+
+fn pack_err_res(code: i32, msg: &str, id: Option<serde_json::Value>) -> message::Response {
+    let err = message::Error {
+        code,
+        message: msg.to_string(),
+        data: None,
+    };
+
+    message::Response {
+        jsonrpc: JSONRPC_VERSION.to_string(),
+        error: Some(err),
+        result: None,
+        id,
+    }
+}
+
+/// RPC server config
+#[derive(Default)]
+pub struct ServerConfig {
+    codec_config: CodecConfig,
+}
+
+/// Represents an RPC server
+pub struct Server<'a> {
+    listener: Listener,
+    services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>,
+    task_group: TaskGroup<'a>,
+    config: ServerConfig,
+}
+
+impl<'a> Server<'a> {
+    /// Creates a new RPC server by passing a listener. It supports Tcp, Unix, and Tls.
+    pub fn new<T: ToListener>(listener: T, config: ServerConfig, ex: Executor<'a>) -> Arc<Self> {
+        Arc::new(Self {
+            listener: listener.to_listener(),
+            services: RwLock::new(HashMap::new()),
+            task_group: TaskGroup::new(ex),
+            config,
+        })
+    }
+
+    /// Returns the local endpoint.
+    pub fn local_endpoint(&self) -> Result<Endpoint> {
+        self.listener.local_endpoint().map_err(Error::KaryonNet)
+    }
+
+    /// Starts the RPC server
+    pub async fn start(self: Arc<Self>) -> Result<()> {
+        loop {
+            let conn = self.listener.accept().await?;
+            if let Err(err) = self.handle_conn(conn).await {
+                error!("Failed to handle a new conn: {err}")
+            }
+        }
+    }
+
+    /// Attach a new service to the RPC server
+    pub async fn attach_service(&self, service: impl RPCService + 'a) {
+        self.services
+            .write()
+            .await
+            .insert(service.name(), Box::new(service));
+    }
+
+    /// Shuts down the RPC server
+    pub async fn shutdown(&self) {
+        self.task_group.cancel().await;
+    }
+
+    /// Handles a new connection
+    async fn handle_conn(self: &Arc<Self>, conn: Conn) -> Result<()> {
+        let endpoint = conn.peer_endpoint()?;
+        debug!("Handle a new connection {endpoint}");
+
+        let on_failure = |result: TaskResult<Result<()>>| async move {
+            if let TaskResult::Completed(Err(err)) = result {
+                error!("Connection {} dropped: {}", endpoint, err);
+            } else {
+                warn!("Connection {} dropped", endpoint);
+            }
+        };
+
+        let codec = Codec::new(conn, self.config.codec_config.clone());
+
+        let selfc = self.clone();
+        self.task_group.spawn(
+            async move {
+                loop {
+                    let mut buffer = vec![];
+                    codec.read_until(&mut buffer).await?;
+                    let response = selfc.handle_request(&buffer).await;
+                    let mut payload = serde_json::to_vec(&response)?;
+                    payload.push(b'\n');
+                    codec.write_all(&payload).await?;
+                    debug!("--> {response}");
+                }
+            },
+            on_failure,
+        );
+
+        Ok(())
+    }
+
+    /// Handles a request
+    async fn handle_request(&self, buffer: &[u8]) -> message::Response {
+        let rpc_msg = match serde_json::from_slice::<message::Request>(buffer) {
+            Ok(m) => m,
+            Err(_) => {
+                return pack_err_res(message::PARSE_ERROR_CODE, FAILED_TO_PARSE_ERROR_MSG, None);
+            }
+        };
+
+        debug!("<-- {rpc_msg}");
+
+        let srvc_method: Vec<&str> = rpc_msg.method.split('.').collect();
+        if srvc_method.len() != 2 {
+            return pack_err_res(
+                message::INVALID_REQUEST_ERROR_CODE,
+                INVALID_REQUEST_ERROR_MSG,
+                Some(rpc_msg.id),
+            );
+        }
+
+        let srvc_name = srvc_method[0];
+        let method_name = srvc_method[1];
+
+        let services = self.services.read().await;
+
+        let service = match services.get(srvc_name) {
+            Some(s) => s,
+            None => {
+                return pack_err_res(
+                    message::METHOD_NOT_FOUND_ERROR_CODE,
+                    METHOD_NOT_FOUND_ERROR_MSG,
+                    Some(rpc_msg.id),
+                );
+            }
+        };
+
+        let method = match service.get_method(method_name) {
+            Some(m) => m,
+            None => {
+                return pack_err_res(
+                    message::METHOD_NOT_FOUND_ERROR_CODE,
+                    METHOD_NOT_FOUND_ERROR_MSG,
+                    Some(rpc_msg.id),
+                );
+            }
+        };
+
+        let result = match method(rpc_msg.params.clone()).await {
+            Ok(res) => res,
+            Err(Error::ParseJSON(_)) => {
+                return pack_err_res(
+                    message::PARSE_ERROR_CODE,
+                    FAILED_TO_PARSE_ERROR_MSG,
+                    Some(rpc_msg.id),
+                );
+            }
+            Err(Error::InvalidParams(msg)) => {
+                return pack_err_res(message::INVALID_PARAMS_ERROR_CODE, msg, Some(rpc_msg.id));
+            }
+            Err(Error::InvalidRequest(msg)) => {
+                return pack_err_res(message::INVALID_REQUEST_ERROR_CODE, msg, Some(rpc_msg.id));
+            }
+            Err(Error::RPCMethodError(code, msg)) => {
+                return pack_err_res(code, msg, Some(rpc_msg.id));
+            }
+            Err(_) => {
+                return pack_err_res(
+                    message::INTERNAL_ERROR_CODE,
+                    INTERNAL_ERROR_MSG,
+                    Some(rpc_msg.id),
+                );
+            }
+        };
+
+        message::Response {
+            jsonrpc: JSONRPC_VERSION.to_string(),
+            error: None,
+            result: Some(result),
+            id: Some(rpc_msg.id),
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_jsonrpc/service.rs.html b/src/karyon_jsonrpc/service.rs.html new file mode 100644 index 00000000..2e83e12f --- /dev/null +++ b/src/karyon_jsonrpc/service.rs.html @@ -0,0 +1,130 @@ +service.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+
use std::{future::Future, pin::Pin};
+
+use crate::Result;
+
+/// Represents the RPC method
+pub type RPCMethod<'a> = Box<dyn Fn(serde_json::Value) -> RPCMethodOutput<'a> + Send + 'a>;
+type RPCMethodOutput<'a> =
+    Pin<Box<dyn Future<Output = Result<serde_json::Value>> + Send + Sync + 'a>>;
+
+/// Defines the interface for an RPC service.
+pub trait RPCService: Sync + Send {
+    fn get_method<'a>(&'a self, name: &'a str) -> Option<RPCMethod>;
+    fn name(&self) -> String;
+}
+
+/// Implements the [`RPCService`] trait for a provided type.
+///
+/// # Example
+///
+/// ```
+/// use serde_json::Value;
+///
+/// use karyon_jsonrpc::{JsonRPCError, register_service};
+///
+/// struct Hello {}
+///
+/// impl Hello {
+///     async fn foo(&self, params: Value) -> Result<Value, JsonRPCError> {
+///         Ok(serde_json::json!("foo!"))
+///     }
+///
+///     async fn bar(&self, params: Value) -> Result<Value, JsonRPCError> {
+///         Ok(serde_json::json!("bar!"))
+///     }
+/// }
+///
+/// register_service!(Hello, foo, bar);
+///
+/// ```
+#[macro_export]
+macro_rules! register_service {
+    ($t:ty, $($m:ident),*) => {
+        impl karyon_jsonrpc::RPCService for $t {
+            fn get_method<'a>(
+                &'a self,
+                name: &'a str
+            ) -> Option<karyon_jsonrpc::RPCMethod> {
+                match name {
+                $(
+                    stringify!($m) => {
+                        Some(Box::new(move |params: serde_json::Value| Box::pin(self.$m(params))))
+                    }
+                )*
+                    _ => None,
+                }
+
+
+            }
+            fn name(&self) -> String{
+                stringify!($t).to_string()
+            }
+        }
+    };
+}
+
\ No newline at end of file diff --git a/src/karyon_net/connection.rs.html b/src/karyon_net/connection.rs.html new file mode 100644 index 00000000..83a92e49 --- /dev/null +++ b/src/karyon_net/connection.rs.html @@ -0,0 +1,132 @@ +connection.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+
use async_trait::async_trait;
+
+use crate::{
+    transports::{tcp, udp, unix},
+    Endpoint, Error, Result,
+};
+
+/// Alias for `Box<dyn Connection>`
+pub type Conn = Box<dyn Connection>;
+
+/// A trait for objects which can be converted to [`Conn`].
+pub trait ToConn {
+    fn to_conn(self) -> Conn;
+}
+
+/// Connection is a generic network connection interface for
+/// [`udp::UdpConn`], [`tcp::TcpConn`], and [`unix::UnixConn`].
+///
+/// If you are familiar with the Go language, this is similar to the
+/// [Conn](https://pkg.go.dev/net#Conn) interface
+#[async_trait]
+pub trait Connection: Send + Sync {
+    /// Returns the remote peer endpoint of this connection
+    fn peer_endpoint(&self) -> Result<Endpoint>;
+
+    /// Returns the local socket endpoint of this connection
+    fn local_endpoint(&self) -> Result<Endpoint>;
+
+    /// Reads data from this connection.  
+    async fn read(&self, buf: &mut [u8]) -> Result<usize>;
+
+    /// Writes data to this connection
+    async fn write(&self, buf: &[u8]) -> Result<usize>;
+}
+
+/// Connects to the provided endpoint.
+///
+/// it only supports `tcp4/6`, `udp4/6`, and `unix`.
+///
+/// #Example
+///
+/// ```
+/// use karyon_net::{Endpoint, dial};
+///
+/// async {
+///     let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+///
+///     let conn = dial(&endpoint).await.unwrap();
+///
+///     conn.write(b"MSG").await.unwrap();
+///
+///     let mut buffer = [0;32];
+///     conn.read(&mut buffer).await.unwrap();
+/// };
+///
+/// ```
+///
+pub async fn dial(endpoint: &Endpoint) -> Result<Conn> {
+    match endpoint {
+        Endpoint::Tcp(_, _) => Ok(Box::new(tcp::dial_tcp(endpoint).await?)),
+        Endpoint::Udp(_, _) => Ok(Box::new(udp::dial_udp(endpoint).await?)),
+        Endpoint::Unix(addr) => Ok(Box::new(unix::dial_unix(addr).await?)),
+        _ => Err(Error::InvalidEndpoint(endpoint.to_string())),
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/endpoint.rs.html b/src/karyon_net/endpoint.rs.html new file mode 100644 index 00000000..b6527983 --- /dev/null +++ b/src/karyon_net/endpoint.rs.html @@ -0,0 +1,500 @@ +endpoint.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+
use std::{
+    net::{IpAddr, SocketAddr},
+    os::unix::net::SocketAddr as UnixSocketAddress,
+    path::PathBuf,
+    str::FromStr,
+};
+
+use bincode::{Decode, Encode};
+use url::Url;
+
+use crate::{Error, Result};
+
+/// Port defined as a u16.
+pub type Port = u16;
+
+/// Endpoint defines generic network endpoints for karyon.
+///
+/// # Example
+///
+/// ```
+/// use std::net::SocketAddr;
+///
+/// use karyon_net::Endpoint;
+///
+/// let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+///
+/// let socketaddr: SocketAddr = "127.0.0.1:3000".parse().unwrap();
+/// let endpoint =  Endpoint::new_udp_addr(&socketaddr);
+///
+/// ```
+///
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Endpoint {
+    Udp(Addr, Port),
+    Tcp(Addr, Port),
+    Tls(Addr, Port),
+    Ws(Addr, Port),
+    Unix(String),
+}
+
+impl std::fmt::Display for Endpoint {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Endpoint::Udp(ip, port) => {
+                write!(f, "udp://{}:{}", ip, port)
+            }
+            Endpoint::Tcp(ip, port) => {
+                write!(f, "tcp://{}:{}", ip, port)
+            }
+            Endpoint::Tls(ip, port) => {
+                write!(f, "tls://{}:{}", ip, port)
+            }
+            Endpoint::Ws(ip, port) => {
+                write!(f, "ws://{}:{}", ip, port)
+            }
+            Endpoint::Unix(path) => {
+                if path.is_empty() {
+                    write!(f, "unix:/UNNAMED")
+                } else {
+                    write!(f, "unix:/{}", path)
+                }
+            }
+        }
+    }
+}
+
+impl TryFrom<Endpoint> for SocketAddr {
+    type Error = Error;
+    fn try_from(endpoint: Endpoint) -> std::result::Result<SocketAddr, Self::Error> {
+        match endpoint {
+            Endpoint::Udp(ip, port)
+            | Endpoint::Tcp(ip, port)
+            | Endpoint::Tls(ip, port)
+            | Endpoint::Ws(ip, port) => Ok(SocketAddr::new(ip.try_into()?, port)),
+            Endpoint::Unix(_) => Err(Error::TryFromEndpoint),
+        }
+    }
+}
+
+impl TryFrom<Endpoint> for PathBuf {
+    type Error = Error;
+    fn try_from(endpoint: Endpoint) -> std::result::Result<PathBuf, Self::Error> {
+        match endpoint {
+            Endpoint::Unix(path) => Ok(PathBuf::from(&path)),
+            _ => Err(Error::TryFromEndpoint),
+        }
+    }
+}
+
+impl TryFrom<Endpoint> for UnixSocketAddress {
+    type Error = Error;
+    fn try_from(endpoint: Endpoint) -> std::result::Result<UnixSocketAddress, Self::Error> {
+        match endpoint {
+            Endpoint::Unix(a) => Ok(UnixSocketAddress::from_pathname(a)?),
+            _ => Err(Error::TryFromEndpoint),
+        }
+    }
+}
+
+impl FromStr for Endpoint {
+    type Err = Error;
+
+    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
+        let url: Url = match s.parse() {
+            Ok(u) => u,
+            Err(err) => return Err(Error::ParseEndpoint(err.to_string())),
+        };
+
+        if url.has_host() {
+            let host = url.host_str().unwrap();
+
+            let addr = match host.parse::<IpAddr>() {
+                Ok(addr) => Addr::Ip(addr),
+                Err(_) => Addr::Domain(host.to_string()),
+            };
+
+            let port = match url.port() {
+                Some(p) => p,
+                None => return Err(Error::ParseEndpoint(format!("port missing: {s}"))),
+            };
+
+            match url.scheme() {
+                "tcp" => Ok(Endpoint::Tcp(addr, port)),
+                "udp" => Ok(Endpoint::Udp(addr, port)),
+                "tls" => Ok(Endpoint::Tls(addr, port)),
+                "ws" => Ok(Endpoint::Ws(addr, port)),
+                _ => Err(Error::InvalidEndpoint(s.to_string())),
+            }
+        } else {
+            if url.path().is_empty() {
+                return Err(Error::InvalidEndpoint(s.to_string()));
+            }
+
+            match url.scheme() {
+                "unix" => Ok(Endpoint::Unix(url.path().to_string())),
+                _ => Err(Error::InvalidEndpoint(s.to_string())),
+            }
+        }
+    }
+}
+
+impl Endpoint {
+    /// Creates a new TCP endpoint from a `SocketAddr`.
+    pub fn new_tcp_addr(addr: &SocketAddr) -> Endpoint {
+        Endpoint::Tcp(Addr::Ip(addr.ip()), addr.port())
+    }
+
+    /// Creates a new UDP endpoint from a `SocketAddr`.
+    pub fn new_udp_addr(addr: &SocketAddr) -> Endpoint {
+        Endpoint::Udp(Addr::Ip(addr.ip()), addr.port())
+    }
+
+    /// Creates a new TLS endpoint from a `SocketAddr`.
+    pub fn new_tls_addr(addr: &SocketAddr) -> Endpoint {
+        Endpoint::Tls(Addr::Ip(addr.ip()), addr.port())
+    }
+
+    /// Creates a new WS endpoint from a `SocketAddr`.
+    pub fn new_ws_addr(addr: &SocketAddr) -> Endpoint {
+        Endpoint::Ws(Addr::Ip(addr.ip()), addr.port())
+    }
+
+    /// Creates a new Unix endpoint from a `UnixSocketAddress`.
+    pub fn new_unix_addr(addr: &UnixSocketAddress) -> Endpoint {
+        Endpoint::Unix(
+            addr.as_pathname()
+                .and_then(|a| a.to_str())
+                .unwrap_or("")
+                .to_string(),
+        )
+    }
+
+    /// Returns the `Port` of the endpoint.
+    pub fn port(&self) -> Result<&Port> {
+        match self {
+            Endpoint::Tcp(_, port)
+            | Endpoint::Udp(_, port)
+            | Endpoint::Tls(_, port)
+            | Endpoint::Ws(_, port) => Ok(port),
+            _ => Err(Error::TryFromEndpoint),
+        }
+    }
+
+    /// Returns the `Addr` of the endpoint.
+    pub fn addr(&self) -> Result<&Addr> {
+        match self {
+            Endpoint::Tcp(addr, _)
+            | Endpoint::Udp(addr, _)
+            | Endpoint::Tls(addr, _)
+            | Endpoint::Ws(addr, _) => Ok(addr),
+            _ => Err(Error::TryFromEndpoint),
+        }
+    }
+}
+
+/// Addr defines a type for an address, either IP or domain.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
+pub enum Addr {
+    Ip(IpAddr),
+    Domain(String),
+}
+
+impl TryFrom<Addr> for IpAddr {
+    type Error = Error;
+    fn try_from(addr: Addr) -> std::result::Result<IpAddr, Self::Error> {
+        match addr {
+            Addr::Ip(ip) => Ok(ip),
+            Addr::Domain(d) => Err(Error::InvalidAddress(d)),
+        }
+    }
+}
+
+impl std::fmt::Display for Addr {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        match self {
+            Addr::Ip(ip) => {
+                write!(f, "{}", ip)
+            }
+            Addr::Domain(d) => {
+                write!(f, "{}", d)
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::net::Ipv4Addr;
+
+    #[test]
+    fn test_endpoint_from_str() {
+        let endpoint_str: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+        let endpoint = Endpoint::Tcp(Addr::Ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), 3000);
+        assert_eq!(endpoint_str, endpoint);
+
+        let endpoint_str: Endpoint = "udp://127.0.0.1:4000".parse().unwrap();
+        let endpoint = Endpoint::Udp(Addr::Ip(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))), 4000);
+        assert_eq!(endpoint_str, endpoint);
+
+        let endpoint_str: Endpoint = "tcp://example.com:3000".parse().unwrap();
+        let endpoint = Endpoint::Tcp(Addr::Domain("example.com".to_string()), 3000);
+        assert_eq!(endpoint_str, endpoint);
+
+        let endpoint_str = "unix:/home/x/s.socket".parse::<Endpoint>().unwrap();
+        let endpoint = Endpoint::Unix("/home/x/s.socket".to_string());
+        assert_eq!(endpoint_str, endpoint);
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/error.rs.html b/src/karyon_net/error.rs.html new file mode 100644 index 00000000..8a2537c9 --- /dev/null +++ b/src/karyon_net/error.rs.html @@ -0,0 +1,92 @@ +error.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+
use thiserror::Error as ThisError;
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(ThisError, Debug)]
+pub enum Error {
+    #[error(transparent)]
+    IO(#[from] std::io::Error),
+
+    #[error("Try from endpoint Error")]
+    TryFromEndpoint,
+
+    #[error("invalid address {0}")]
+    InvalidAddress(String),
+
+    #[error("invalid endpoint {0}")]
+    InvalidEndpoint(String),
+
+    #[error("Parse endpoint error {0}")]
+    ParseEndpoint(String),
+
+    #[error("Timeout Error")]
+    Timeout,
+
+    #[error("Channel Send Error: {0}")]
+    ChannelSend(String),
+
+    #[error(transparent)]
+    ChannelRecv(#[from] smol::channel::RecvError),
+
+    #[error("Tls Error: {0}")]
+    Rustls(#[from] futures_rustls::rustls::Error),
+
+    #[error("Invalid DNS Name: {0}")]
+    InvalidDnsNameError(#[from] futures_rustls::pki_types::InvalidDnsNameError),
+
+    #[error(transparent)]
+    KaryonCore(#[from] karyon_core::error::Error),
+}
+
+impl<T> From<smol::channel::SendError<T>> for Error {
+    fn from(error: smol::channel::SendError<T>) -> Self {
+        Error::ChannelSend(error.to_string())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/lib.rs.html b/src/karyon_net/lib.rs.html new file mode 100644 index 00000000..5649fe2c --- /dev/null +++ b/src/karyon_net/lib.rs.html @@ -0,0 +1,52 @@ +lib.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+
mod connection;
+mod endpoint;
+mod error;
+mod listener;
+mod transports;
+
+pub use {
+    connection::{dial, Conn, Connection, ToConn},
+    endpoint::{Addr, Endpoint, Port},
+    listener::{listen, ConnListener, Listener, ToListener},
+    transports::{
+        tcp::{dial_tcp, listen_tcp, TcpConn},
+        tls,
+        udp::{dial_udp, listen_udp, UdpConn},
+        unix::{dial_unix, listen_unix, UnixConn},
+    },
+};
+
+use error::{Error, Result};
+
+/// Represents karyon's Net Error
+pub use error::Error as NetError;
+
+/// Represents karyon's Net Result
+pub use error::Result as NetResult;
+
\ No newline at end of file diff --git a/src/karyon_net/listener.rs.html b/src/karyon_net/listener.rs.html new file mode 100644 index 00000000..b0eefa15 --- /dev/null +++ b/src/karyon_net/listener.rs.html @@ -0,0 +1,94 @@ +listener.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+
use async_trait::async_trait;
+
+use crate::{
+    transports::{tcp, unix},
+    Conn, Endpoint, Error, Result,
+};
+
+/// Alias for `Box<dyn ConnListener>`
+pub type Listener = Box<dyn ConnListener>;
+
+/// A trait for objects which can be converted to [`Listener`].
+pub trait ToListener {
+    fn to_listener(self) -> Listener;
+}
+
+/// ConnListener is a generic network listener.
+#[async_trait]
+pub trait ConnListener: Send + Sync {
+    fn local_endpoint(&self) -> Result<Endpoint>;
+    async fn accept(&self) -> Result<Conn>;
+}
+
+/// Listens to the provided endpoint.
+///
+/// it only supports `tcp4/6`, and `unix`.
+///
+/// #Example
+///
+/// ```
+/// use karyon_net::{Endpoint, listen};
+///
+/// async {
+///     let endpoint: Endpoint = "tcp://127.0.0.1:3000".parse().unwrap();
+///
+///     let listener = listen(&endpoint).await.unwrap();
+///     let conn = listener.accept().await.unwrap();
+/// };
+///
+/// ```
+pub async fn listen(endpoint: &Endpoint) -> Result<Box<dyn ConnListener>> {
+    match endpoint {
+        Endpoint::Tcp(_, _) => Ok(Box::new(tcp::listen_tcp(endpoint).await?)),
+        Endpoint::Unix(addr) => Ok(Box::new(unix::listen_unix(addr)?)),
+        _ => Err(Error::InvalidEndpoint(endpoint.to_string())),
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/transports/mod.rs.html b/src/karyon_net/transports/mod.rs.html new file mode 100644 index 00000000..beceb741 --- /dev/null +++ b/src/karyon_net/transports/mod.rs.html @@ -0,0 +1,10 @@ +mod.rs - source +
1
+2
+3
+4
+
pub mod tcp;
+pub mod tls;
+pub mod udp;
+pub mod unix;
+
\ No newline at end of file diff --git a/src/karyon_net/transports/tcp.rs.html b/src/karyon_net/transports/tcp.rs.html new file mode 100644 index 00000000..97fbcf97 --- /dev/null +++ b/src/karyon_net/transports/tcp.rs.html @@ -0,0 +1,234 @@ +tcp.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+
use std::net::SocketAddr;
+
+use async_trait::async_trait;
+use smol::{
+    io::{split, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
+    lock::Mutex,
+    net::{TcpListener, TcpStream},
+};
+
+use crate::{
+    connection::{Connection, ToConn},
+    endpoint::Endpoint,
+    listener::{ConnListener, ToListener},
+    Error, Result,
+};
+
+/// TCP network connection implementation of the [`Connection`] trait.
+pub struct TcpConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TcpStream>>,
+    write: Mutex<WriteHalf<TcpStream>>,
+}
+
+impl TcpConn {
+    /// Creates a new TcpConn
+    pub fn new(conn: TcpStream) -> Self {
+        let (read, write) = split(conn.clone());
+        Self {
+            inner: conn,
+            read: Mutex::new(read),
+            write: Mutex::new(write),
+        }
+    }
+}
+
+#[async_trait]
+impl Connection for TcpConn {
+    fn peer_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tcp_addr(&self.inner.peer_addr()?))
+    }
+
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tcp_addr(&self.inner.local_addr()?))
+    }
+
+    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
+        self.read.lock().await.read(buf).await.map_err(Error::from)
+    }
+
+    async fn write(&self, buf: &[u8]) -> Result<usize> {
+        self.write
+            .lock()
+            .await
+            .write(buf)
+            .await
+            .map_err(Error::from)
+    }
+}
+
+#[async_trait]
+impl ConnListener for TcpListener {
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tcp_addr(&self.local_addr()?))
+    }
+
+    async fn accept(&self) -> Result<Box<dyn Connection>> {
+        let (conn, _) = self.accept().await?;
+        conn.set_nodelay(true)?;
+        Ok(Box::new(TcpConn::new(conn)))
+    }
+}
+
+/// Connects to the given TCP address and port.
+pub async fn dial_tcp(endpoint: &Endpoint) -> Result<TcpConn> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+    let conn = TcpStream::connect(addr).await?;
+    conn.set_nodelay(true)?;
+    Ok(TcpConn::new(conn))
+}
+
+/// Listens on the given TCP address and port.
+pub async fn listen_tcp(endpoint: &Endpoint) -> Result<TcpListener> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+    let listener = TcpListener::bind(addr).await?;
+    Ok(listener)
+}
+
+impl From<TcpStream> for Box<dyn Connection> {
+    fn from(conn: TcpStream) -> Self {
+        Box::new(TcpConn::new(conn))
+    }
+}
+
+impl From<TcpListener> for Box<dyn ConnListener> {
+    fn from(listener: TcpListener) -> Self {
+        Box::new(listener)
+    }
+}
+
+impl ToConn for TcpStream {
+    fn to_conn(self) -> Box<dyn Connection> {
+        self.into()
+    }
+}
+
+impl ToConn for TcpConn {
+    fn to_conn(self) -> Box<dyn Connection> {
+        Box::new(self)
+    }
+}
+
+impl ToListener for TcpListener {
+    fn to_listener(self) -> Box<dyn ConnListener> {
+        self.into()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/transports/tls.rs.html b/src/karyon_net/transports/tls.rs.html new file mode 100644 index 00000000..646695d5 --- /dev/null +++ b/src/karyon_net/transports/tls.rs.html @@ -0,0 +1,304 @@ +tls.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+
use std::{net::SocketAddr, sync::Arc};
+
+use async_trait::async_trait;
+use futures_rustls::{pki_types, rustls, TlsAcceptor, TlsConnector, TlsStream};
+use smol::{
+    io::{split, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
+    lock::Mutex,
+    net::{TcpListener, TcpStream},
+};
+
+use crate::{
+    connection::{Connection, ToConn},
+    endpoint::Endpoint,
+    listener::{ConnListener, ToListener},
+    Error, Result,
+};
+
+/// TLS network connection implementation of the [`Connection`] trait.
+pub struct TlsConn {
+    inner: TcpStream,
+    read: Mutex<ReadHalf<TlsStream<TcpStream>>>,
+    write: Mutex<WriteHalf<TlsStream<TcpStream>>>,
+}
+
+impl TlsConn {
+    /// Creates a new TlsConn
+    pub fn new(sock: TcpStream, conn: TlsStream<TcpStream>) -> Self {
+        let (read, write) = split(conn);
+        Self {
+            inner: sock,
+            read: Mutex::new(read),
+            write: Mutex::new(write),
+        }
+    }
+}
+
+#[async_trait]
+impl Connection for TlsConn {
+    fn peer_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tls_addr(&self.inner.peer_addr()?))
+    }
+
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tls_addr(&self.inner.local_addr()?))
+    }
+
+    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
+        self.read.lock().await.read(buf).await.map_err(Error::from)
+    }
+
+    async fn write(&self, buf: &[u8]) -> Result<usize> {
+        self.write
+            .lock()
+            .await
+            .write(buf)
+            .await
+            .map_err(Error::from)
+    }
+}
+
+/// Connects to the given TLS address and port.
+pub async fn dial_tls(
+    endpoint: &Endpoint,
+    config: rustls::ClientConfig,
+    dns_name: &'static str,
+) -> Result<TlsConn> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+
+    let connector = TlsConnector::from(Arc::new(config));
+
+    let sock = TcpStream::connect(addr).await?;
+    sock.set_nodelay(true)?;
+
+    let altname = pki_types::ServerName::try_from(dns_name)?;
+    let conn = connector.connect(altname, sock.clone()).await?;
+    Ok(TlsConn::new(sock, TlsStream::Client(conn)))
+}
+
+/// Connects to the given TLS endpoint, returns `Conn` ([`Connection`]).
+pub async fn dial(
+    endpoint: &Endpoint,
+    config: rustls::ClientConfig,
+    dns_name: &'static str,
+) -> Result<Box<dyn Connection>> {
+    match endpoint {
+        Endpoint::Tcp(..) | Endpoint::Tls(..) => {}
+        _ => return Err(Error::InvalidEndpoint(endpoint.to_string())),
+    }
+
+    dial_tls(endpoint, config, dns_name)
+        .await
+        .map(|c| Box::new(c) as Box<dyn Connection>)
+}
+
+/// Tls network listener implementation of the `Listener` [`ConnListener`] trait.
+pub struct TlsListener {
+    acceptor: TlsAcceptor,
+    listener: TcpListener,
+}
+
+#[async_trait]
+impl ConnListener for TlsListener {
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_tls_addr(&self.listener.local_addr()?))
+    }
+
+    async fn accept(&self) -> Result<Box<dyn Connection>> {
+        let (sock, _) = self.listener.accept().await?;
+        sock.set_nodelay(true)?;
+        let conn = self.acceptor.accept(sock.clone()).await?;
+        Ok(Box::new(TlsConn::new(sock, TlsStream::Server(conn))))
+    }
+}
+
+/// Listens on the given TLS address and port.
+pub async fn listen_tls(endpoint: &Endpoint, config: rustls::ServerConfig) -> Result<TlsListener> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+    let acceptor = TlsAcceptor::from(Arc::new(config));
+    let listener = TcpListener::bind(addr).await?;
+    Ok(TlsListener { acceptor, listener })
+}
+
+impl From<TlsStream<TcpStream>> for Box<dyn Connection> {
+    fn from(conn: TlsStream<TcpStream>) -> Self {
+        Box::new(TlsConn::new(conn.get_ref().0.clone(), conn))
+    }
+}
+
+impl From<TlsListener> for Box<dyn ConnListener> {
+    fn from(listener: TlsListener) -> Self {
+        Box::new(listener)
+    }
+}
+
+impl ToConn for TlsStream<TcpStream> {
+    fn to_conn(self) -> Box<dyn Connection> {
+        self.into()
+    }
+}
+
+impl ToConn for TlsConn {
+    fn to_conn(self) -> Box<dyn Connection> {
+        Box::new(self)
+    }
+}
+
+impl ToListener for TlsListener {
+    fn to_listener(self) -> Box<dyn ConnListener> {
+        self.into()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/transports/udp.rs.html b/src/karyon_net/transports/udp.rs.html new file mode 100644 index 00000000..876e8191 --- /dev/null +++ b/src/karyon_net/transports/udp.rs.html @@ -0,0 +1,188 @@ +udp.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+
use std::net::SocketAddr;
+
+use async_trait::async_trait;
+use smol::net::UdpSocket;
+
+use crate::{
+    connection::{Connection, ToConn},
+    endpoint::Endpoint,
+    Error, Result,
+};
+
+/// UDP network connection implementation of the [`Connection`] trait.
+pub struct UdpConn {
+    inner: UdpSocket,
+}
+
+impl UdpConn {
+    /// Creates a new UdpConn
+    pub fn new(conn: UdpSocket) -> Self {
+        Self { inner: conn }
+    }
+}
+
+impl UdpConn {
+    /// Receives a single datagram message. Returns the number of bytes read
+    /// and the origin endpoint.
+    pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, Endpoint)> {
+        let (size, addr) = self.inner.recv_from(buf).await?;
+        Ok((size, Endpoint::new_udp_addr(&addr)))
+    }
+
+    /// Sends data to the given address. Returns the number of bytes written.
+    pub async fn send_to(&self, buf: &[u8], addr: &Endpoint) -> Result<usize> {
+        let addr: SocketAddr = addr.clone().try_into()?;
+        let size = self.inner.send_to(buf, addr).await?;
+        Ok(size)
+    }
+}
+
+#[async_trait]
+impl Connection for UdpConn {
+    fn peer_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_udp_addr(&self.inner.peer_addr()?))
+    }
+
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_udp_addr(&self.inner.local_addr()?))
+    }
+
+    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
+        self.inner.recv(buf).await.map_err(Error::from)
+    }
+
+    async fn write(&self, buf: &[u8]) -> Result<usize> {
+        self.inner.send(buf).await.map_err(Error::from)
+    }
+}
+
+/// Connects to the given UDP address and port.
+pub async fn dial_udp(endpoint: &Endpoint) -> Result<UdpConn> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+
+    // Let the operating system assign an available port to this socket
+    let conn = UdpSocket::bind("[::]:0").await?;
+    conn.connect(addr).await?;
+    Ok(UdpConn::new(conn))
+}
+
+/// Listens on the given UDP address and port.
+pub async fn listen_udp(endpoint: &Endpoint) -> Result<UdpConn> {
+    let addr = SocketAddr::try_from(endpoint.clone())?;
+    let conn = UdpSocket::bind(addr).await?;
+    let udp_conn = UdpConn::new(conn);
+    Ok(udp_conn)
+}
+
+impl From<UdpSocket> for Box<dyn Connection> {
+    fn from(conn: UdpSocket) -> Self {
+        Box::new(UdpConn::new(conn))
+    }
+}
+
+impl ToConn for UdpSocket {
+    fn to_conn(self) -> Box<dyn Connection> {
+        self.into()
+    }
+}
+
+impl ToConn for UdpConn {
+    fn to_conn(self) -> Box<dyn Connection> {
+        Box::new(self)
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_net/transports/unix.rs.html b/src/karyon_net/transports/unix.rs.html new file mode 100644 index 00000000..a24a08a7 --- /dev/null +++ b/src/karyon_net/transports/unix.rs.html @@ -0,0 +1,224 @@ +unix.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+
use async_trait::async_trait;
+
+use smol::{
+    io::{split, AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf},
+    lock::Mutex,
+    net::unix::{UnixListener, UnixStream},
+};
+
+use crate::{
+    connection::{Connection, ToConn},
+    endpoint::Endpoint,
+    listener::{ConnListener, ToListener},
+    Error, Result,
+};
+
+/// Unix domain socket implementation of the [`Connection`] trait.
+pub struct UnixConn {
+    inner: UnixStream,
+    read: Mutex<ReadHalf<UnixStream>>,
+    write: Mutex<WriteHalf<UnixStream>>,
+}
+
+impl UnixConn {
+    /// Creates a new UnixConn
+    pub fn new(conn: UnixStream) -> Self {
+        let (read, write) = split(conn.clone());
+        Self {
+            inner: conn,
+            read: Mutex::new(read),
+            write: Mutex::new(write),
+        }
+    }
+}
+
+#[async_trait]
+impl Connection for UnixConn {
+    fn peer_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_unix_addr(&self.inner.peer_addr()?))
+    }
+
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_unix_addr(&self.inner.local_addr()?))
+    }
+
+    async fn read(&self, buf: &mut [u8]) -> Result<usize> {
+        self.read.lock().await.read(buf).await.map_err(Error::from)
+    }
+
+    async fn write(&self, buf: &[u8]) -> Result<usize> {
+        self.write
+            .lock()
+            .await
+            .write(buf)
+            .await
+            .map_err(Error::from)
+    }
+}
+
+#[async_trait]
+impl ConnListener for UnixListener {
+    fn local_endpoint(&self) -> Result<Endpoint> {
+        Ok(Endpoint::new_unix_addr(&self.local_addr()?))
+    }
+
+    async fn accept(&self) -> Result<Box<dyn Connection>> {
+        let (conn, _) = self.accept().await?;
+        Ok(Box::new(UnixConn::new(conn)))
+    }
+}
+
+/// Connects to the given Unix socket path.
+pub async fn dial_unix(path: &String) -> Result<UnixConn> {
+    let conn = UnixStream::connect(path).await?;
+    Ok(UnixConn::new(conn))
+}
+
+/// Listens on the given Unix socket path.
+pub fn listen_unix(path: &String) -> Result<UnixListener> {
+    let listener = UnixListener::bind(path)?;
+    Ok(listener)
+}
+
+impl From<UnixStream> for Box<dyn Connection> {
+    fn from(conn: UnixStream) -> Self {
+        Box::new(UnixConn::new(conn))
+    }
+}
+
+impl From<UnixListener> for Box<dyn ConnListener> {
+    fn from(listener: UnixListener) -> Self {
+        Box::new(listener)
+    }
+}
+
+impl ToConn for UnixStream {
+    fn to_conn(self) -> Box<dyn Connection> {
+        self.into()
+    }
+}
+
+impl ToConn for UnixConn {
+    fn to_conn(self) -> Box<dyn Connection> {
+        Box::new(self)
+    }
+}
+
+impl ToListener for UnixListener {
+    fn to_listener(self) -> Box<dyn ConnListener> {
+        self.into()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/backend.rs.html b/src/karyon_p2p/backend.rs.html new file mode 100644 index 00000000..2320e41f --- /dev/null +++ b/src/karyon_p2p/backend.rs.html @@ -0,0 +1,252 @@ +backend.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+
use std::sync::Arc;
+
+use log::info;
+
+use karyon_core::{crypto::KeyPair, pubsub::Subscription, GlobalExecutor};
+
+use crate::{
+    config::Config,
+    connection::ConnQueue,
+    discovery::{ArcDiscovery, Discovery},
+    monitor::{Monitor, MonitorEvent},
+    peer_pool::PeerPool,
+    protocol::{ArcProtocol, Protocol},
+    ArcPeer, PeerID, Result,
+};
+
+pub type ArcBackend = Arc<Backend>;
+
+/// Backend serves as the central entry point for initiating and managing
+/// the P2P network.
+pub struct Backend {
+    /// The Configuration for the P2P network.
+    config: Arc<Config>,
+
+    /// Identity Key pair
+    key_pair: KeyPair,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+
+    /// Discovery instance.
+    discovery: ArcDiscovery,
+
+    /// PeerPool instance.
+    peer_pool: Arc<PeerPool>,
+}
+
+impl Backend {
+    /// Creates a new Backend.
+    pub fn new(key_pair: &KeyPair, config: Config, ex: GlobalExecutor) -> ArcBackend {
+        let config = Arc::new(config);
+        let monitor = Arc::new(Monitor::new());
+        let conn_queue = ConnQueue::new();
+
+        let peer_id = PeerID::try_from(key_pair.public())
+            .expect("Derive a peer id from the provided key pair.");
+        info!("PeerID: {}", peer_id);
+
+        let peer_pool = PeerPool::new(
+            &peer_id,
+            conn_queue.clone(),
+            config.clone(),
+            monitor.clone(),
+            ex.clone(),
+        );
+
+        let discovery = Discovery::new(
+            key_pair,
+            &peer_id,
+            conn_queue,
+            config.clone(),
+            monitor.clone(),
+            ex,
+        );
+
+        Arc::new(Self {
+            key_pair: key_pair.clone(),
+            monitor,
+            discovery,
+            config,
+            peer_pool,
+        })
+    }
+
+    /// Run the Backend, starting the PeerPool and Discovery instances.
+    pub async fn run(self: &Arc<Self>) -> Result<()> {
+        self.peer_pool.start().await?;
+        self.discovery.start().await?;
+        Ok(())
+    }
+
+    /// Attach a custom protocol to the network
+    pub async fn attach_protocol<P: Protocol>(
+        &self,
+        c: impl Fn(ArcPeer) -> ArcProtocol + Send + Sync + 'static,
+    ) -> Result<()> {
+        self.peer_pool.attach_protocol::<P>(Box::new(c)).await
+    }
+
+    /// Returns the number of currently connected peers.
+    pub async fn peers(&self) -> usize {
+        self.peer_pool.peers_len().await
+    }
+
+    /// Returns the `Config`.
+    pub fn config(&self) -> Arc<Config> {
+        self.config.clone()
+    }
+
+    /// Returns the `KeyPair`.
+    pub async fn key_pair(&self) -> &KeyPair {
+        &self.key_pair
+    }
+
+    /// Returns the number of occupied inbound slots.
+    pub fn inbound_slots(&self) -> usize {
+        self.discovery.inbound_slots.load()
+    }
+
+    /// Returns the number of occupied outbound slots.
+    pub fn outbound_slots(&self) -> usize {
+        self.discovery.outbound_slots.load()
+    }
+
+    /// Subscribes to the monitor to receive network events.
+    pub async fn monitor(&self) -> Subscription<MonitorEvent> {
+        self.monitor.subscribe().await
+    }
+
+    /// Shuts down the Backend.
+    pub async fn shutdown(&self) {
+        self.discovery.shutdown().await;
+        self.peer_pool.shutdown().await;
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/codec.rs.html b/src/karyon_p2p/codec.rs.html new file mode 100644 index 00000000..95aec89e --- /dev/null +++ b/src/karyon_p2p/codec.rs.html @@ -0,0 +1,242 @@ +codec.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+
use std::time::Duration;
+
+use bincode::{Decode, Encode};
+
+use karyon_core::{
+    async_util::timeout,
+    util::{decode, encode, encode_into_slice},
+};
+
+use karyon_net::{Connection, NetError};
+
+use crate::{
+    message::{NetMsg, NetMsgCmd, NetMsgHeader, MAX_ALLOWED_MSG_SIZE, MSG_HEADER_SIZE},
+    Error, Result,
+};
+
+pub trait CodecMsg: Decode + Encode + std::fmt::Debug {}
+impl<T: Encode + Decode + std::fmt::Debug> CodecMsg for T {}
+
+/// A Codec working with generic network connections.
+///
+/// It is responsible for both decoding data received from the network and
+/// encoding data before sending it.
+pub struct Codec {
+    conn: Box<dyn Connection>,
+}
+
+impl Codec {
+    /// Creates a new Codec.
+    pub fn new(conn: Box<dyn Connection>) -> Self {
+        Self { conn }
+    }
+
+    /// Reads a message of type `NetMsg` from the connection.
+    ///
+    /// It reads the first 6 bytes as the header of the message, then reads
+    /// and decodes the remaining message data based on the determined header.
+    pub async fn read(&self) -> Result<NetMsg> {
+        // Read 6 bytes to get the header of the incoming message
+        let mut buf = [0; MSG_HEADER_SIZE];
+        self.read_exact(&mut buf).await?;
+
+        // Decode the header from bytes to NetMsgHeader
+        let (header, _) = decode::<NetMsgHeader>(&buf)?;
+
+        if header.payload_size > MAX_ALLOWED_MSG_SIZE {
+            return Err(Error::InvalidMsg(
+                "Message exceeds the maximum allowed size".to_string(),
+            ));
+        }
+
+        // Create a buffer to hold the message based on its length
+        let mut payload = vec![0; header.payload_size as usize];
+        self.read_exact(&mut payload).await?;
+
+        Ok(NetMsg { header, payload })
+    }
+
+    /// Writes a message of type `T` to the connection.
+    ///
+    /// Before appending the actual message payload, it calculates the length of
+    /// the encoded message in bytes and appends this length to the message header.
+    pub async fn write<T: CodecMsg>(&self, command: NetMsgCmd, msg: &T) -> Result<()> {
+        let payload = encode(msg)?;
+
+        // Create a buffer to hold the message header (6 bytes)
+        let header_buf = &mut [0; MSG_HEADER_SIZE];
+        let header = NetMsgHeader {
+            command,
+            payload_size: payload.len() as u32,
+        };
+        encode_into_slice(&header, header_buf)?;
+
+        let mut buffer = vec![];
+        // Append the header bytes to the buffer
+        buffer.extend_from_slice(header_buf);
+        // Append the message payload to the buffer
+        buffer.extend_from_slice(&payload);
+
+        self.write_all(&buffer).await?;
+        Ok(())
+    }
+
+    /// Reads a message of type `NetMsg` with the given timeout.
+    pub async fn read_timeout(&self, duration: Duration) -> Result<NetMsg> {
+        timeout(duration, self.read())
+            .await
+            .map_err(|_| NetError::Timeout)?
+    }
+
+    /// Reads the exact number of bytes required to fill `buf`.
+    async fn read_exact(&self, mut buf: &mut [u8]) -> Result<()> {
+        while !buf.is_empty() {
+            let n = self.conn.read(buf).await?;
+            let (_, rest) = std::mem::take(&mut buf).split_at_mut(n);
+            buf = rest;
+
+            if n == 0 {
+                return Err(Error::IO(std::io::ErrorKind::UnexpectedEof.into()));
+            }
+        }
+
+        Ok(())
+    }
+
+    /// Writes an entire buffer into the connection.
+    async fn write_all(&self, mut buf: &[u8]) -> Result<()> {
+        while !buf.is_empty() {
+            let n = self.conn.write(buf).await?;
+            let (_, rest) = std::mem::take(&mut buf).split_at(n);
+            buf = rest;
+
+            if n == 0 {
+                return Err(Error::IO(std::io::ErrorKind::UnexpectedEof.into()));
+            }
+        }
+
+        Ok(())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/config.rs.html b/src/karyon_p2p/config.rs.html new file mode 100644 index 00000000..fc69cfb2 --- /dev/null +++ b/src/karyon_p2p/config.rs.html @@ -0,0 +1,222 @@ +config.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+
use karyon_net::{Endpoint, Port};
+
+use crate::Version;
+
+/// the Configuration for the P2P network.
+pub struct Config {
+    /// Represents the network version.
+    pub version: Version,
+
+    /////////////////
+    // PeerPool
+    ////////////////
+    /// Timeout duration for the handshake with new peers, in seconds.
+    pub handshake_timeout: u64,
+    /// Interval at which the ping protocol sends ping messages to a peer to
+    /// maintain connections, in seconds.
+    pub ping_interval: u64,
+    /// Timeout duration for receiving the pong message corresponding to the
+    /// sent ping message, in seconds.
+    pub ping_timeout: u64,
+    /// The maximum number of retries for outbound connection establishment.
+    pub max_connect_retries: usize,
+
+    /////////////////
+    // DISCOVERY
+    ////////////////
+    /// A list of bootstrap peers for the seeding process.
+    pub bootstrap_peers: Vec<Endpoint>,
+    /// An optional listening endpoint to accept incoming connections.
+    pub listen_endpoint: Option<Endpoint>,
+    /// A list of endpoints representing peers that the `Discovery` will
+    /// manually connect to.
+    pub peer_endpoints: Vec<Endpoint>,
+    /// The number of available inbound slots for incoming connections.
+    pub inbound_slots: usize,
+    /// The number of available outbound slots for outgoing connections.
+    pub outbound_slots: usize,
+    /// TCP/UDP port for lookup and refresh processes.
+    pub discovery_port: Port,
+    /// Time interval, in seconds, at which the Discovery restarts the
+    /// seeding process.
+    pub seeding_interval: u64,
+
+    /////////////////
+    // LOOKUP
+    ////////////////
+    /// The number of available inbound slots for incoming connections during
+    /// the lookup process.
+    pub lookup_inbound_slots: usize,
+    /// The number of available outbound slots for outgoing connections during
+    /// the lookup process.
+    pub lookup_outbound_slots: usize,
+    /// Timeout duration for a peer response during the lookup process, in
+    /// seconds.
+    pub lookup_response_timeout: u64,
+    /// Maximum allowable time for a live connection with a peer during the
+    /// lookup process, in seconds.
+    pub lookup_connection_lifespan: u64,
+    /// The maximum number of retries for outbound connection establishment
+    /// during the lookup process.
+    pub lookup_connect_retries: usize,
+
+    /////////////////
+    // REFRESH
+    ////////////////
+    /// Interval at which the table refreshes its entries, in seconds.
+    pub refresh_interval: u64,
+    /// Timeout duration for a peer response during the table refresh process,
+    /// in seconds.
+    pub refresh_response_timeout: u64,
+    /// The maximum number of retries for outbound connection establishment
+    /// during the refresh process.
+    pub refresh_connect_retries: usize,
+
+    /// Enables TLS for all connections.
+    pub enable_tls: bool,
+}
+
+impl Default for Config {
+    fn default() -> Self {
+        Config {
+            version: "0.1.0".parse().unwrap(),
+
+            handshake_timeout: 2,
+            ping_interval: 20,
+            ping_timeout: 2,
+
+            bootstrap_peers: vec![],
+            listen_endpoint: None,
+            peer_endpoints: vec![],
+            inbound_slots: 12,
+            outbound_slots: 12,
+            max_connect_retries: 3,
+            discovery_port: 0,
+            seeding_interval: 60,
+
+            lookup_inbound_slots: 20,
+            lookup_outbound_slots: 20,
+            lookup_response_timeout: 1,
+            lookup_connection_lifespan: 3,
+            lookup_connect_retries: 3,
+
+            refresh_interval: 1800,
+            refresh_response_timeout: 1,
+            refresh_connect_retries: 3,
+
+            enable_tls: false,
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/connection.rs.html b/src/karyon_p2p/connection.rs.html new file mode 100644 index 00000000..7c915ba3 --- /dev/null +++ b/src/karyon_p2p/connection.rs.html @@ -0,0 +1,142 @@ +connection.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+
use std::{collections::VecDeque, fmt, sync::Arc};
+
+use smol::{channel::Sender, lock::Mutex};
+
+use karyon_core::async_util::CondVar;
+use karyon_net::Conn;
+
+use crate::Result;
+
+/// Defines the direction of a network connection.
+#[derive(Clone, Debug)]
+pub enum ConnDirection {
+    Inbound,
+    Outbound,
+}
+
+impl fmt::Display for ConnDirection {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match self {
+            ConnDirection::Inbound => write!(f, "Inbound"),
+            ConnDirection::Outbound => write!(f, "Outbound"),
+        }
+    }
+}
+
+pub struct NewConn {
+    pub direction: ConnDirection,
+    pub conn: Conn,
+    pub disconnect_signal: Sender<Result<()>>,
+}
+
+/// Connection queue
+pub struct ConnQueue {
+    queue: Mutex<VecDeque<NewConn>>,
+    conn_available: CondVar,
+}
+
+impl ConnQueue {
+    pub fn new() -> Arc<Self> {
+        Arc::new(Self {
+            queue: Mutex::new(VecDeque::new()),
+            conn_available: CondVar::new(),
+        })
+    }
+
+    /// Push a connection into the queue and wait for the disconnect signal
+    pub async fn handle(&self, conn: Conn, direction: ConnDirection) -> Result<()> {
+        let (disconnect_signal, chan) = smol::channel::bounded(1);
+        let new_conn = NewConn {
+            direction,
+            conn,
+            disconnect_signal,
+        };
+        self.queue.lock().await.push_back(new_conn);
+        self.conn_available.signal();
+        if let Ok(result) = chan.recv().await {
+            return result;
+        }
+        Ok(())
+    }
+
+    /// Receive the next connection in the queue
+    pub async fn next(&self) -> NewConn {
+        let mut queue = self.queue.lock().await;
+        while queue.is_empty() {
+            queue = self.conn_available.wait(queue).await;
+        }
+        queue.pop_front().unwrap()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/connector.rs.html b/src/karyon_p2p/connector.rs.html new file mode 100644 index 00000000..a9dd8eae --- /dev/null +++ b/src/karyon_p2p/connector.rs.html @@ -0,0 +1,304 @@ +connector.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+
use std::{future::Future, sync::Arc};
+
+use log::{error, trace, warn};
+
+use karyon_core::{
+    async_util::{Backoff, TaskGroup, TaskResult},
+    crypto::KeyPair,
+    GlobalExecutor,
+};
+use karyon_net::{dial, tls, Conn, Endpoint, NetError};
+
+use crate::{
+    monitor::{ConnEvent, Monitor},
+    slots::ConnectionSlots,
+    tls_config::tls_client_config,
+    Error, PeerID, Result,
+};
+
+static DNS_NAME: &str = "karyontech.net";
+
+/// Responsible for creating outbound connections with other peers.
+pub struct Connector {
+    /// Identity Key pair
+    key_pair: KeyPair,
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+
+    /// Manages available outbound slots.
+    connection_slots: Arc<ConnectionSlots>,
+
+    /// The maximum number of retries allowed before successfully
+    /// establishing a connection.
+    max_retries: usize,
+
+    /// Enables secure connection.
+    enable_tls: bool,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+}
+
+impl Connector {
+    /// Creates a new Connector
+    pub fn new(
+        key_pair: &KeyPair,
+        max_retries: usize,
+        connection_slots: Arc<ConnectionSlots>,
+        enable_tls: bool,
+        monitor: Arc<Monitor>,
+        ex: GlobalExecutor,
+    ) -> Arc<Self> {
+        Arc::new(Self {
+            key_pair: key_pair.clone(),
+            max_retries,
+            task_group: TaskGroup::new(ex),
+            monitor,
+            connection_slots,
+            enable_tls,
+        })
+    }
+
+    /// Shuts down the connector
+    pub async fn shutdown(&self) {
+        self.task_group.cancel().await;
+    }
+
+    /// Establish a connection to the specified `endpoint`. If the connection
+    /// attempt fails, it performs a backoff and retries until the maximum allowed
+    /// number of retries is exceeded. On a successful connection, it returns a
+    /// `Conn` instance.
+    ///
+    /// This method will block until it finds an available slot.
+    pub async fn connect(&self, endpoint: &Endpoint, peer_id: &Option<PeerID>) -> Result<Conn> {
+        self.connection_slots.wait_for_slot().await;
+        self.connection_slots.add();
+
+        let mut retry = 0;
+        let backoff = Backoff::new(500, 2000);
+        while retry < self.max_retries {
+            match self.dial(endpoint, peer_id).await {
+                Ok(conn) => {
+                    self.monitor
+                        .notify(&ConnEvent::Connected(endpoint.clone()).into())
+                        .await;
+                    return Ok(conn);
+                }
+                Err(err) => {
+                    error!("Failed to establish a connection to {endpoint}: {err}");
+                }
+            }
+
+            self.monitor
+                .notify(&ConnEvent::ConnectRetried(endpoint.clone()).into())
+                .await;
+
+            backoff.sleep().await;
+
+            warn!("try to reconnect {endpoint}");
+            retry += 1;
+        }
+
+        self.monitor
+            .notify(&ConnEvent::ConnectFailed(endpoint.clone()).into())
+            .await;
+
+        self.connection_slots.remove().await;
+        Err(NetError::Timeout.into())
+    }
+
+    /// Establish a connection to the given `endpoint`. For each new connection,
+    /// it invokes the provided `callback`, and pass the connection to the callback.
+    pub async fn connect_with_cback<Fut>(
+        self: &Arc<Self>,
+        endpoint: &Endpoint,
+        peer_id: &Option<PeerID>,
+        callback: impl FnOnce(Conn) -> Fut + Send + 'static,
+    ) -> Result<()>
+    where
+        Fut: Future<Output = Result<()>> + Send + 'static,
+    {
+        let conn = self.connect(endpoint, peer_id).await?;
+
+        let selfc = self.clone();
+        let endpoint = endpoint.clone();
+        let on_disconnect = |res| async move {
+            if let TaskResult::Completed(Err(err)) = res {
+                trace!("Outbound connection dropped: {err}");
+            }
+            selfc
+                .monitor
+                .notify(&ConnEvent::Disconnected(endpoint.clone()).into())
+                .await;
+            selfc.connection_slots.remove().await;
+        };
+
+        self.task_group.spawn(callback(conn), on_disconnect);
+
+        Ok(())
+    }
+
+    async fn dial(&self, endpoint: &Endpoint, peer_id: &Option<PeerID>) -> Result<Conn> {
+        if self.enable_tls {
+            let tls_config = tls_client_config(&self.key_pair, peer_id.clone())?;
+            tls::dial(endpoint, tls_config, DNS_NAME).await
+        } else {
+            dial(endpoint).await
+        }
+        .map_err(Error::KaryonNet)
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/discovery/lookup.rs.html b/src/karyon_p2p/discovery/lookup.rs.html new file mode 100644 index 00000000..3be71c3e --- /dev/null +++ b/src/karyon_p2p/discovery/lookup.rs.html @@ -0,0 +1,802 @@ +lookup.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+
use std::{sync::Arc, time::Duration};
+
+use futures_util::{stream::FuturesUnordered, StreamExt};
+use log::{error, trace};
+use rand::{rngs::OsRng, seq::SliceRandom, RngCore};
+use smol::lock::{Mutex, RwLock};
+
+use karyon_core::{async_util::timeout, crypto::KeyPair, util::decode, GlobalExecutor};
+
+use karyon_net::{Conn, Endpoint};
+
+use crate::{
+    codec::Codec,
+    connector::Connector,
+    listener::Listener,
+    message::{
+        get_msg_payload, FindPeerMsg, NetMsg, NetMsgCmd, PeerMsg, PeersMsg, PingMsg, PongMsg,
+        ShutdownMsg,
+    },
+    monitor::{ConnEvent, DiscoveryEvent, Monitor},
+    routing_table::RoutingTable,
+    slots::ConnectionSlots,
+    version::version_match,
+    Config, Error, PeerID, Result,
+};
+
+/// Maximum number of peers that can be returned in a PeersMsg.
+pub const MAX_PEERS_IN_PEERSMSG: usize = 10;
+
+pub struct LookupService {
+    /// Peer's ID
+    id: PeerID,
+
+    /// Routing Table
+    table: Arc<Mutex<RoutingTable>>,
+
+    /// Listener
+    listener: Arc<Listener>,
+    /// Connector
+    connector: Arc<Connector>,
+
+    /// Outbound slots.
+    outbound_slots: Arc<ConnectionSlots>,
+
+    /// Resolved listen endpoint
+    listen_endpoint: Option<RwLock<Endpoint>>,
+
+    /// Holds the configuration for the P2P network.
+    config: Arc<Config>,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+}
+
+impl LookupService {
+    /// Creates a new lookup service
+    pub fn new(
+        key_pair: &KeyPair,
+        id: &PeerID,
+        table: Arc<Mutex<RoutingTable>>,
+        config: Arc<Config>,
+        monitor: Arc<Monitor>,
+        ex: GlobalExecutor,
+    ) -> Self {
+        let inbound_slots = Arc::new(ConnectionSlots::new(config.lookup_inbound_slots));
+        let outbound_slots = Arc::new(ConnectionSlots::new(config.lookup_outbound_slots));
+
+        let listener = Listener::new(
+            key_pair,
+            inbound_slots.clone(),
+            config.enable_tls,
+            monitor.clone(),
+            ex.clone(),
+        );
+
+        let connector = Connector::new(
+            key_pair,
+            config.lookup_connect_retries,
+            outbound_slots.clone(),
+            config.enable_tls,
+            monitor.clone(),
+            ex,
+        );
+
+        let listen_endpoint = config
+            .listen_endpoint
+            .as_ref()
+            .map(|endpoint| RwLock::new(endpoint.clone()));
+
+        Self {
+            id: id.clone(),
+            table,
+            listener,
+            connector,
+            outbound_slots,
+            listen_endpoint,
+            config,
+            monitor,
+        }
+    }
+
+    /// Start the lookup service.
+    pub async fn start(self: &Arc<Self>) -> Result<()> {
+        self.start_listener().await?;
+        Ok(())
+    }
+
+    /// Set the resolved listen endpoint.
+    pub async fn set_listen_endpoint(&self, resolved_endpoint: &Endpoint) {
+        if let Some(endpoint) = &self.listen_endpoint {
+            *endpoint.write().await = resolved_endpoint.clone();
+        }
+    }
+
+    /// Shuts down the lookup service.
+    pub async fn shutdown(&self) {
+        self.connector.shutdown().await;
+        self.listener.shutdown().await;
+    }
+
+    /// Starts iterative lookup and populate the routing table.
+    ///
+    /// This method begins by generating a random peer ID and connecting to the
+    /// provided endpoint. It then sends a FindPeer message containing the
+    /// randomly generated peer ID. Upon receiving peers from the initial lookup,
+    /// it starts connecting to these received peers and sends them a FindPeer
+    /// message that contains our own peer ID.
+    pub async fn start_lookup(&self, endpoint: &Endpoint, peer_id: Option<PeerID>) -> Result<()> {
+        trace!("Lookup started {endpoint}");
+        self.monitor
+            .notify(&DiscoveryEvent::LookupStarted(endpoint.clone()).into())
+            .await;
+
+        let mut random_peers = vec![];
+        if let Err(err) = self
+            .random_lookup(endpoint, peer_id, &mut random_peers)
+            .await
+        {
+            self.monitor
+                .notify(&DiscoveryEvent::LookupFailed(endpoint.clone()).into())
+                .await;
+            return Err(err);
+        };
+
+        let mut peer_buffer = vec![];
+        self.self_lookup(&random_peers, &mut peer_buffer).await;
+
+        while peer_buffer.len() < MAX_PEERS_IN_PEERSMSG {
+            match random_peers.pop() {
+                Some(p) => peer_buffer.push(p),
+                None => break,
+            }
+        }
+
+        let mut table = self.table.lock().await;
+        for peer in peer_buffer.iter() {
+            let result = table.add_entry(peer.clone().into());
+            trace!("Add entry {:?}", result);
+        }
+        drop(table);
+
+        self.monitor
+            .notify(&DiscoveryEvent::LookupSucceeded(endpoint.clone(), peer_buffer.len()).into())
+            .await;
+
+        Ok(())
+    }
+
+    /// Starts a random lookup
+    ///
+    /// This will perfom lookup on a random generated PeerID
+    async fn random_lookup(
+        &self,
+        endpoint: &Endpoint,
+        peer_id: Option<PeerID>,
+        random_peers: &mut Vec<PeerMsg>,
+    ) -> Result<()> {
+        for _ in 0..2 {
+            let random_peer_id = PeerID::random();
+            let peers = self
+                .connect(endpoint.clone(), peer_id.clone(), &random_peer_id)
+                .await?;
+
+            let table = self.table.lock().await;
+            for peer in peers {
+                if random_peers.contains(&peer)
+                    || peer.peer_id == self.id
+                    || table.contains_key(&peer.peer_id.0)
+                {
+                    continue;
+                }
+
+                random_peers.push(peer);
+            }
+        }
+
+        Ok(())
+    }
+
+    /// Starts a self lookup
+    async fn self_lookup(&self, random_peers: &Vec<PeerMsg>, peer_buffer: &mut Vec<PeerMsg>) {
+        let mut tasks = FuturesUnordered::new();
+        for peer in random_peers.choose_multiple(&mut OsRng, random_peers.len()) {
+            let endpoint = Endpoint::Tcp(peer.addr.clone(), peer.discovery_port);
+            tasks.push(self.connect(endpoint, Some(peer.peer_id.clone()), &self.id))
+        }
+
+        while let Some(result) = tasks.next().await {
+            match result {
+                Ok(peers) => peer_buffer.extend(peers),
+                Err(err) => {
+                    error!("Failed to do self lookup: {err}");
+                }
+            }
+        }
+    }
+
+    /// Connects to the given endpoint and initiates a lookup process for the
+    /// provided peer ID.
+    async fn connect(
+        &self,
+        endpoint: Endpoint,
+        peer_id: Option<PeerID>,
+        target_peer_id: &PeerID,
+    ) -> Result<Vec<PeerMsg>> {
+        let conn = self.connector.connect(&endpoint, &peer_id).await?;
+        let io_codec = Codec::new(conn);
+        let result = self.handle_outbound(io_codec, target_peer_id).await;
+
+        self.monitor
+            .notify(&ConnEvent::Disconnected(endpoint).into())
+            .await;
+        self.outbound_slots.remove().await;
+
+        result
+    }
+
+    /// Handles outbound connection
+    async fn handle_outbound(
+        &self,
+        io_codec: Codec,
+        target_peer_id: &PeerID,
+    ) -> Result<Vec<PeerMsg>> {
+        trace!("Send Ping msg");
+        self.send_ping_msg(&io_codec).await?;
+
+        trace!("Send FindPeer msg");
+        let peers = self.send_findpeer_msg(&io_codec, target_peer_id).await?;
+
+        if peers.0.len() >= MAX_PEERS_IN_PEERSMSG {
+            return Err(Error::Lookup("Received too many peers in PeersMsg"));
+        }
+
+        trace!("Send Peer msg");
+        if let Some(endpoint) = &self.listen_endpoint {
+            self.send_peer_msg(&io_codec, endpoint.read().await.clone())
+                .await?;
+        }
+
+        trace!("Send Shutdown msg");
+        self.send_shutdown_msg(&io_codec).await?;
+
+        Ok(peers.0)
+    }
+
+    /// Start a listener.
+    async fn start_listener(self: &Arc<Self>) -> Result<()> {
+        let addr = match &self.listen_endpoint {
+            Some(a) => a.read().await.addr()?.clone(),
+            None => return Ok(()),
+        };
+
+        let endpoint = Endpoint::Tcp(addr, self.config.discovery_port);
+
+        let selfc = self.clone();
+        let callback = |conn: Conn| async move {
+            let t = Duration::from_secs(selfc.config.lookup_connection_lifespan);
+            timeout(t, selfc.handle_inbound(conn)).await??;
+            Ok(())
+        };
+
+        self.listener.start(endpoint.clone(), callback).await?;
+        Ok(())
+    }
+
+    /// Handles inbound connection
+    async fn handle_inbound(self: &Arc<Self>, conn: Conn) -> Result<()> {
+        let io_codec = Codec::new(conn);
+        loop {
+            let msg: NetMsg = io_codec.read().await?;
+            trace!("Receive msg {:?}", msg.header.command);
+
+            if let NetMsgCmd::Shutdown = msg.header.command {
+                return Ok(());
+            }
+
+            match &msg.header.command {
+                NetMsgCmd::Ping => {
+                    let (ping_msg, _) = decode::<PingMsg>(&msg.payload)?;
+                    if !version_match(&self.config.version.req, &ping_msg.version) {
+                        return Err(Error::IncompatibleVersion("system: {}".into()));
+                    }
+                    self.send_pong_msg(ping_msg.nonce, &io_codec).await?;
+                }
+                NetMsgCmd::FindPeer => {
+                    let (findpeer_msg, _) = decode::<FindPeerMsg>(&msg.payload)?;
+                    let peer_id = findpeer_msg.0;
+                    self.send_peers_msg(&peer_id, &io_codec).await?;
+                }
+                NetMsgCmd::Peer => {
+                    let (peer, _) = decode::<PeerMsg>(&msg.payload)?;
+                    let result = self.table.lock().await.add_entry(peer.clone().into());
+                    trace!("Add entry result: {:?}", result);
+                }
+                c => return Err(Error::InvalidMsg(format!("Unexpected msg: {:?}", c))),
+            }
+        }
+    }
+
+    /// Sends a Ping msg and wait to receive the Pong message.
+    async fn send_ping_msg(&self, io_codec: &Codec) -> Result<()> {
+        trace!("Send Pong msg");
+
+        let mut nonce: [u8; 32] = [0; 32];
+        RngCore::fill_bytes(&mut OsRng, &mut nonce);
+
+        let ping_msg = PingMsg {
+            version: self.config.version.v.clone(),
+            nonce,
+        };
+        io_codec.write(NetMsgCmd::Ping, &ping_msg).await?;
+
+        let t = Duration::from_secs(self.config.lookup_response_timeout);
+        let recv_msg: NetMsg = io_codec.read_timeout(t).await?;
+
+        let payload = get_msg_payload!(Pong, recv_msg);
+        let (pong_msg, _) = decode::<PongMsg>(&payload)?;
+
+        if ping_msg.nonce != pong_msg.0 {
+            return Err(Error::InvalidPongMsg);
+        }
+
+        Ok(())
+    }
+
+    /// Sends a Pong msg
+    async fn send_pong_msg(&self, nonce: [u8; 32], io_codec: &Codec) -> Result<()> {
+        trace!("Send Pong msg");
+        io_codec.write(NetMsgCmd::Pong, &PongMsg(nonce)).await?;
+        Ok(())
+    }
+
+    /// Sends a FindPeer msg and wait to receivet the Peers msg.
+    async fn send_findpeer_msg(&self, io_codec: &Codec, peer_id: &PeerID) -> Result<PeersMsg> {
+        trace!("Send FindPeer msg");
+        io_codec
+            .write(NetMsgCmd::FindPeer, &FindPeerMsg(peer_id.clone()))
+            .await?;
+
+        let t = Duration::from_secs(self.config.lookup_response_timeout);
+        let recv_msg: NetMsg = io_codec.read_timeout(t).await?;
+
+        let payload = get_msg_payload!(Peers, recv_msg);
+        let (peers, _) = decode(&payload)?;
+
+        Ok(peers)
+    }
+
+    /// Sends a Peers msg.
+    async fn send_peers_msg(&self, peer_id: &PeerID, io_codec: &Codec) -> Result<()> {
+        trace!("Send Peers msg");
+        let table = self.table.lock().await;
+        let entries = table.closest_entries(&peer_id.0, MAX_PEERS_IN_PEERSMSG);
+        drop(table);
+
+        let peers: Vec<PeerMsg> = entries.into_iter().map(|e| e.into()).collect();
+        io_codec.write(NetMsgCmd::Peers, &PeersMsg(peers)).await?;
+        Ok(())
+    }
+
+    /// Sends a Peer msg.
+    async fn send_peer_msg(&self, io_codec: &Codec, endpoint: Endpoint) -> Result<()> {
+        trace!("Send Peer msg");
+        let peer_msg = PeerMsg {
+            addr: endpoint.addr()?.clone(),
+            port: *endpoint.port()?,
+            discovery_port: self.config.discovery_port,
+            peer_id: self.id.clone(),
+        };
+        io_codec.write(NetMsgCmd::Peer, &peer_msg).await?;
+        Ok(())
+    }
+
+    /// Sends a Shutdown msg.
+    async fn send_shutdown_msg(&self, io_codec: &Codec) -> Result<()> {
+        trace!("Send Shutdown msg");
+        io_codec.write(NetMsgCmd::Shutdown, &ShutdownMsg(0)).await?;
+        Ok(())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/discovery/mod.rs.html b/src/karyon_p2p/discovery/mod.rs.html new file mode 100644 index 00000000..53bad16b --- /dev/null +++ b/src/karyon_p2p/discovery/mod.rs.html @@ -0,0 +1,612 @@ +mod.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+
mod lookup;
+mod refresh;
+
+use std::sync::Arc;
+
+use log::{error, info};
+use rand::{rngs::OsRng, seq::SliceRandom};
+use smol::lock::Mutex;
+
+use karyon_core::{
+    async_util::{Backoff, TaskGroup, TaskResult},
+    crypto::KeyPair,
+    GlobalExecutor,
+};
+
+use karyon_net::{Conn, Endpoint};
+
+use crate::{
+    config::Config,
+    connection::{ConnDirection, ConnQueue},
+    connector::Connector,
+    listener::Listener,
+    monitor::Monitor,
+    routing_table::{
+        Entry, EntryStatusFlag, RoutingTable, CONNECTED_ENTRY, DISCONNECTED_ENTRY,
+        INCOMPATIBLE_ENTRY, PENDING_ENTRY, UNREACHABLE_ENTRY, UNSTABLE_ENTRY,
+    },
+    slots::ConnectionSlots,
+    Error, PeerID, Result,
+};
+
+use lookup::LookupService;
+use refresh::RefreshService;
+
+pub type ArcDiscovery = Arc<Discovery>;
+
+pub struct Discovery {
+    /// Routing table
+    table: Arc<Mutex<RoutingTable>>,
+
+    /// Lookup Service
+    lookup_service: Arc<LookupService>,
+
+    /// Refresh Service
+    refresh_service: Arc<RefreshService>,
+
+    /// Connector
+    connector: Arc<Connector>,
+    /// Listener
+    listener: Arc<Listener>,
+
+    /// Connection queue
+    conn_queue: Arc<ConnQueue>,
+
+    /// Inbound slots.
+    pub(crate) inbound_slots: Arc<ConnectionSlots>,
+    /// Outbound slots.
+    pub(crate) outbound_slots: Arc<ConnectionSlots>,
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+
+    /// Holds the configuration for the P2P network.
+    config: Arc<Config>,
+}
+
+impl Discovery {
+    /// Creates a new Discovery
+    pub fn new(
+        key_pair: &KeyPair,
+        peer_id: &PeerID,
+        conn_queue: Arc<ConnQueue>,
+        config: Arc<Config>,
+        monitor: Arc<Monitor>,
+        ex: GlobalExecutor,
+    ) -> ArcDiscovery {
+        let inbound_slots = Arc::new(ConnectionSlots::new(config.inbound_slots));
+        let outbound_slots = Arc::new(ConnectionSlots::new(config.outbound_slots));
+
+        let table_key = peer_id.0;
+        let table = Arc::new(Mutex::new(RoutingTable::new(table_key)));
+
+        let refresh_service =
+            RefreshService::new(config.clone(), table.clone(), monitor.clone(), ex.clone());
+        let lookup_service = LookupService::new(
+            key_pair,
+            peer_id,
+            table.clone(),
+            config.clone(),
+            monitor.clone(),
+            ex.clone(),
+        );
+
+        let connector = Connector::new(
+            key_pair,
+            config.max_connect_retries,
+            outbound_slots.clone(),
+            config.enable_tls,
+            monitor.clone(),
+            ex.clone(),
+        );
+
+        let listener = Listener::new(
+            key_pair,
+            inbound_slots.clone(),
+            config.enable_tls,
+            monitor.clone(),
+            ex.clone(),
+        );
+
+        Arc::new(Self {
+            refresh_service: Arc::new(refresh_service),
+            lookup_service: Arc::new(lookup_service),
+            conn_queue,
+            table,
+            inbound_slots,
+            outbound_slots,
+            connector,
+            listener,
+            task_group: TaskGroup::new(ex),
+            config,
+        })
+    }
+
+    /// Start the Discovery
+    pub async fn start(self: &Arc<Self>) -> Result<()> {
+        // Check if the listen_endpoint is provided, and if so, start a listener.
+        if let Some(endpoint) = &self.config.listen_endpoint {
+            // Return an error if the discovery port is set to 0.
+            if self.config.discovery_port == 0 {
+                return Err(Error::Config(
+                    "Please add a valid discovery port".to_string(),
+                ));
+            }
+
+            let resolved_endpoint = self.start_listener(endpoint).await?;
+
+            if endpoint.addr()? != resolved_endpoint.addr()? {
+                info!("Resolved listen endpoint: {resolved_endpoint}");
+                self.lookup_service
+                    .set_listen_endpoint(&resolved_endpoint)
+                    .await;
+                self.refresh_service
+                    .set_listen_endpoint(&resolved_endpoint)
+                    .await;
+            }
+        }
+
+        // Start the lookup service
+        self.lookup_service.start().await?;
+        // Start the refresh service
+        self.refresh_service.start().await?;
+
+        // Attempt to manually connect to peer endpoints provided in the Config.
+        for endpoint in self.config.peer_endpoints.iter() {
+            let _ = self.connect(endpoint, None).await;
+        }
+
+        // Start connect loop
+        let selfc = self.clone();
+        self.task_group
+            .spawn(selfc.connect_loop(), |res| async move {
+                if let TaskResult::Completed(Err(err)) = res {
+                    error!("Connect loop stopped: {err}");
+                }
+            });
+
+        Ok(())
+    }
+
+    /// Shuts down the discovery
+    pub async fn shutdown(&self) {
+        self.task_group.cancel().await;
+        self.connector.shutdown().await;
+        self.listener.shutdown().await;
+
+        self.refresh_service.shutdown().await;
+        self.lookup_service.shutdown().await;
+    }
+
+    /// Start a listener and on success, return the resolved endpoint.
+    async fn start_listener(self: &Arc<Self>, endpoint: &Endpoint) -> Result<Endpoint> {
+        let selfc = self.clone();
+        let callback = |c: Conn| async move {
+            selfc.conn_queue.handle(c, ConnDirection::Inbound).await?;
+            Ok(())
+        };
+
+        let resolved_endpoint = self.listener.start(endpoint.clone(), callback).await?;
+        Ok(resolved_endpoint)
+    }
+
+    /// This method will attempt to connect to a peer in the routing table.
+    /// If the routing table is empty, it will start the seeding process for
+    /// finding new peers.
+    ///
+    /// This will perform a backoff to prevent getting stuck in the loop
+    /// if the seeding process couldn't find any peers.
+    async fn connect_loop(self: Arc<Self>) -> Result<()> {
+        let backoff = Backoff::new(500, self.config.seeding_interval * 1000);
+        loop {
+            let random_entry = self.random_entry(PENDING_ENTRY).await;
+            match random_entry {
+                Some(entry) => {
+                    backoff.reset();
+                    let endpoint = Endpoint::Tcp(entry.addr, entry.port);
+                    self.connect(&endpoint, Some(entry.key.into())).await;
+                }
+                None => {
+                    backoff.sleep().await;
+                    self.start_seeding().await;
+                }
+            }
+        }
+    }
+
+    /// Connect to the given endpoint using the connector
+    async fn connect(self: &Arc<Self>, endpoint: &Endpoint, pid: Option<PeerID>) {
+        let selfc = self.clone();
+        let pid_c = pid.clone();
+        let endpoint_c = endpoint.clone();
+        let cback = |conn: Conn| async move {
+            let result = selfc.conn_queue.handle(conn, ConnDirection::Outbound).await;
+
+            // If the entry is not in the routing table, ignore the result
+            let pid = match pid_c {
+                Some(p) => p,
+                None => return Ok(()),
+            };
+
+            match result {
+                Err(Error::IncompatiblePeer) => {
+                    error!("Failed to do handshake: {endpoint_c} incompatible peer");
+                    selfc.update_entry(&pid, INCOMPATIBLE_ENTRY).await;
+                }
+                Err(Error::PeerAlreadyConnected) => {
+                    // TODO: Use the appropriate status.
+                    selfc.update_entry(&pid, DISCONNECTED_ENTRY).await;
+                }
+                Err(_) => {
+                    selfc.update_entry(&pid, UNSTABLE_ENTRY).await;
+                }
+                Ok(_) => {
+                    selfc.update_entry(&pid, DISCONNECTED_ENTRY).await;
+                }
+            }
+
+            Ok(())
+        };
+
+        let result = self
+            .connector
+            .connect_with_cback(endpoint, &pid, cback)
+            .await;
+
+        if let Some(pid) = &pid {
+            match result {
+                Ok(_) => {
+                    self.update_entry(pid, CONNECTED_ENTRY).await;
+                }
+                Err(_) => {
+                    self.update_entry(pid, UNREACHABLE_ENTRY).await;
+                }
+            }
+        }
+    }
+
+    /// Starts seeding process.
+    ///
+    /// This method randomly selects a peer from the routing table and
+    /// attempts to connect to that peer for the initial lookup. If the routing
+    /// table doesn't have an available entry, it will connect to one of the
+    /// provided bootstrap endpoints in the `Config` and initiate the lookup.
+    async fn start_seeding(&self) {
+        match self.random_entry(PENDING_ENTRY | CONNECTED_ENTRY).await {
+            Some(entry) => {
+                let endpoint = Endpoint::Tcp(entry.addr, entry.discovery_port);
+                let peer_id = Some(entry.key.into());
+                if let Err(err) = self.lookup_service.start_lookup(&endpoint, peer_id).await {
+                    self.update_entry(&entry.key.into(), UNSTABLE_ENTRY).await;
+                    error!("Failed to do lookup: {endpoint}: {err}");
+                }
+            }
+            None => {
+                let peers = &self.config.bootstrap_peers;
+                for endpoint in peers.choose_multiple(&mut OsRng, peers.len()) {
+                    if let Err(err) = self.lookup_service.start_lookup(endpoint, None).await {
+                        error!("Failed to do lookup: {endpoint}: {err}");
+                    }
+                }
+            }
+        }
+    }
+
+    /// Returns a random entry from routing table.
+    async fn random_entry(&self, entry_flag: EntryStatusFlag) -> Option<Entry> {
+        self.table.lock().await.random_entry(entry_flag).cloned()
+    }
+
+    /// Update the entry status  
+    async fn update_entry(&self, pid: &PeerID, entry_flag: EntryStatusFlag) {
+        let table = &mut self.table.lock().await;
+        table.update_entry(&pid.0, entry_flag);
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/discovery/refresh.rs.html b/src/karyon_p2p/discovery/refresh.rs.html new file mode 100644 index 00000000..4f778098 --- /dev/null +++ b/src/karyon_p2p/discovery/refresh.rs.html @@ -0,0 +1,580 @@ +refresh.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+
use std::{sync::Arc, time::Duration};
+
+use bincode::{Decode, Encode};
+use log::{error, info, trace};
+use rand::{rngs::OsRng, RngCore};
+use smol::{
+    lock::{Mutex, RwLock},
+    stream::StreamExt,
+    Timer,
+};
+
+use karyon_core::{
+    async_util::{timeout, Backoff, TaskGroup, TaskResult},
+    util::{decode, encode},
+    GlobalExecutor,
+};
+
+use karyon_net::{dial_udp, listen_udp, Addr, Connection, Endpoint, NetError, Port, UdpConn};
+
+/// Maximum failures for an entry before removing it from the routing table.
+pub const MAX_FAILURES: u32 = 3;
+
+/// Ping message size
+const PINGMSG_SIZE: usize = 32;
+
+use crate::{
+    monitor::{ConnEvent, DiscoveryEvent, Monitor},
+    routing_table::{BucketEntry, Entry, RoutingTable, PENDING_ENTRY, UNREACHABLE_ENTRY},
+    Config, Error, Result,
+};
+
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct PingMsg(pub [u8; 32]);
+
+#[derive(Decode, Encode, Debug)]
+pub struct PongMsg(pub [u8; 32]);
+
+pub struct RefreshService {
+    /// Routing table
+    table: Arc<Mutex<RoutingTable>>,
+
+    /// Resolved listen endpoint
+    listen_endpoint: Option<RwLock<Endpoint>>,
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+
+    /// A global executor
+    executor: GlobalExecutor,
+
+    /// Holds the configuration for the P2P network.
+    config: Arc<Config>,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+}
+
+impl RefreshService {
+    /// Creates a new refresh service
+    pub fn new(
+        config: Arc<Config>,
+        table: Arc<Mutex<RoutingTable>>,
+        monitor: Arc<Monitor>,
+        executor: GlobalExecutor,
+    ) -> Self {
+        let listen_endpoint = config
+            .listen_endpoint
+            .as_ref()
+            .map(|endpoint| RwLock::new(endpoint.clone()));
+
+        Self {
+            table,
+            listen_endpoint,
+            task_group: TaskGroup::new(executor.clone()),
+            executor,
+            config,
+            monitor,
+        }
+    }
+
+    /// Start the refresh service
+    pub async fn start(self: &Arc<Self>) -> Result<()> {
+        if let Some(endpoint) = &self.listen_endpoint {
+            let endpoint = endpoint.read().await;
+            let addr = endpoint.addr()?;
+            let port = self.config.discovery_port;
+
+            let selfc = self.clone();
+            self.task_group
+                .spawn(selfc.listen_loop(addr.clone(), port), |res| async move {
+                    if let TaskResult::Completed(Err(err)) = res {
+                        error!("Listen loop stopped: {err}");
+                    }
+                });
+        }
+
+        let selfc = self.clone();
+        self.task_group
+            .spawn(selfc.refresh_loop(), |res| async move {
+                if let TaskResult::Completed(Err(err)) = res {
+                    error!("Refresh loop stopped: {err}");
+                }
+            });
+
+        Ok(())
+    }
+
+    /// Set the resolved listen endpoint.
+    pub async fn set_listen_endpoint(&self, resolved_endpoint: &Endpoint) {
+        if let Some(endpoint) = &self.listen_endpoint {
+            *endpoint.write().await = resolved_endpoint.clone();
+        }
+    }
+
+    /// Shuts down the refresh service
+    pub async fn shutdown(&self) {
+        self.task_group.cancel().await;
+    }
+
+    /// Initiates periodic refreshing of the routing table. This function will
+    /// selects the first 8 entries (oldest entries) from each bucket in the
+    /// routing table and starts sending Ping messages to the collected entries.
+    async fn refresh_loop(self: Arc<Self>) -> Result<()> {
+        let mut timer = Timer::interval(Duration::from_secs(self.config.refresh_interval));
+        loop {
+            timer.next().await;
+            trace!("Start refreshing the routing table...");
+
+            self.monitor
+                .notify(&DiscoveryEvent::RefreshStarted.into())
+                .await;
+
+            let mut entries: Vec<BucketEntry> = vec![];
+            for bucket in self.table.lock().await.iter() {
+                for entry in bucket
+                    .iter()
+                    .filter(|e| !e.is_connected() && !e.is_incompatible())
+                    .take(8)
+                {
+                    entries.push(entry.clone())
+                }
+            }
+
+            self.clone().do_refresh(&entries).await;
+        }
+    }
+
+    /// Iterates over the entries and spawns a new task for each entry to
+    /// initiate a connection attempt.
+    async fn do_refresh(self: Arc<Self>, entries: &[BucketEntry]) {
+        let ex = &self.executor;
+        // Enforce a maximum of 16 concurrent connections.
+        for chunk in entries.chunks(16) {
+            let mut tasks = Vec::new();
+            for bucket_entry in chunk {
+                if bucket_entry.failures >= MAX_FAILURES {
+                    self.table
+                        .lock()
+                        .await
+                        .remove_entry(&bucket_entry.entry.key);
+                    continue;
+                }
+
+                tasks.push(ex.spawn(self.clone().refresh_entry(bucket_entry.clone())))
+            }
+
+            for task in tasks {
+                task.await;
+            }
+        }
+    }
+
+    /// Initiates refresh for a specific entry within the routing table. It
+    /// updates the routing table according to the result.
+    async fn refresh_entry(self: Arc<Self>, bucket_entry: BucketEntry) {
+        let key = &bucket_entry.entry.key;
+        match self.connect(&bucket_entry.entry).await {
+            Ok(_) => {
+                self.table.lock().await.update_entry(key, PENDING_ENTRY);
+            }
+            Err(err) => {
+                trace!("Failed to refresh entry {:?}: {err}", key);
+                let table = &mut self.table.lock().await;
+                if bucket_entry.failures >= MAX_FAILURES {
+                    table.remove_entry(key);
+                    return;
+                }
+                table.update_entry(key, UNREACHABLE_ENTRY);
+            }
+        }
+    }
+
+    /// Initiates a UDP connection with the entry and attempts to send a Ping
+    /// message. If it fails, it retries according to the allowed retries
+    /// specified in the Config, with backoff between each retry.
+    async fn connect(&self, entry: &Entry) -> Result<()> {
+        let mut retry = 0;
+        let endpoint = Endpoint::Ws(entry.addr.clone(), entry.discovery_port);
+        let conn = dial_udp(&endpoint).await?;
+        let backoff = Backoff::new(100, 5000);
+        while retry < self.config.refresh_connect_retries {
+            match self.send_ping_msg(&conn).await {
+                Ok(()) => return Ok(()),
+                Err(Error::KaryonNet(NetError::Timeout)) => {
+                    retry += 1;
+                    backoff.sleep().await;
+                }
+                Err(err) => {
+                    return Err(err);
+                }
+            }
+        }
+
+        Err(NetError::Timeout.into())
+    }
+
+    /// Set up a UDP listener and start listening for Ping messages from other
+    /// peers.
+    async fn listen_loop(self: Arc<Self>, addr: Addr, port: Port) -> Result<()> {
+        let endpoint = Endpoint::Udp(addr.clone(), port);
+        let conn = match listen_udp(&endpoint).await {
+            Ok(c) => {
+                self.monitor
+                    .notify(&ConnEvent::Listening(endpoint.clone()).into())
+                    .await;
+                c
+            }
+            Err(err) => {
+                self.monitor
+                    .notify(&ConnEvent::ListenFailed(endpoint.clone()).into())
+                    .await;
+                return Err(err.into());
+            }
+        };
+        info!("Start listening on {endpoint}");
+
+        loop {
+            let res = self.listen_to_ping_msg(&conn).await;
+            if let Err(err) = res {
+                trace!("Failed to handle ping msg {err}");
+                self.monitor.notify(&ConnEvent::AcceptFailed.into()).await;
+            }
+        }
+    }
+
+    /// Listen to receive a Ping message and respond with a Pong message.
+    async fn listen_to_ping_msg(&self, conn: &UdpConn) -> Result<()> {
+        let mut buf = [0; PINGMSG_SIZE];
+        let (_, endpoint) = conn.recv_from(&mut buf).await?;
+
+        self.monitor
+            .notify(&ConnEvent::Accepted(endpoint.clone()).into())
+            .await;
+
+        let (ping_msg, _) = decode::<PingMsg>(&buf)?;
+
+        let pong_msg = PongMsg(ping_msg.0);
+        let buffer = encode(&pong_msg)?;
+
+        conn.send_to(&buffer, &endpoint).await?;
+
+        self.monitor
+            .notify(&ConnEvent::Disconnected(endpoint.clone()).into())
+            .await;
+        Ok(())
+    }
+
+    /// Sends a Ping msg and wait to receive the Pong message.
+    async fn send_ping_msg(&self, conn: &UdpConn) -> Result<()> {
+        let mut nonce: [u8; 32] = [0; 32];
+        RngCore::fill_bytes(&mut OsRng, &mut nonce);
+
+        let ping_msg = PingMsg(nonce);
+        let buffer = encode(&ping_msg)?;
+        conn.write(&buffer).await?;
+
+        let buf = &mut [0; PINGMSG_SIZE];
+        let t = Duration::from_secs(self.config.refresh_response_timeout);
+        timeout(t, conn.read(buf)).await??;
+
+        let (pong_msg, _) = decode::<PongMsg>(buf)?;
+
+        if ping_msg.0 != pong_msg.0 {
+            return Err(Error::InvalidPongMsg);
+        }
+
+        Ok(())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/error.rs.html b/src/karyon_p2p/error.rs.html new file mode 100644 index 00000000..51caaba8 --- /dev/null +++ b/src/karyon_p2p/error.rs.html @@ -0,0 +1,178 @@ +error.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+
use thiserror::Error as ThisError;
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Represents karyon's p2p Error.
+#[derive(ThisError, Debug)]
+pub enum Error {
+    #[error(transparent)]
+    IO(#[from] std::io::Error),
+
+    #[error("Unsupported protocol error: {0}")]
+    UnsupportedProtocol(String),
+
+    #[error("Try from public key Error: {0}")]
+    TryFromPublicKey(&'static str),
+
+    #[error("Invalid message error: {0}")]
+    InvalidMsg(String),
+
+    #[error("Incompatible Peer")]
+    IncompatiblePeer,
+
+    #[error(transparent)]
+    ParseIntError(#[from] std::num::ParseIntError),
+
+    #[error(transparent)]
+    ParseFloatError(#[from] std::num::ParseFloatError),
+
+    #[error(transparent)]
+    SemverError(#[from] semver::Error),
+
+    #[error("Parse Error: {0}")]
+    ParseError(String),
+
+    #[error("Incompatible version error: {0}")]
+    IncompatibleVersion(String),
+
+    #[error("Config error: {0}")]
+    Config(String),
+
+    #[error("Peer shutdown")]
+    PeerShutdown,
+
+    #[error("Invalid Pong Msg")]
+    InvalidPongMsg,
+
+    #[error("Discovery error: {0}")]
+    Discovery(&'static str),
+
+    #[error("Lookup error: {0}")]
+    Lookup(&'static str),
+
+    #[error("Peer already connected")]
+    PeerAlreadyConnected,
+
+    #[error("Yasna Error: {0}")]
+    Yasna(#[from] yasna::ASN1Error),
+
+    #[error("X509 Parser Error: {0}")]
+    X509Parser(#[from] x509_parser::error::X509Error),
+
+    #[error("Rcgen Error: {0}")]
+    Rcgen(#[from] rcgen::Error),
+
+    #[error("Tls Error: {0}")]
+    Rustls(#[from] futures_rustls::rustls::Error),
+
+    #[error("Invalid DNS Name: {0}")]
+    InvalidDnsNameError(#[from] futures_rustls::pki_types::InvalidDnsNameError),
+
+    #[error("Channel Send Error: {0}")]
+    ChannelSend(String),
+
+    #[error(transparent)]
+    ChannelRecv(#[from] smol::channel::RecvError),
+
+    #[error(transparent)]
+    KaryonCore(#[from] karyon_core::error::Error),
+
+    #[error(transparent)]
+    KaryonNet(#[from] karyon_net::NetError),
+}
+
+impl<T> From<smol::channel::SendError<T>> for Error {
+    fn from(error: smol::channel::SendError<T>) -> Self {
+        Error::ChannelSend(error.to_string())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/lib.rs.html b/src/karyon_p2p/lib.rs.html new file mode 100644 index 00000000..c2ee0b08 --- /dev/null +++ b/src/karyon_p2p/lib.rs.html @@ -0,0 +1,138 @@ +lib.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+
//! A lightweight, extensible, and customizable peer-to-peer (p2p) network stack.
+//!
+//! # Example
+//! ```
+//! use std::sync::Arc;
+//!
+//! use easy_parallel::Parallel;
+//! use smol::{channel as smol_channel, future, Executor};
+//!
+//! use karyon_core::crypto::{KeyPair, KeyPairType};
+//! use karyon_p2p::{Backend, Config, PeerID};
+//!
+//! let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+//!
+//! // Create the configuration for the backend.
+//! let mut config = Config::default();
+//!
+//! // Create a new Executor
+//! let ex = Arc::new(Executor::new());
+//!
+//! // Create a new Backend
+//! let backend = Backend::new(&key_pair, config, ex.clone());
+//!
+//! let task = async {
+//!     // Run the backend
+//!     backend.run().await.unwrap();
+//!
+//!     // ....
+//!
+//!     // Shutdown the backend
+//!     backend.shutdown().await;
+//! };
+//!
+//! future::block_on(ex.run(task));
+//!
+//! ```
+//!
+mod backend;
+mod codec;
+mod config;
+mod connection;
+mod connector;
+mod discovery;
+mod error;
+mod listener;
+mod message;
+mod peer;
+mod peer_pool;
+mod protocols;
+mod routing_table;
+mod slots;
+mod tls_config;
+mod version;
+
+/// Responsible for network and system monitoring.
+/// [`Read More`](./monitor/struct.Monitor.html)
+pub mod monitor;
+/// Defines the protocol trait.
+/// [`Read More`](./protocol/trait.Protocol.html)
+pub mod protocol;
+
+pub use backend::{ArcBackend, Backend};
+pub use config::Config;
+pub use error::Error as P2pError;
+pub use peer::{ArcPeer, PeerID};
+pub use version::Version;
+
+use error::{Error, Result};
+
\ No newline at end of file diff --git a/src/karyon_p2p/listener.rs.html b/src/karyon_p2p/listener.rs.html new file mode 100644 index 00000000..9882a1e6 --- /dev/null +++ b/src/karyon_p2p/listener.rs.html @@ -0,0 +1,334 @@ +listener.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+
use std::{future::Future, sync::Arc};
+
+use log::{debug, error, info};
+
+use karyon_core::{
+    async_util::{TaskGroup, TaskResult},
+    crypto::KeyPair,
+    GlobalExecutor,
+};
+
+use karyon_net::{listen, tls, Conn, ConnListener, Endpoint};
+
+use crate::{
+    monitor::{ConnEvent, Monitor},
+    slots::ConnectionSlots,
+    tls_config::tls_server_config,
+    Error, Result,
+};
+
+/// Responsible for creating inbound connections with other peers.
+pub struct Listener {
+    /// Identity Key pair
+    key_pair: KeyPair,
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+
+    /// Manages available inbound slots.
+    connection_slots: Arc<ConnectionSlots>,
+
+    /// Enables secure connection.
+    enable_tls: bool,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+}
+
+impl Listener {
+    /// Creates a new Listener
+    pub fn new(
+        key_pair: &KeyPair,
+        connection_slots: Arc<ConnectionSlots>,
+        enable_tls: bool,
+        monitor: Arc<Monitor>,
+        ex: GlobalExecutor,
+    ) -> Arc<Self> {
+        Arc::new(Self {
+            key_pair: key_pair.clone(),
+            connection_slots,
+            task_group: TaskGroup::new(ex),
+            enable_tls,
+            monitor,
+        })
+    }
+
+    /// Starts a listener on the given `endpoint`. For each incoming connection
+    /// that is accepted, it invokes the provided `callback`, and pass the
+    /// connection to the callback.
+    ///
+    /// Returns the resloved listening endpoint.
+    pub async fn start<Fut>(
+        self: &Arc<Self>,
+        endpoint: Endpoint,
+        // https://github.com/rust-lang/rfcs/pull/2132
+        callback: impl FnOnce(Conn) -> Fut + Clone + Send + 'static,
+    ) -> Result<Endpoint>
+    where
+        Fut: Future<Output = Result<()>> + Send + 'static,
+    {
+        let listener = match self.listend(&endpoint).await {
+            Ok(listener) => {
+                self.monitor
+                    .notify(&ConnEvent::Listening(endpoint.clone()).into())
+                    .await;
+                listener
+            }
+            Err(err) => {
+                error!("Failed to listen on {endpoint}: {err}");
+                self.monitor
+                    .notify(&ConnEvent::ListenFailed(endpoint).into())
+                    .await;
+                return Err(err);
+            }
+        };
+
+        let resolved_endpoint = listener.local_endpoint()?;
+
+        info!("Start listening on {resolved_endpoint}");
+
+        let selfc = self.clone();
+        self.task_group
+            .spawn(selfc.listen_loop(listener, callback), |_| async {});
+        Ok(resolved_endpoint)
+    }
+
+    /// Shuts down the listener
+    pub async fn shutdown(&self) {
+        self.task_group.cancel().await;
+    }
+
+    async fn listen_loop<Fut>(
+        self: Arc<Self>,
+        listener: Box<dyn ConnListener>,
+        callback: impl FnOnce(Conn) -> Fut + Clone + Send + 'static,
+    ) where
+        Fut: Future<Output = Result<()>> + Send + 'static,
+    {
+        loop {
+            // Wait for an available inbound slot.
+            self.connection_slots.wait_for_slot().await;
+            let result = listener.accept().await;
+
+            let (conn, endpoint) = match result {
+                Ok(c) => {
+                    let endpoint = match c.peer_endpoint() {
+                        Ok(e) => e,
+                        Err(err) => {
+                            self.monitor.notify(&ConnEvent::AcceptFailed.into()).await;
+                            error!("Failed to accept a new connection: {err}");
+                            continue;
+                        }
+                    };
+
+                    self.monitor
+                        .notify(&ConnEvent::Accepted(endpoint.clone()).into())
+                        .await;
+                    (c, endpoint)
+                }
+                Err(err) => {
+                    error!("Failed to accept a new connection: {err}");
+                    self.monitor.notify(&ConnEvent::AcceptFailed.into()).await;
+                    continue;
+                }
+            };
+
+            self.connection_slots.add();
+
+            let selfc = self.clone();
+            let on_disconnect = |res| async move {
+                if let TaskResult::Completed(Err(err)) = res {
+                    debug!("Inbound connection dropped: {err}");
+                }
+                selfc
+                    .monitor
+                    .notify(&ConnEvent::Disconnected(endpoint).into())
+                    .await;
+                selfc.connection_slots.remove().await;
+            };
+
+            let callback = callback.clone();
+            self.task_group.spawn(callback(conn), on_disconnect);
+        }
+    }
+
+    async fn listend(&self, endpoint: &Endpoint) -> Result<Box<dyn ConnListener>> {
+        if self.enable_tls {
+            let tls_config = tls_server_config(&self.key_pair)?;
+            tls::listen_tls(endpoint, tls_config)
+                .await
+                .map(|l| Box::new(l) as Box<dyn ConnListener>)
+        } else {
+            listen(endpoint).await
+        }
+        .map_err(Error::KaryonNet)
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/message.rs.html b/src/karyon_p2p/message.rs.html new file mode 100644 index 00000000..81d4919d --- /dev/null +++ b/src/karyon_p2p/message.rs.html @@ -0,0 +1,284 @@ +message.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+
use std::collections::HashMap;
+
+use bincode::{Decode, Encode};
+
+use karyon_net::{Addr, Port};
+
+use crate::{protocol::ProtocolID, routing_table::Entry, version::VersionInt, PeerID};
+
+/// The size of the message header, in bytes.
+pub const MSG_HEADER_SIZE: usize = 6;
+
+/// The maximum allowed size for a message in bytes.
+pub const MAX_ALLOWED_MSG_SIZE: u32 = 1024 * 1024; // 1MB
+
+/// Defines the main message in the karyon p2p network.
+///
+/// This message structure consists of a header and payload, where the header
+/// typically contains essential information about the message, and the payload
+/// contains the actual data being transmitted.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct NetMsg {
+    pub header: NetMsgHeader,
+    pub payload: Vec<u8>,
+}
+
+/// Represents the header of a message.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct NetMsgHeader {
+    pub command: NetMsgCmd,
+    pub payload_size: u32,
+}
+
+/// Defines message commands.
+#[derive(Decode, Encode, Debug, Clone)]
+#[repr(u8)]
+pub enum NetMsgCmd {
+    Version,
+    Verack,
+    Protocol,
+    Shutdown,
+
+    // NOTE: The following commands are used during the lookup process.
+    Ping,
+    Pong,
+    FindPeer,
+    Peer,
+    Peers,
+}
+
+/// Defines a message related to a specific protocol.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct ProtocolMsg {
+    pub protocol_id: ProtocolID,
+    pub payload: Vec<u8>,
+}
+
+/// Version message, providing information about a peer's capabilities.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct VerMsg {
+    pub peer_id: PeerID,
+    pub version: VersionInt,
+    pub protocols: HashMap<ProtocolID, VersionInt>,
+}
+
+/// VerAck message acknowledges the receipt of a Version message. The message
+/// consists of the peer ID and an acknowledgment boolean value indicating
+/// whether the version is accepted.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct VerAckMsg {
+    pub peer_id: PeerID,
+    pub ack: bool,
+}
+
+/// Shutdown message.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct ShutdownMsg(pub u8);
+
+/// Ping message with a nonce and version information.
+#[derive(Decode, Encode, Debug, Clone)]
+pub struct PingMsg {
+    pub nonce: [u8; 32],
+    pub version: VersionInt,
+}
+
+/// Ping message with a nonce.
+#[derive(Decode, Encode, Debug)]
+pub struct PongMsg(pub [u8; 32]);
+
+/// FindPeer message used to find a specific peer.
+#[derive(Decode, Encode, Debug)]
+pub struct FindPeerMsg(pub PeerID);
+
+/// PeerMsg containing information about a peer.
+#[derive(Decode, Encode, Debug, Clone, PartialEq, Eq)]
+pub struct PeerMsg {
+    pub peer_id: PeerID,
+    pub addr: Addr,
+    pub port: Port,
+    pub discovery_port: Port,
+}
+
+/// PeersMsg a list of `PeerMsg`.
+#[derive(Decode, Encode, Debug)]
+pub struct PeersMsg(pub Vec<PeerMsg>);
+
+macro_rules! get_msg_payload {
+    ($a:ident, $b:ident) => {
+        if let NetMsgCmd::$a = $b.header.command {
+            $b.payload
+        } else {
+            return Err(Error::InvalidMsg(format!(
+                "Unexpected msg {:?}",
+                $b.header.command
+            )));
+        }
+    };
+}
+
+pub(super) use get_msg_payload;
+
+impl From<Entry> for PeerMsg {
+    fn from(entry: Entry) -> PeerMsg {
+        PeerMsg {
+            peer_id: PeerID(entry.key),
+            addr: entry.addr,
+            port: entry.port,
+            discovery_port: entry.discovery_port,
+        }
+    }
+}
+
+impl From<PeerMsg> for Entry {
+    fn from(peer: PeerMsg) -> Entry {
+        Entry {
+            key: peer.peer_id.0,
+            addr: peer.addr,
+            port: peer.port,
+            discovery_port: peer.discovery_port,
+        }
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/monitor.rs.html b/src/karyon_p2p/monitor.rs.html new file mode 100644 index 00000000..939931b2 --- /dev/null +++ b/src/karyon_p2p/monitor.rs.html @@ -0,0 +1,330 @@ +monitor.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+
use std::fmt;
+
+use crate::PeerID;
+
+use karyon_core::pubsub::{ArcPublisher, Publisher, Subscription};
+
+use karyon_net::Endpoint;
+
+/// Responsible for network and system monitoring.
+///
+/// It use pub-sub pattern to notify the subscribers with new events.
+///
+/// # Example
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// use smol::Executor;
+///
+/// use karyon_core::crypto::{KeyPair, KeyPairType};
+/// use karyon_p2p::{Config, Backend, PeerID};
+///
+/// async {
+///     
+///     // Create a new Executor
+///     let ex = Arc::new(Executor::new());
+///
+///     let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+///     let backend = Backend::new(&key_pair, Config::default(), ex);
+///
+///     // Create a new Subscription
+///     let sub =  backend.monitor().await;
+///     
+///     let event = sub.recv().await;
+/// };
+/// ```
+pub struct Monitor {
+    inner: ArcPublisher<MonitorEvent>,
+}
+
+impl Monitor {
+    /// Creates a new Monitor
+    pub(crate) fn new() -> Monitor {
+        Self {
+            inner: Publisher::new(),
+        }
+    }
+
+    /// Sends a new monitor event to all subscribers.
+    pub async fn notify(&self, event: &MonitorEvent) {
+        self.inner.notify(event).await;
+    }
+
+    /// Subscribes to listen to new events.
+    pub async fn subscribe(&self) -> Subscription<MonitorEvent> {
+        self.inner.subscribe().await
+    }
+}
+
+/// Defines various type of event that can be monitored.
+#[derive(Clone, Debug)]
+pub enum MonitorEvent {
+    Conn(ConnEvent),
+    PeerPool(PeerPoolEvent),
+    Discovery(DiscoveryEvent),
+}
+
+/// Defines connection-related events.
+#[derive(Clone, Debug)]
+pub enum ConnEvent {
+    Connected(Endpoint),
+    ConnectRetried(Endpoint),
+    ConnectFailed(Endpoint),
+    Accepted(Endpoint),
+    AcceptFailed,
+    Disconnected(Endpoint),
+    Listening(Endpoint),
+    ListenFailed(Endpoint),
+}
+
+/// Defines `PeerPool` events.
+#[derive(Clone, Debug)]
+pub enum PeerPoolEvent {
+    NewPeer(PeerID),
+    RemovePeer(PeerID),
+}
+
+/// Defines `Discovery` events.
+#[derive(Clone, Debug)]
+pub enum DiscoveryEvent {
+    LookupStarted(Endpoint),
+    LookupFailed(Endpoint),
+    LookupSucceeded(Endpoint, usize),
+    RefreshStarted,
+}
+
+impl fmt::Display for MonitorEvent {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let val = match self {
+            MonitorEvent::Conn(e) => format!("Connection Event: {e}"),
+            MonitorEvent::PeerPool(e) => format!("PeerPool Event: {e}"),
+            MonitorEvent::Discovery(e) => format!("Discovery Event: {e}"),
+        };
+        write!(f, "{}", val)
+    }
+}
+
+impl fmt::Display for ConnEvent {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let val = match self {
+            ConnEvent::Connected(endpoint) => format!("Connected: {endpoint}"),
+            ConnEvent::ConnectFailed(endpoint) => format!("ConnectFailed: {endpoint}"),
+            ConnEvent::ConnectRetried(endpoint) => format!("ConnectRetried: {endpoint}"),
+            ConnEvent::AcceptFailed => "AcceptFailed".to_string(),
+            ConnEvent::Accepted(endpoint) => format!("Accepted: {endpoint}"),
+            ConnEvent::Disconnected(endpoint) => format!("Disconnected: {endpoint}"),
+            ConnEvent::Listening(endpoint) => format!("Listening: {endpoint}"),
+            ConnEvent::ListenFailed(endpoint) => format!("ListenFailed: {endpoint}"),
+        };
+        write!(f, "{}", val)
+    }
+}
+
+impl fmt::Display for PeerPoolEvent {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let val = match self {
+            PeerPoolEvent::NewPeer(pid) => format!("NewPeer: {pid}"),
+            PeerPoolEvent::RemovePeer(pid) => format!("RemovePeer: {pid}"),
+        };
+        write!(f, "{}", val)
+    }
+}
+
+impl fmt::Display for DiscoveryEvent {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let val = match self {
+            DiscoveryEvent::LookupStarted(endpoint) => format!("LookupStarted: {endpoint}"),
+            DiscoveryEvent::LookupFailed(endpoint) => format!("LookupFailed: {endpoint}"),
+            DiscoveryEvent::LookupSucceeded(endpoint, len) => {
+                format!("LookupSucceeded: {endpoint} {len}")
+            }
+            DiscoveryEvent::RefreshStarted => "RefreshStarted".to_string(),
+        };
+        write!(f, "{}", val)
+    }
+}
+
+impl From<ConnEvent> for MonitorEvent {
+    fn from(val: ConnEvent) -> Self {
+        MonitorEvent::Conn(val)
+    }
+}
+
+impl From<PeerPoolEvent> for MonitorEvent {
+    fn from(val: PeerPoolEvent) -> Self {
+        MonitorEvent::PeerPool(val)
+    }
+}
+
+impl From<DiscoveryEvent> for MonitorEvent {
+    fn from(val: DiscoveryEvent) -> Self {
+        MonitorEvent::Discovery(val)
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/peer/mod.rs.html b/src/karyon_p2p/peer/mod.rs.html new file mode 100644 index 00000000..6d73f5bb --- /dev/null +++ b/src/karyon_p2p/peer/mod.rs.html @@ -0,0 +1,468 @@ +mod.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+
mod peer_id;
+
+pub use peer_id::PeerID;
+
+use std::sync::Arc;
+
+use log::{error, trace};
+use smol::{
+    channel::{self, Receiver, Sender},
+    lock::RwLock,
+};
+
+use karyon_core::{
+    async_util::{select, Either, TaskGroup, TaskResult},
+    event::{ArcEventSys, EventListener, EventSys},
+    util::{decode, encode},
+    GlobalExecutor,
+};
+
+use karyon_net::Endpoint;
+
+use crate::{
+    codec::{Codec, CodecMsg},
+    connection::ConnDirection,
+    message::{NetMsgCmd, ProtocolMsg, ShutdownMsg},
+    peer_pool::{ArcPeerPool, WeakPeerPool},
+    protocol::{Protocol, ProtocolEvent, ProtocolID},
+    Config, Error, Result,
+};
+
+pub type ArcPeer = Arc<Peer>;
+
+pub struct Peer {
+    /// Peer's ID
+    id: PeerID,
+
+    /// A weak pointer to `PeerPool`
+    peer_pool: WeakPeerPool,
+
+    /// Holds the Codec for the peer connection
+    codec: Codec,
+
+    /// Remote endpoint for the peer
+    remote_endpoint: Endpoint,
+
+    /// The direction of the connection, either `Inbound` or `Outbound`
+    conn_direction: ConnDirection,
+
+    /// A list of protocol IDs
+    protocol_ids: RwLock<Vec<ProtocolID>>,
+
+    /// `EventSys` responsible for sending events to the protocols.
+    protocol_events: ArcEventSys<ProtocolID>,
+
+    /// This channel is used to send a stop signal to the read loop.
+    stop_chan: (Sender<Result<()>>, Receiver<Result<()>>),
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+}
+
+impl Peer {
+    /// Creates a new peer
+    pub fn new(
+        peer_pool: WeakPeerPool,
+        id: &PeerID,
+        codec: Codec,
+        remote_endpoint: Endpoint,
+        conn_direction: ConnDirection,
+        ex: GlobalExecutor,
+    ) -> ArcPeer {
+        Arc::new(Peer {
+            id: id.clone(),
+            peer_pool,
+            codec,
+            protocol_ids: RwLock::new(Vec::new()),
+            remote_endpoint,
+            conn_direction,
+            protocol_events: EventSys::new(),
+            task_group: TaskGroup::new(ex),
+            stop_chan: channel::bounded(1),
+        })
+    }
+
+    /// Run the peer
+    pub async fn run(self: Arc<Self>) -> Result<()> {
+        self.start_protocols().await;
+        self.read_loop().await
+    }
+
+    /// Send a message to the peer connection using the specified protocol.
+    pub async fn send<T: CodecMsg>(&self, protocol_id: &ProtocolID, msg: &T) -> Result<()> {
+        let payload = encode(msg)?;
+
+        let proto_msg = ProtocolMsg {
+            protocol_id: protocol_id.to_string(),
+            payload: payload.to_vec(),
+        };
+
+        self.codec.write(NetMsgCmd::Protocol, &proto_msg).await?;
+        Ok(())
+    }
+
+    /// Broadcast a message to all connected peers using the specified protocol.
+    pub async fn broadcast<T: CodecMsg>(&self, protocol_id: &ProtocolID, msg: &T) {
+        self.peer_pool().broadcast(protocol_id, msg).await;
+    }
+
+    /// Shuts down the peer
+    pub async fn shutdown(&self) {
+        trace!("peer {} start shutting down", self.id);
+
+        // Send shutdown event to all protocols
+        for protocol_id in self.protocol_ids.read().await.iter() {
+            self.protocol_events
+                .emit_by_topic(protocol_id, &ProtocolEvent::Shutdown)
+                .await;
+        }
+
+        // Send a stop signal to the read loop
+        //
+        // No need to handle the error here; a dropped channel and
+        // sending a stop signal have the same effect.
+        let _ = self.stop_chan.0.try_send(Ok(()));
+
+        // No need to handle the error here
+        let _ = self.codec.write(NetMsgCmd::Shutdown, &ShutdownMsg(0)).await;
+
+        // Force shutting down
+        self.task_group.cancel().await;
+    }
+
+    /// Check if the connection is Inbound
+    #[inline]
+    pub fn is_inbound(&self) -> bool {
+        match self.conn_direction {
+            ConnDirection::Inbound => true,
+            ConnDirection::Outbound => false,
+        }
+    }
+
+    /// Returns the direction of the connection, which can be either `Inbound`
+    /// or `Outbound`.
+    #[inline]
+    pub fn direction(&self) -> &ConnDirection {
+        &self.conn_direction
+    }
+
+    /// Returns the remote endpoint for the peer
+    #[inline]
+    pub fn remote_endpoint(&self) -> &Endpoint {
+        &self.remote_endpoint
+    }
+
+    /// Return the peer's ID
+    #[inline]
+    pub fn id(&self) -> &PeerID {
+        &self.id
+    }
+
+    /// Returns the `Config` instance.
+    pub fn config(&self) -> Arc<Config> {
+        self.peer_pool().config.clone()
+    }
+
+    /// Registers a listener for the given Protocol `P`.
+    pub async fn register_listener<P: Protocol>(&self) -> EventListener<ProtocolID, ProtocolEvent> {
+        self.protocol_events.register(&P::id()).await
+    }
+
+    /// Start a read loop to handle incoming messages from the peer connection.
+    async fn read_loop(&self) -> Result<()> {
+        loop {
+            let fut = select(self.stop_chan.1.recv(), self.codec.read()).await;
+            let result = match fut {
+                Either::Left(stop_signal) => {
+                    trace!("Peer {} received a stop signal", self.id);
+                    return stop_signal?;
+                }
+                Either::Right(result) => result,
+            };
+
+            let msg = result?;
+
+            match msg.header.command {
+                NetMsgCmd::Protocol => {
+                    let msg: ProtocolMsg = decode(&msg.payload)?.0;
+
+                    if !self.protocol_ids.read().await.contains(&msg.protocol_id) {
+                        return Err(Error::UnsupportedProtocol(msg.protocol_id));
+                    }
+
+                    let proto_id = &msg.protocol_id;
+                    let msg = ProtocolEvent::Message(msg.payload);
+                    self.protocol_events.emit_by_topic(proto_id, &msg).await;
+                }
+                NetMsgCmd::Shutdown => {
+                    return Err(Error::PeerShutdown);
+                }
+                command => return Err(Error::InvalidMsg(format!("Unexpected msg {:?}", command))),
+            }
+        }
+    }
+
+    /// Start running the protocols for this peer connection.
+    async fn start_protocols(self: &Arc<Self>) {
+        for (protocol_id, constructor) in self.peer_pool().protocols.read().await.iter() {
+            trace!("peer {} start protocol {protocol_id}", self.id);
+            let protocol = constructor(self.clone());
+
+            self.protocol_ids.write().await.push(protocol_id.clone());
+
+            let selfc = self.clone();
+            let proto_idc = protocol_id.clone();
+
+            let on_failure = |result: TaskResult<Result<()>>| async move {
+                if let TaskResult::Completed(res) = result {
+                    if res.is_err() {
+                        error!("protocol {} stopped", proto_idc);
+                    }
+                    // Send a stop signal to read loop
+                    let _ = selfc.stop_chan.0.try_send(res);
+                }
+            };
+
+            self.task_group.spawn(protocol.start(), on_failure);
+        }
+    }
+
+    fn peer_pool(&self) -> ArcPeerPool {
+        self.peer_pool.upgrade().unwrap()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/peer/peer_id.rs.html b/src/karyon_p2p/peer/peer_id.rs.html new file mode 100644 index 00000000..d2967e3e --- /dev/null +++ b/src/karyon_p2p/peer/peer_id.rs.html @@ -0,0 +1,118 @@ +peer_id.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+
use bincode::{Decode, Encode};
+use rand::{rngs::OsRng, RngCore};
+use sha2::{Digest, Sha256};
+
+use karyon_core::crypto::PublicKey;
+
+use crate::Error;
+
+/// Represents a unique identifier for a peer.
+#[derive(Clone, Debug, Eq, PartialEq, Hash, Decode, Encode)]
+pub struct PeerID(pub [u8; 32]);
+
+impl std::fmt::Display for PeerID {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        let id = self.0[0..8]
+            .iter()
+            .map(|b| format!("{:x}", b))
+            .collect::<Vec<String>>()
+            .join("");
+
+        write!(f, "{}", id)
+    }
+}
+
+impl PeerID {
+    /// Creates a new PeerID.
+    pub fn new(src: &[u8]) -> Self {
+        let mut hasher = Sha256::new();
+        hasher.update(src);
+        Self(hasher.finalize().into())
+    }
+
+    /// Generates a random PeerID.
+    pub fn random() -> Self {
+        let mut id: [u8; 32] = [0; 32];
+        OsRng.fill_bytes(&mut id);
+        Self(id)
+    }
+}
+
+impl From<[u8; 32]> for PeerID {
+    fn from(b: [u8; 32]) -> Self {
+        PeerID(b)
+    }
+}
+
+impl TryFrom<PublicKey> for PeerID {
+    type Error = Error;
+
+    fn try_from(pk: PublicKey) -> Result<Self, Self::Error> {
+        let pk: [u8; 32] = pk
+            .as_bytes()
+            .try_into()
+            .map_err(|_| Error::TryFromPublicKey("Failed to convert public key to [u8;32]"))?;
+
+        Ok(PeerID(pk))
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/peer_pool.rs.html b/src/karyon_p2p/peer_pool.rs.html new file mode 100644 index 00000000..2f798748 --- /dev/null +++ b/src/karyon_p2p/peer_pool.rs.html @@ -0,0 +1,694 @@ +peer_pool.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+
use std::{
+    collections::HashMap,
+    sync::{Arc, Weak},
+    time::Duration,
+};
+
+use log::{error, info, trace, warn};
+use smol::{
+    channel::Sender,
+    lock::{Mutex, RwLock},
+};
+
+use karyon_core::{
+    async_util::{TaskGroup, TaskResult},
+    util::decode,
+    GlobalExecutor,
+};
+
+use karyon_net::Conn;
+
+use crate::{
+    codec::{Codec, CodecMsg},
+    config::Config,
+    connection::{ConnDirection, ConnQueue},
+    message::{get_msg_payload, NetMsg, NetMsgCmd, VerAckMsg, VerMsg},
+    monitor::{Monitor, PeerPoolEvent},
+    peer::{ArcPeer, Peer, PeerID},
+    protocol::{Protocol, ProtocolConstructor, ProtocolID},
+    protocols::PingProtocol,
+    version::{version_match, Version, VersionInt},
+    Error, Result,
+};
+
+pub type ArcPeerPool = Arc<PeerPool>;
+pub type WeakPeerPool = Weak<PeerPool>;
+
+pub struct PeerPool {
+    /// Peer's ID
+    pub id: PeerID,
+
+    /// Connection queue
+    conn_queue: Arc<ConnQueue>,
+
+    /// Holds the running peers.
+    peers: Mutex<HashMap<PeerID, ArcPeer>>,
+
+    /// Hashmap contains protocol constructors.
+    pub(crate) protocols: RwLock<HashMap<ProtocolID, Box<ProtocolConstructor>>>,
+
+    /// Hashmap contains protocol IDs and their versions.
+    protocol_versions: Arc<RwLock<HashMap<ProtocolID, Version>>>,
+
+    /// Managing spawned tasks.
+    task_group: TaskGroup<'static>,
+
+    /// A global Executor
+    executor: GlobalExecutor,
+
+    /// The Configuration for the P2P network.
+    pub(crate) config: Arc<Config>,
+
+    /// Responsible for network and system monitoring.
+    monitor: Arc<Monitor>,
+}
+
+impl PeerPool {
+    /// Creates a new PeerPool
+    pub fn new(
+        id: &PeerID,
+        conn_queue: Arc<ConnQueue>,
+        config: Arc<Config>,
+        monitor: Arc<Monitor>,
+        executor: GlobalExecutor,
+    ) -> Arc<Self> {
+        let protocols = RwLock::new(HashMap::new());
+        let protocol_versions = Arc::new(RwLock::new(HashMap::new()));
+
+        Arc::new(Self {
+            id: id.clone(),
+            conn_queue,
+            peers: Mutex::new(HashMap::new()),
+            protocols,
+            protocol_versions,
+            task_group: TaskGroup::new(executor.clone()),
+            executor,
+            monitor,
+            config,
+        })
+    }
+
+    /// Start
+    pub async fn start(self: &Arc<Self>) -> Result<()> {
+        self.setup_protocols().await?;
+        let selfc = self.clone();
+        self.task_group.spawn(selfc.listen_loop(), |_| async {});
+        Ok(())
+    }
+
+    /// Listens to a new connection from the connection queue
+    pub async fn listen_loop(self: Arc<Self>) {
+        loop {
+            let new_conn = self.conn_queue.next().await;
+            let signal = new_conn.disconnect_signal;
+
+            let result = self
+                .new_peer(new_conn.conn, &new_conn.direction, signal.clone())
+                .await;
+
+            // Only send a disconnect signal if there is an error when adding a peer.
+            if result.is_err() {
+                let _ = signal.send(result).await;
+            }
+        }
+    }
+
+    /// Shuts down
+    pub async fn shutdown(&self) {
+        for (_, peer) in self.peers.lock().await.iter() {
+            peer.shutdown().await;
+        }
+
+        self.task_group.cancel().await;
+    }
+
+    /// Attach a custom protocol to the network
+    pub async fn attach_protocol<P: Protocol>(&self, c: Box<ProtocolConstructor>) -> Result<()> {
+        let protocol_versions = &mut self.protocol_versions.write().await;
+        let protocols = &mut self.protocols.write().await;
+
+        protocol_versions.insert(P::id(), P::version()?);
+        protocols.insert(P::id(), c);
+        Ok(())
+    }
+
+    /// Returns the number of currently connected peers.
+    pub async fn peers_len(&self) -> usize {
+        self.peers.lock().await.len()
+    }
+
+    /// Broadcast a message to all connected peers using the specified protocol.
+    pub async fn broadcast<T: CodecMsg>(&self, proto_id: &ProtocolID, msg: &T) {
+        for (pid, peer) in self.peers.lock().await.iter() {
+            if let Err(err) = peer.send(proto_id, msg).await {
+                error!("failed to send msg to {pid}: {err}");
+                continue;
+            }
+        }
+    }
+
+    /// Add a new peer to the peer list.
+    pub async fn new_peer(
+        self: &Arc<Self>,
+        conn: Conn,
+        conn_direction: &ConnDirection,
+        disconnect_signal: Sender<Result<()>>,
+    ) -> Result<()> {
+        let endpoint = conn.peer_endpoint()?;
+        let codec = Codec::new(conn);
+
+        // Do a handshake with the connection before creating a new peer.
+        let pid = self.do_handshake(&codec, conn_direction).await?;
+
+        // TODO: Consider restricting the subnet for inbound connections
+        if self.contains_peer(&pid).await {
+            return Err(Error::PeerAlreadyConnected);
+        }
+
+        // Create a new peer
+        let peer = Peer::new(
+            Arc::downgrade(self),
+            &pid,
+            codec,
+            endpoint.clone(),
+            conn_direction.clone(),
+            self.executor.clone(),
+        );
+
+        // Insert the new peer
+        self.peers.lock().await.insert(pid.clone(), peer.clone());
+
+        let selfc = self.clone();
+        let pid_c = pid.clone();
+        let on_disconnect = |result| async move {
+            if let TaskResult::Completed(result) = result {
+                if let Err(err) = selfc.remove_peer(&pid_c).await {
+                    error!("Failed to remove peer {pid_c}: {err}");
+                }
+                let _ = disconnect_signal.send(result).await;
+            }
+        };
+
+        self.task_group.spawn(peer.run(), on_disconnect);
+
+        info!("Add new peer {pid}, direction: {conn_direction}, endpoint: {endpoint}");
+
+        self.monitor
+            .notify(&PeerPoolEvent::NewPeer(pid.clone()).into())
+            .await;
+
+        Ok(())
+    }
+
+    /// Checks if the peer list contains a peer with the given peer id
+    pub async fn contains_peer(&self, pid: &PeerID) -> bool {
+        self.peers.lock().await.contains_key(pid)
+    }
+
+    /// Shuts down the peer and remove it from the peer list.
+    async fn remove_peer(&self, pid: &PeerID) -> Result<()> {
+        let result = self.peers.lock().await.remove(pid);
+
+        let peer = match result {
+            Some(p) => p,
+            None => return Ok(()),
+        };
+
+        peer.shutdown().await;
+
+        self.monitor
+            .notify(&PeerPoolEvent::RemovePeer(pid.clone()).into())
+            .await;
+
+        let endpoint = peer.remote_endpoint();
+        let direction = peer.direction();
+
+        warn!("Peer {pid} removed, direction: {direction}, endpoint: {endpoint}",);
+        Ok(())
+    }
+
+    /// Attach the core protocols.
+    async fn setup_protocols(&self) -> Result<()> {
+        let executor = self.executor.clone();
+        let c = move |peer| PingProtocol::new(peer, executor.clone());
+        self.attach_protocol::<PingProtocol>(Box::new(c)).await
+    }
+
+    /// Initiate a handshake with a connection.
+    async fn do_handshake(&self, codec: &Codec, conn_direction: &ConnDirection) -> Result<PeerID> {
+        match conn_direction {
+            ConnDirection::Inbound => {
+                let result = self.wait_vermsg(codec).await;
+                match result {
+                    Ok(_) => {
+                        self.send_verack(codec, true).await?;
+                    }
+                    Err(Error::IncompatibleVersion(_)) | Err(Error::UnsupportedProtocol(_)) => {
+                        self.send_verack(codec, false).await?;
+                    }
+                    _ => {}
+                }
+                result
+            }
+
+            ConnDirection::Outbound => {
+                self.send_vermsg(codec).await?;
+                self.wait_verack(codec).await
+            }
+        }
+    }
+
+    /// Send a Version message
+    async fn send_vermsg(&self, codec: &Codec) -> Result<()> {
+        let pids = self.protocol_versions.read().await;
+        let protocols = pids.iter().map(|p| (p.0.clone(), p.1.v.clone())).collect();
+        drop(pids);
+
+        let vermsg = VerMsg {
+            peer_id: self.id.clone(),
+            protocols,
+            version: self.config.version.v.clone(),
+        };
+
+        trace!("Send VerMsg");
+        codec.write(NetMsgCmd::Version, &vermsg).await?;
+        Ok(())
+    }
+
+    /// Wait for a Version message
+    ///
+    /// Returns the peer's ID upon successfully receiving the Version message.
+    async fn wait_vermsg(&self, codec: &Codec) -> Result<PeerID> {
+        let timeout = Duration::from_secs(self.config.handshake_timeout);
+        let msg: NetMsg = codec.read_timeout(timeout).await?;
+
+        let payload = get_msg_payload!(Version, msg);
+        let (vermsg, _) = decode::<VerMsg>(&payload)?;
+
+        if !version_match(&self.config.version.req, &vermsg.version) {
+            return Err(Error::IncompatibleVersion("system: {}".into()));
+        }
+
+        self.protocols_match(&vermsg.protocols).await?;
+
+        trace!("Received VerMsg from: {}", vermsg.peer_id);
+        Ok(vermsg.peer_id)
+    }
+
+    /// Send a Verack message
+    async fn send_verack(&self, codec: &Codec, ack: bool) -> Result<()> {
+        let verack = VerAckMsg {
+            peer_id: self.id.clone(),
+            ack,
+        };
+
+        trace!("Send VerAckMsg {:?}", verack);
+        codec.write(NetMsgCmd::Verack, &verack).await?;
+        Ok(())
+    }
+
+    /// Wait for a Verack message
+    ///
+    /// Returns the peer's ID upon successfully receiving the Verack message.
+    async fn wait_verack(&self, codec: &Codec) -> Result<PeerID> {
+        let timeout = Duration::from_secs(self.config.handshake_timeout);
+        let msg: NetMsg = codec.read_timeout(timeout).await?;
+
+        let payload = get_msg_payload!(Verack, msg);
+        let (verack, _) = decode::<VerAckMsg>(&payload)?;
+
+        if !verack.ack {
+            return Err(Error::IncompatiblePeer);
+        }
+
+        trace!("Received VerAckMsg from: {}", verack.peer_id);
+        Ok(verack.peer_id)
+    }
+
+    /// Check if the new connection has compatible protocols.
+    async fn protocols_match(&self, protocols: &HashMap<ProtocolID, VersionInt>) -> Result<()> {
+        for (n, pv) in protocols.iter() {
+            let pids = self.protocol_versions.read().await;
+
+            match pids.get(n) {
+                Some(v) => {
+                    if !version_match(&v.req, pv) {
+                        return Err(Error::IncompatibleVersion(format!("{n} protocol: {pv}")));
+                    }
+                }
+                None => {
+                    return Err(Error::UnsupportedProtocol(n.to_string()));
+                }
+            }
+        }
+        Ok(())
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/protocol.rs.html b/src/karyon_p2p/protocol.rs.html new file mode 100644 index 00000000..ae9acb01 --- /dev/null +++ b/src/karyon_p2p/protocol.rs.html @@ -0,0 +1,236 @@ +protocol.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+
use std::sync::Arc;
+
+use async_trait::async_trait;
+
+use karyon_core::event::EventValue;
+
+use crate::{peer::ArcPeer, version::Version, Result};
+
+pub type ArcProtocol = Arc<dyn Protocol>;
+
+pub type ProtocolConstructor = dyn Fn(ArcPeer) -> Arc<dyn Protocol> + Send + Sync;
+
+pub type ProtocolID = String;
+
+/// Protocol event
+#[derive(Debug, Clone)]
+pub enum ProtocolEvent {
+    /// Message event, contains a vector of bytes.
+    Message(Vec<u8>),
+    /// Shutdown event signals the protocol to gracefully shut down.
+    Shutdown,
+}
+
+impl EventValue for ProtocolEvent {
+    fn id() -> &'static str {
+        "ProtocolEvent"
+    }
+}
+
+/// The Protocol trait defines the interface for core protocols
+/// and custom protocols.
+///
+/// # Example
+/// ```
+/// use std::sync::Arc;
+///
+/// use async_trait::async_trait;
+/// use smol::Executor;
+///
+/// use karyon_core::crypto::{KeyPair, KeyPairType};
+/// use karyon_p2p::{
+///     protocol::{ArcProtocol, Protocol, ProtocolID, ProtocolEvent},
+///     Backend, PeerID, Config, Version, P2pError, ArcPeer};
+///
+/// pub struct NewProtocol {
+///     peer: ArcPeer,
+/// }
+///
+/// impl NewProtocol {
+///     fn new(peer: ArcPeer) -> ArcProtocol {
+///         Arc::new(Self {
+///             peer,
+///         })
+///     }
+/// }
+///
+/// #[async_trait]
+/// impl Protocol for NewProtocol {
+///     async fn start(self: Arc<Self>) -> Result<(), P2pError> {
+///         let listener = self.peer.register_listener::<Self>().await;
+///         loop {
+///             let event = listener.recv().await.unwrap();
+///
+///             match event {
+///                 ProtocolEvent::Message(msg) => {
+///                     println!("{:?}", msg);
+///                 }
+///                 ProtocolEvent::Shutdown => {
+///                     break;
+///                 }
+///             }
+///         }
+///
+///         listener.cancel().await;
+///         Ok(())
+///     }
+///
+///     fn version() -> Result<Version, P2pError> {
+///         "0.2.0, >0.1.0".parse()
+///     }
+///
+///     fn id() -> ProtocolID {
+///         "NEWPROTOCOLID".into()
+///     }
+/// }
+///
+///  async {
+///     let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+///     let config = Config::default();
+///
+///     // Create a new Executor
+///     let ex = Arc::new(Executor::new());
+///
+///     // Create a new Backend
+///     let backend = Backend::new(&key_pair, config, ex);
+///
+///     // Attach the NewProtocol
+///     let c = move |peer| NewProtocol::new(peer);
+///     backend.attach_protocol::<NewProtocol>(c).await.unwrap();
+///  };
+///
+/// ```  
+#[async_trait]
+pub trait Protocol: Send + Sync {
+    /// Start the protocol
+    async fn start(self: Arc<Self>) -> Result<()>;
+
+    /// Returns the version of the protocol.
+    fn version() -> Result<Version>
+    where
+        Self: Sized;
+
+    /// Returns the unique ProtocolID associated with the protocol.
+    fn id() -> ProtocolID
+    where
+        Self: Sized;
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/protocols/mod.rs.html b/src/karyon_p2p/protocols/mod.rs.html new file mode 100644 index 00000000..d9845957 --- /dev/null +++ b/src/karyon_p2p/protocols/mod.rs.html @@ -0,0 +1,8 @@ +mod.rs - source +
1
+2
+3
+
mod ping;
+
+pub use ping::PingProtocol;
+
\ No newline at end of file diff --git a/src/karyon_p2p/protocols/ping.rs.html b/src/karyon_p2p/protocols/ping.rs.html new file mode 100644 index 00000000..ad655831 --- /dev/null +++ b/src/karyon_p2p/protocols/ping.rs.html @@ -0,0 +1,348 @@ +ping.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+
use std::{sync::Arc, time::Duration};
+
+use async_trait::async_trait;
+use bincode::{Decode, Encode};
+use log::trace;
+use rand::{rngs::OsRng, RngCore};
+use smol::{
+    channel,
+    channel::{Receiver, Sender},
+    stream::StreamExt,
+    Timer,
+};
+
+use karyon_core::{
+    async_util::{select, timeout, Either, TaskGroup, TaskResult},
+    event::EventListener,
+    util::decode,
+    GlobalExecutor,
+};
+
+use karyon_net::NetError;
+
+use crate::{
+    peer::ArcPeer,
+    protocol::{ArcProtocol, Protocol, ProtocolEvent, ProtocolID},
+    version::Version,
+    Result,
+};
+
+const MAX_FAILUERS: u32 = 3;
+
+#[derive(Clone, Debug, Encode, Decode)]
+enum PingProtocolMsg {
+    Ping([u8; 32]),
+    Pong([u8; 32]),
+}
+
+pub struct PingProtocol {
+    peer: ArcPeer,
+    ping_interval: u64,
+    ping_timeout: u64,
+    task_group: TaskGroup<'static>,
+}
+
+impl PingProtocol {
+    #[allow(clippy::new_ret_no_self)]
+    pub fn new(peer: ArcPeer, executor: GlobalExecutor) -> ArcProtocol {
+        let ping_interval = peer.config().ping_interval;
+        let ping_timeout = peer.config().ping_timeout;
+        Arc::new(Self {
+            peer,
+            ping_interval,
+            ping_timeout,
+            task_group: TaskGroup::new(executor),
+        })
+    }
+
+    async fn recv_loop(
+        &self,
+        listener: &EventListener<ProtocolID, ProtocolEvent>,
+        pong_chan: Sender<[u8; 32]>,
+    ) -> Result<()> {
+        loop {
+            let event = listener.recv().await?;
+            let msg_payload = match event.clone() {
+                ProtocolEvent::Message(m) => m,
+                ProtocolEvent::Shutdown => {
+                    break;
+                }
+            };
+
+            let (msg, _) = decode::<PingProtocolMsg>(&msg_payload)?;
+
+            match msg {
+                PingProtocolMsg::Ping(nonce) => {
+                    trace!("Received Ping message {:?}", nonce);
+                    self.peer
+                        .send(&Self::id(), &PingProtocolMsg::Pong(nonce))
+                        .await?;
+                    trace!("Send back Pong message {:?}", nonce);
+                }
+                PingProtocolMsg::Pong(nonce) => {
+                    pong_chan.send(nonce).await?;
+                }
+            }
+        }
+        Ok(())
+    }
+
+    async fn ping_loop(self: Arc<Self>, chan: Receiver<[u8; 32]>) -> Result<()> {
+        let mut timer = Timer::interval(Duration::from_secs(self.ping_interval));
+        let rng = &mut OsRng;
+        let mut retry = 0;
+
+        while retry < MAX_FAILUERS {
+            timer.next().await;
+
+            let mut ping_nonce: [u8; 32] = [0; 32];
+            rng.fill_bytes(&mut ping_nonce);
+
+            trace!("Send Ping message {:?}", ping_nonce);
+            self.peer
+                .send(&Self::id(), &PingProtocolMsg::Ping(ping_nonce))
+                .await?;
+
+            let d = Duration::from_secs(self.ping_timeout);
+
+            // Wait for Pong message
+            let pong_msg = match timeout(d, chan.recv()).await {
+                Ok(m) => m?,
+                Err(_) => {
+                    retry += 1;
+                    continue;
+                }
+            };
+
+            trace!("Received Pong message {:?}", pong_msg);
+
+            if pong_msg != ping_nonce {
+                retry += 1;
+                continue;
+            }
+        }
+
+        Err(NetError::Timeout.into())
+    }
+}
+
+#[async_trait]
+impl Protocol for PingProtocol {
+    async fn start(self: Arc<Self>) -> Result<()> {
+        trace!("Start Ping protocol");
+
+        let (pong_chan, pong_chan_recv) = channel::bounded(1);
+        let (stop_signal_s, stop_signal) = channel::bounded::<Result<()>>(1);
+
+        let selfc = self.clone();
+        self.task_group.spawn(
+            selfc.clone().ping_loop(pong_chan_recv.clone()),
+            |res| async move {
+                if let TaskResult::Completed(result) = res {
+                    let _ = stop_signal_s.send(result).await;
+                }
+            },
+        );
+
+        let listener = self.peer.register_listener::<Self>().await;
+
+        let result = select(self.recv_loop(&listener, pong_chan), stop_signal.recv()).await;
+        listener.cancel().await;
+        self.task_group.cancel().await;
+
+        match result {
+            Either::Left(res) => {
+                trace!("Receive loop stopped {:?}", res);
+                res
+            }
+            Either::Right(res) => {
+                let res = res?;
+                trace!("Ping loop stopped {:?}", res);
+                res
+            }
+        }
+    }
+
+    fn version() -> Result<Version> {
+        "0.1.0".parse()
+    }
+
+    fn id() -> ProtocolID {
+        "PING".into()
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/routing_table/bucket.rs.html b/src/karyon_p2p/routing_table/bucket.rs.html new file mode 100644 index 00000000..cc3438a1 --- /dev/null +++ b/src/karyon_p2p/routing_table/bucket.rs.html @@ -0,0 +1,266 @@ +bucket.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+
use super::{Entry, Key};
+
+use rand::{rngs::OsRng, seq::SliceRandom};
+
+/// BITFLAGS represent the status of an Entry within a bucket.
+pub type EntryStatusFlag = u16;
+
+/// The entry is connected.
+pub const CONNECTED_ENTRY: EntryStatusFlag = 0b000001;
+
+/// The entry is disconnected. This will increase the failure counter.
+pub const DISCONNECTED_ENTRY: EntryStatusFlag = 0b000010;
+
+/// The entry is ready to reconnect, meaning it has either been added and
+/// has no connection attempts, or it has been refreshed.
+pub const PENDING_ENTRY: EntryStatusFlag = 0b000100;
+
+/// The entry is unreachable. This will increase the failure counter.
+pub const UNREACHABLE_ENTRY: EntryStatusFlag = 0b001000;
+
+/// The entry is unstable. This will increase the failure counter.
+pub const UNSTABLE_ENTRY: EntryStatusFlag = 0b010000;
+
+/// The entry is incompatible. This entry will not contribute to an increase in
+/// failure attempts, instead, it will persist in the routing table for the
+/// lookup process and will only be removed in the presence of a new entry.
+pub const INCOMPATIBLE_ENTRY: EntryStatusFlag = 0b100000;
+
+#[allow(dead_code)]
+pub const ALL_ENTRY: EntryStatusFlag = 0b111111;
+
+/// A BucketEntry represents a peer in the routing table.
+#[derive(Clone, Debug)]
+pub struct BucketEntry {
+    pub status: EntryStatusFlag,
+    pub entry: Entry,
+    pub failures: u32,
+    pub last_seen: i64,
+}
+
+impl BucketEntry {
+    pub fn is_connected(&self) -> bool {
+        self.status ^ CONNECTED_ENTRY == 0
+    }
+
+    pub fn is_incompatible(&self) -> bool {
+        self.status ^ INCOMPATIBLE_ENTRY == 0
+    }
+
+    pub fn is_unreachable(&self) -> bool {
+        self.status ^ UNREACHABLE_ENTRY == 0
+    }
+
+    pub fn is_unstable(&self) -> bool {
+        self.status ^ UNSTABLE_ENTRY == 0
+    }
+}
+
+/// The number of entries that can be stored within a single bucket.
+pub const BUCKET_SIZE: usize = 20;
+
+/// A Bucket represents a group of entries in the routing table.
+#[derive(Debug, Clone)]
+pub struct Bucket {
+    entries: Vec<BucketEntry>,
+}
+
+impl Bucket {
+    /// Creates a new empty Bucket
+    pub fn new() -> Self {
+        Self {
+            entries: Vec::with_capacity(BUCKET_SIZE),
+        }
+    }
+
+    /// Add an entry to the bucket.
+    pub fn add(&mut self, entry: &Entry) {
+        self.entries.push(BucketEntry {
+            status: PENDING_ENTRY,
+            entry: entry.clone(),
+            failures: 0,
+            last_seen: chrono::Utc::now().timestamp(),
+        })
+    }
+
+    /// Get the number of entries in the bucket.
+    pub fn len(&self) -> usize {
+        self.entries.len()
+    }
+
+    /// Returns an iterator over the entries in the bucket.
+    pub fn iter(&self) -> impl Iterator<Item = &BucketEntry> {
+        self.entries.iter()
+    }
+
+    /// Remove an entry.
+    pub fn remove(&mut self, key: &Key) {
+        let position = self.entries.iter().position(|e| &e.entry.key == key);
+        if let Some(i) = position {
+            self.entries.remove(i);
+        }
+    }
+
+    /// Returns an iterator of entries in random order.
+    pub fn random_iter(&self, amount: usize) -> impl Iterator<Item = &BucketEntry> {
+        self.entries.choose_multiple(&mut OsRng, amount)
+    }
+
+    /// Updates the status of an entry in the bucket identified by the given key.
+    ///
+    /// If the key is not found in the bucket, no action is taken.
+    ///
+    /// This will also update the last_seen field and increase the failures
+    /// counter for the bucket entry according to the new status.
+    pub fn update_entry(&mut self, key: &Key, entry_flag: EntryStatusFlag) {
+        if let Some(e) = self.entries.iter_mut().find(|e| &e.entry.key == key) {
+            e.status = entry_flag;
+            if e.is_unreachable() || e.is_unstable() {
+                e.failures += 1;
+            }
+
+            if !e.is_unreachable() {
+                e.last_seen = chrono::Utc::now().timestamp();
+            }
+        }
+    }
+
+    /// Check if the bucket contains the given key.
+    pub fn contains_key(&self, key: &Key) -> bool {
+        self.entries.iter().any(|e| &e.entry.key == key)
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/routing_table/entry.rs.html b/src/karyon_p2p/routing_table/entry.rs.html new file mode 100644 index 00000000..bc6785c9 --- /dev/null +++ b/src/karyon_p2p/routing_table/entry.rs.html @@ -0,0 +1,84 @@ +entry.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+
use bincode::{Decode, Encode};
+
+use karyon_net::{Addr, Port};
+
+/// Specifies the size of the key, in bytes.
+pub const KEY_SIZE: usize = 32;
+
+/// An Entry represents a peer in the routing table.
+#[derive(Encode, Decode, Clone, Debug)]
+pub struct Entry {
+    /// The unique key identifying the peer.
+    pub key: Key,
+    /// The IP address of the peer.
+    pub addr: Addr,
+    /// TCP port
+    pub port: Port,
+    /// UDP/TCP port
+    pub discovery_port: Port,
+}
+
+impl PartialEq for Entry {
+    fn eq(&self, other: &Self) -> bool {
+        // TODO: this should also compare both addresses (the self.addr == other.addr)
+        self.key == other.key
+    }
+}
+
+/// The unique key identifying the peer.
+pub type Key = [u8; KEY_SIZE];
+
+/// Calculates the XOR distance between two provided keys.
+///
+/// The XOR distance is a metric used in Kademlia to measure the closeness
+/// of keys.
+pub fn xor_distance(key: &Key, other: &Key) -> Key {
+    let mut res = [0; 32];
+    for (i, (k, o)) in key.iter().zip(other.iter()).enumerate() {
+        res[i] = k ^ o;
+    }
+    res
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/routing_table/mod.rs.html b/src/karyon_p2p/routing_table/mod.rs.html new file mode 100644 index 00000000..e264a7e2 --- /dev/null +++ b/src/karyon_p2p/routing_table/mod.rs.html @@ -0,0 +1,974 @@ +mod.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+283
+284
+285
+286
+287
+288
+289
+290
+291
+292
+293
+294
+295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
+307
+308
+309
+310
+311
+312
+313
+314
+315
+316
+317
+318
+319
+320
+321
+322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
+406
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
+435
+436
+437
+438
+439
+440
+441
+442
+443
+444
+445
+446
+447
+448
+449
+450
+451
+452
+453
+454
+455
+456
+457
+458
+459
+460
+461
+462
+463
+464
+465
+466
+467
+468
+469
+470
+471
+472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
+
use std::net::IpAddr;
+
+mod bucket;
+mod entry;
+
+pub use bucket::{
+    Bucket, BucketEntry, EntryStatusFlag, CONNECTED_ENTRY, DISCONNECTED_ENTRY, INCOMPATIBLE_ENTRY,
+    PENDING_ENTRY, UNREACHABLE_ENTRY, UNSTABLE_ENTRY,
+};
+pub use entry::{xor_distance, Entry, Key};
+
+use rand::{rngs::OsRng, seq::SliceRandom};
+
+use karyon_net::Addr;
+
+use bucket::BUCKET_SIZE;
+use entry::KEY_SIZE;
+
+/// The total number of buckets in the routing table.
+const TABLE_SIZE: usize = 32;
+
+/// The distance limit for the closest buckets.
+const DISTANCE_LIMIT: usize = 32;
+
+/// The maximum number of matched subnets allowed within a single bucket.
+const MAX_MATCHED_SUBNET_IN_BUCKET: usize = 1;
+
+/// The maximum number of matched subnets across the entire routing table.
+const MAX_MATCHED_SUBNET_IN_TABLE: usize = 6;
+
+/// Represents the possible result when adding a new entry.
+#[derive(Debug)]
+pub enum AddEntryResult {
+    /// The entry is added.
+    Added,
+    /// The entry is already exists.
+    Exists,
+    /// The entry is ignored.
+    Ignored,
+    /// The entry is restricted and not allowed.
+    Restricted,
+}
+
+/// This is a modified version of the Kademlia Distributed Hash Table (DHT).
+/// <https://en.wikipedia.org/wiki/Kademlia>
+#[derive(Debug)]
+pub struct RoutingTable {
+    key: Key,
+    buckets: Vec<Bucket>,
+}
+
+impl RoutingTable {
+    /// Creates a new RoutingTable
+    pub fn new(key: Key) -> Self {
+        let buckets: Vec<Bucket> = (0..TABLE_SIZE).map(|_| Bucket::new()).collect();
+        Self { key, buckets }
+    }
+
+    /// Adds a new entry to the table and returns a result indicating success,
+    /// failure, or restrictions.
+    pub fn add_entry(&mut self, entry: Entry) -> AddEntryResult {
+        // Determine the index of the bucket where the entry should be placed.
+        let bucket_idx = match self.bucket_index(&entry.key) {
+            Some(i) => i,
+            None => return AddEntryResult::Ignored,
+        };
+
+        let bucket = &self.buckets[bucket_idx];
+
+        // Check if the entry already exists in the bucket.
+        if bucket.contains_key(&entry.key) {
+            return AddEntryResult::Exists;
+        }
+
+        // Check if the entry is restricted.
+        if self.subnet_restricted(bucket_idx, &entry) {
+            return AddEntryResult::Restricted;
+        }
+
+        let bucket = &mut self.buckets[bucket_idx];
+
+        // If the bucket has free space, add the entry and return success.
+        if bucket.len() < BUCKET_SIZE {
+            bucket.add(&entry);
+            return AddEntryResult::Added;
+        }
+
+        // Replace it with an incompatible entry if one exists.
+        let incompatible_entry = bucket.iter().find(|e| e.is_incompatible()).cloned();
+        if let Some(e) = incompatible_entry {
+            bucket.remove(&e.entry.key);
+            bucket.add(&entry);
+            return AddEntryResult::Added;
+        }
+
+        // If the bucket is full, the entry is ignored.
+        AddEntryResult::Ignored
+    }
+
+    /// Check if the table contains the given key.
+    pub fn contains_key(&self, key: &Key) -> bool {
+        // Determine the bucket index for the given key.
+        let bucket_idx = match self.bucket_index(key) {
+            Some(bi) => bi,
+            None => return false,
+        };
+
+        let bucket = &self.buckets[bucket_idx];
+        bucket.contains_key(key)
+    }
+
+    /// Updates the status of an entry in the routing table identified
+    /// by the given key.
+    ///
+    /// If the key is not found, no action is taken.
+    pub fn update_entry(&mut self, key: &Key, entry_flag: EntryStatusFlag) {
+        // Determine the bucket index for the given key.
+        let bucket_idx = match self.bucket_index(key) {
+            Some(bi) => bi,
+            None => return,
+        };
+
+        let bucket = &mut self.buckets[bucket_idx];
+        bucket.update_entry(key, entry_flag);
+    }
+
+    /// Returns a list of bucket indexes that are closest to the given target key.
+    pub fn bucket_indexes(&self, target_key: &Key) -> Vec<usize> {
+        let mut indexes = vec![];
+
+        // Determine the primary bucket index for the target key.
+        let bucket_idx = self.bucket_index(target_key).unwrap_or(0);
+
+        indexes.push(bucket_idx);
+
+        // Add additional bucket indexes within a certain distance limit.
+        for i in 1..DISTANCE_LIMIT {
+            if bucket_idx >= i && bucket_idx - i >= 1 {
+                indexes.push(bucket_idx - i);
+            }
+
+            if bucket_idx + i < (TABLE_SIZE - 1) {
+                indexes.push(bucket_idx + i);
+            }
+        }
+
+        indexes
+    }
+
+    /// Returns a list of the closest entries to the given target key, limited by max_entries.
+    pub fn closest_entries(&self, target_key: &Key, max_entries: usize) -> Vec<Entry> {
+        let mut entries: Vec<Entry> = vec![];
+
+        // Collect entries
+        'outer: for idx in self.bucket_indexes(target_key) {
+            let bucket = &self.buckets[idx];
+            for bucket_entry in bucket.iter() {
+                if bucket_entry.is_unreachable() || bucket_entry.is_unstable() {
+                    continue;
+                }
+
+                entries.push(bucket_entry.entry.clone());
+                if entries.len() == max_entries {
+                    break 'outer;
+                }
+            }
+        }
+
+        // Sort the entries by their distance to the target key.
+        entries.sort_by(|a, b| {
+            xor_distance(target_key, &a.key).cmp(&xor_distance(target_key, &b.key))
+        });
+
+        entries
+    }
+
+    /// Removes an entry with the given key from the routing table, if it exists.
+    pub fn remove_entry(&mut self, key: &Key) {
+        // Determine the bucket index for the given key.
+        let bucket_idx = match self.bucket_index(key) {
+            Some(bi) => bi,
+            None => return,
+        };
+
+        let bucket = &mut self.buckets[bucket_idx];
+        bucket.remove(key);
+    }
+
+    /// Returns an iterator of entries.
+    pub fn iter(&self) -> impl Iterator<Item = &Bucket> {
+        self.buckets.iter()
+    }
+
+    /// Returns a random entry from the routing table.
+    pub fn random_entry(&self, entry_flag: EntryStatusFlag) -> Option<&Entry> {
+        for bucket in self.buckets.choose_multiple(&mut OsRng, self.buckets.len()) {
+            for entry in bucket.random_iter(bucket.len()) {
+                if entry.status & entry_flag == 0 {
+                    continue;
+                }
+                return Some(&entry.entry);
+            }
+        }
+
+        None
+    }
+
+    // Returns the bucket index for a given key in the table.
+    fn bucket_index(&self, key: &Key) -> Option<usize> {
+        // Calculate the XOR distance between the self key and the provided key.
+        let distance = xor_distance(&self.key, key);
+
+        for (i, b) in distance.iter().enumerate() {
+            if *b != 0 {
+                let lz = i * 8 + b.leading_zeros() as usize;
+                let bits = KEY_SIZE * 8 - 1;
+                let idx = (bits - lz) / 8;
+                return Some(idx);
+            }
+        }
+        None
+    }
+
+    /// This function iterate through the routing table and counts how many
+    /// entries in the same subnet as the given Entry are already present.
+    ///
+    /// If the number of matching entries in the same bucket exceeds a
+    /// threshold (MAX_MATCHED_SUBNET_IN_BUCKET), or if the total count of
+    /// matching entries in the entire table exceeds a threshold
+    /// (MAX_MATCHED_SUBNET_IN_TABLE), the addition of the Entry
+    /// is considered restricted and returns true.
+    fn subnet_restricted(&self, idx: usize, entry: &Entry) -> bool {
+        let mut bucket_count = 0;
+        let mut table_count = 0;
+
+        // Iterate through the routing table's buckets and entries to check
+        // for subnet matches.
+        for (i, bucket) in self.buckets.iter().enumerate() {
+            for e in bucket.iter() {
+                // If there is a subnet match, update the counts.
+                let matched = subnet_match(&e.entry.addr, &entry.addr);
+                if matched {
+                    if i == idx {
+                        bucket_count += 1;
+                    }
+                    table_count += 1;
+                }
+
+                // If the number of matched entries in the same bucket exceeds
+                // the limit, return true
+                if bucket_count >= MAX_MATCHED_SUBNET_IN_BUCKET {
+                    return true;
+                }
+            }
+
+            // If the total matched entries in the table exceed the limit,
+            // return true.
+            if table_count >= MAX_MATCHED_SUBNET_IN_TABLE {
+                return true;
+            }
+        }
+
+        // If no subnet restrictions are encountered, return false.
+        false
+    }
+}
+
+/// Check if two addresses belong to the same subnet.
+pub fn subnet_match(addr: &Addr, other_addr: &Addr) -> bool {
+    match (addr, other_addr) {
+        (Addr::Ip(IpAddr::V4(ip)), Addr::Ip(IpAddr::V4(other_ip))) => {
+            // TODO: Consider moving this to a different place
+            if other_ip.is_loopback() && ip.is_loopback() {
+                return false;
+            }
+            ip.octets()[0..3] == other_ip.octets()[0..3]
+        }
+        _ => false,
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::bucket::ALL_ENTRY;
+    use super::*;
+
+    use karyon_net::Addr;
+
+    struct Setup {
+        local_key: Key,
+        keys: Vec<Key>,
+    }
+
+    fn new_entry(key: &Key, addr: &Addr, port: u16, discovery_port: u16) -> Entry {
+        Entry {
+            key: key.clone(),
+            addr: addr.clone(),
+            port,
+            discovery_port,
+        }
+    }
+
+    impl Setup {
+        fn new() -> Self {
+            let keys = vec![
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    0, 0, 0, 0, 0, 1,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    1, 1, 0, 1, 1, 2,
+                ],
+                [
+                    0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    0, 0, 0, 0, 0, 3,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 1, 18, 0, 0, 0,
+                    0, 0, 0, 0, 0, 4,
+                ],
+                [
+                    223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    0, 0, 0, 0, 0, 5,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 1, 18, 0, 0, 0,
+                    0, 0, 0, 0, 0, 6,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 50, 1, 18, 0, 0,
+                    0, 0, 0, 0, 0, 0, 7,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 50, 1, 18, 0, 0,
+                    0, 0, 0, 0, 0, 0, 8,
+                ],
+                [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 50, 1, 18, 0, 0,
+                    0, 0, 0, 0, 0, 0, 9,
+                ],
+            ];
+
+            Self {
+                local_key: [
+                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                    0, 0, 0, 0, 0, 0,
+                ],
+                keys,
+            }
+        }
+
+        fn entries(&self) -> Vec<Entry> {
+            let mut entries = vec![];
+            for (i, key) in self.keys.iter().enumerate() {
+                entries.push(new_entry(
+                    key,
+                    &Addr::Ip(format!("127.0.{i}.1").parse().unwrap()),
+                    3000,
+                    3010,
+                ));
+            }
+            entries
+        }
+
+        fn table(&self) -> RoutingTable {
+            let mut table = RoutingTable::new(self.local_key.clone());
+
+            for entry in self.entries() {
+                let res = table.add_entry(entry);
+                assert!(matches!(res, AddEntryResult::Added));
+            }
+
+            table
+        }
+    }
+
+    #[test]
+    fn test_bucket_index() {
+        let setup = Setup::new();
+        let table = setup.table();
+
+        assert_eq!(table.bucket_index(&setup.local_key), None);
+        assert_eq!(table.bucket_index(&setup.keys[0]), Some(0));
+        assert_eq!(table.bucket_index(&setup.keys[1]), Some(5));
+        assert_eq!(table.bucket_index(&setup.keys[2]), Some(26));
+        assert_eq!(table.bucket_index(&setup.keys[3]), Some(11));
+        assert_eq!(table.bucket_index(&setup.keys[4]), Some(31));
+        assert_eq!(table.bucket_index(&setup.keys[5]), Some(11));
+        assert_eq!(table.bucket_index(&setup.keys[6]), Some(12));
+        assert_eq!(table.bucket_index(&setup.keys[7]), Some(13));
+        assert_eq!(table.bucket_index(&setup.keys[8]), Some(14));
+    }
+
+    #[test]
+    fn test_closest_entries() {
+        let setup = Setup::new();
+        let table = setup.table();
+        let entries = setup.entries();
+
+        assert_eq!(
+            table.closest_entries(&setup.keys[5], 8),
+            vec![
+                entries[5].clone(),
+                entries[3].clone(),
+                entries[1].clone(),
+                entries[6].clone(),
+                entries[7].clone(),
+                entries[8].clone(),
+                entries[2].clone(),
+            ]
+        );
+
+        assert_eq!(
+            table.closest_entries(&setup.keys[4], 2),
+            vec![entries[4].clone(), entries[2].clone()]
+        );
+    }
+
+    #[test]
+    fn test_random_entry() {
+        let setup = Setup::new();
+        let mut table = setup.table();
+        let entries = setup.entries();
+
+        let entry = table.random_entry(ALL_ENTRY);
+        assert!(matches!(entry, Some(&_)));
+
+        let entry = table.random_entry(CONNECTED_ENTRY);
+        assert!(matches!(entry, None));
+
+        for entry in entries {
+            table.remove_entry(&entry.key);
+        }
+
+        let entry = table.random_entry(ALL_ENTRY);
+        assert!(matches!(entry, None));
+    }
+
+    #[test]
+    fn test_add_entries() {
+        let setup = Setup::new();
+        let mut table = setup.table();
+
+        let key = [
+            0, 0, 0, 0, 0, 0, 0, 1, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+            0, 0, 5,
+        ];
+
+        let key2 = [
+            0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+            0, 0, 5,
+        ];
+
+        let entry1 = new_entry(&key, &Addr::Ip("240.120.3.1".parse().unwrap()), 3000, 3010);
+        assert!(matches!(
+            table.add_entry(entry1.clone()),
+            AddEntryResult::Added
+        ));
+
+        assert!(matches!(table.add_entry(entry1), AddEntryResult::Exists));
+
+        let entry2 = new_entry(&key2, &Addr::Ip("240.120.3.2".parse().unwrap()), 3000, 3010);
+        assert!(matches!(
+            table.add_entry(entry2),
+            AddEntryResult::Restricted
+        ));
+
+        let mut key: [u8; 32] = [0; 32];
+
+        for i in 0..BUCKET_SIZE {
+            key[i] += 1;
+            let entry = new_entry(
+                &key,
+                &Addr::Ip(format!("127.0.{i}.1").parse().unwrap()),
+                3000,
+                3010,
+            );
+            table.add_entry(entry);
+        }
+
+        key[BUCKET_SIZE] += 1;
+        let entry = new_entry(&key, &Addr::Ip("125.20.0.1".parse().unwrap()), 3000, 3010);
+        assert!(matches!(table.add_entry(entry), AddEntryResult::Ignored));
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/slots.rs.html b/src/karyon_p2p/slots.rs.html new file mode 100644 index 00000000..5d1af94e --- /dev/null +++ b/src/karyon_p2p/slots.rs.html @@ -0,0 +1,110 @@ +slots.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+
use std::sync::atomic::{AtomicUsize, Ordering};
+
+use karyon_core::async_util::CondWait;
+
+/// Manages available inbound and outbound slots.
+pub struct ConnectionSlots {
+    /// A condvar for notifying when a slot become available.
+    signal: CondWait,
+    /// The number of occupied slots
+    slots: AtomicUsize,
+    /// The maximum number of slots.
+    max_slots: usize,
+}
+
+impl ConnectionSlots {
+    /// Creates a new ConnectionSlots
+    pub fn new(max_slots: usize) -> Self {
+        Self {
+            signal: CondWait::new(),
+            slots: AtomicUsize::new(0),
+            max_slots,
+        }
+    }
+
+    /// Returns the number of occupied slots
+    pub fn load(&self) -> usize {
+        self.slots.load(Ordering::SeqCst)
+    }
+
+    /// Increases the occupied slots by one.
+    pub fn add(&self) {
+        self.slots.fetch_add(1, Ordering::SeqCst);
+    }
+
+    /// Decreases the occupied slots by one and notifies the waiting signal
+    /// to start accepting/connecting new connections.
+    pub async fn remove(&self) {
+        self.slots.fetch_sub(1, Ordering::SeqCst);
+        if self.slots.load(Ordering::SeqCst) < self.max_slots {
+            self.signal.signal().await;
+        }
+    }
+
+    /// Waits for a slot to become available.
+    pub async fn wait_for_slot(&self) {
+        if self.slots.load(Ordering::SeqCst) < self.max_slots {
+            return;
+        }
+
+        // Wait for a signal
+        self.signal.wait().await;
+        self.signal.reset().await;
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/tls_config.rs.html b/src/karyon_p2p/tls_config.rs.html new file mode 100644 index 00000000..7f9ab942 --- /dev/null +++ b/src/karyon_p2p/tls_config.rs.html @@ -0,0 +1,566 @@ +tls_config.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+94
+95
+96
+97
+98
+99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
+124
+125
+126
+127
+128
+129
+130
+131
+132
+133
+134
+135
+136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
+170
+171
+172
+173
+174
+175
+176
+177
+178
+179
+180
+181
+182
+183
+184
+185
+186
+187
+188
+189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
+224
+225
+226
+227
+228
+229
+230
+231
+232
+233
+234
+235
+236
+237
+238
+239
+240
+241
+242
+243
+244
+245
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
+274
+275
+276
+277
+278
+279
+280
+281
+282
+
use std::sync::Arc;
+
+use futures_rustls::rustls::{
+    self,
+    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
+    crypto::{
+        aws_lc_rs::{self, cipher_suite::TLS13_CHACHA20_POLY1305_SHA256, kx_group},
+        CryptoProvider, SupportedKxGroup,
+    },
+    pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime},
+    server::danger::{ClientCertVerified, ClientCertVerifier},
+    CertificateError, DigitallySignedStruct, DistinguishedName,
+    Error::InvalidCertificate,
+    SignatureScheme, SupportedCipherSuite, SupportedProtocolVersion,
+};
+
+use log::error;
+use x509_parser::{certificate::X509Certificate, parse_x509_certificate};
+
+use karyon_core::crypto::{KeyPair, KeyPairType, PublicKey};
+
+use crate::{PeerID, Result};
+
+// NOTE: This code needs a comprehensive audit.
+
+static PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13];
+static CIPHER_SUITES: &[SupportedCipherSuite] = &[TLS13_CHACHA20_POLY1305_SHA256];
+static KX_GROUPS: &[&dyn SupportedKxGroup] = &[kx_group::X25519];
+static SIGNATURE_SCHEMES: &[SignatureScheme] = &[SignatureScheme::ED25519];
+
+const BAD_SIGNATURE_ERR: rustls::Error = InvalidCertificate(CertificateError::BadSignature);
+const BAD_ENCODING_ERR: rustls::Error = InvalidCertificate(CertificateError::BadEncoding);
+
+/// Returns a TLS client configuration.
+pub fn tls_client_config(
+    key_pair: &KeyPair,
+    peer_id: Option<PeerID>,
+) -> Result<rustls::ClientConfig> {
+    let (cert, private_key) = generate_cert(key_pair)?;
+    let server_verifier = SrvrCertVerifier { peer_id };
+
+    let client_config = rustls::ClientConfig::builder_with_provider(
+        CryptoProvider {
+            kx_groups: KX_GROUPS.to_vec(),
+            cipher_suites: CIPHER_SUITES.to_vec(),
+            ..aws_lc_rs::default_provider()
+        }
+        .into(),
+    )
+    .with_protocol_versions(PROTOCOL_VERSIONS)?
+    .dangerous()
+    .with_custom_certificate_verifier(Arc::new(server_verifier))
+    .with_client_auth_cert(vec![cert], private_key)?;
+
+    Ok(client_config)
+}
+
+/// Returns a TLS server configuration.
+pub fn tls_server_config(key_pair: &KeyPair) -> Result<rustls::ServerConfig> {
+    let (cert, private_key) = generate_cert(key_pair)?;
+    let client_verifier = CliCertVerifier {};
+    let server_config = rustls::ServerConfig::builder_with_provider(
+        CryptoProvider {
+            kx_groups: KX_GROUPS.to_vec(),
+            cipher_suites: CIPHER_SUITES.to_vec(),
+            ..aws_lc_rs::default_provider()
+        }
+        .into(),
+    )
+    .with_protocol_versions(PROTOCOL_VERSIONS)?
+    .with_client_cert_verifier(Arc::new(client_verifier))
+    .with_single_cert(vec![cert], private_key)?;
+
+    Ok(server_config)
+}
+
+/// Generates a certificate and returns both the certificate and the private key.
+fn generate_cert<'a>(key_pair: &KeyPair) -> Result<(CertificateDer<'a>, PrivateKeyDer<'a>)> {
+    let cert_key_pair = rcgen::KeyPair::generate(&rcgen::PKCS_ED25519)?;
+    let private_key = PrivateKeyDer::Pkcs8(cert_key_pair.serialize_der().into());
+
+    // Add a custom extension to the certificate:
+    //   - Sign the certificate's public key with the provided key pair's private key
+    //   - Append both the computed signature and the key pair's public key to the extension
+    let signature = key_pair.sign(&cert_key_pair.public_key_der());
+    let ext_content = yasna::encode_der(&(key_pair.public().as_bytes().to_vec(), signature));
+    // XXX: Not sure about the oid number ???
+    let mut ext = rcgen::CustomExtension::from_oid_content(&[0, 0, 0, 0], ext_content);
+    ext.set_criticality(true);
+
+    let mut params = rcgen::CertificateParams::new(vec![]);
+    params.alg = &rcgen::PKCS_ED25519;
+    params.key_pair = Some(cert_key_pair);
+    params.custom_extensions.push(ext);
+
+    let cert = CertificateDer::from(rcgen::Certificate::from_params(params)?.serialize_der()?);
+    Ok((cert, private_key))
+}
+
+/// Verifies the given certification.
+fn verify_cert(end_entity: &CertificateDer<'_>) -> std::result::Result<PeerID, rustls::Error> {
+    // Parse the certificate.
+    let cert = parse_cert(end_entity)?;
+
+    match cert.extensions().first() {
+        Some(ext) => {
+            // Extract the peer id (public key) and the signature from the extension.
+            let (public_key, signature): (Vec<u8>, Vec<u8>) =
+                yasna::decode_der(ext.value).map_err(|_| BAD_ENCODING_ERR)?;
+
+            // Use the peer id (public key) to verify the extracted signature.
+            let public_key = PublicKey::from_bytes(&KeyPairType::Ed25519, &public_key)
+                .map_err(|_| BAD_ENCODING_ERR)?;
+            public_key
+                .verify(cert.public_key().raw, &signature)
+                .map_err(|_| BAD_SIGNATURE_ERR)?;
+
+            // Verify the certificate signature.
+            verify_cert_signature(
+                &cert,
+                cert.tbs_certificate.as_ref(),
+                cert.signature_value.as_ref(),
+            )?;
+
+            PeerID::try_from(public_key).map_err(|_| BAD_ENCODING_ERR)
+        }
+        None => Err(BAD_ENCODING_ERR),
+    }
+}
+
+/// Parses the given x509 certificate.
+fn parse_cert<'a>(
+    end_entity: &'a CertificateDer<'a>,
+) -> std::result::Result<X509Certificate<'a>, rustls::Error> {
+    let (_, cert) = parse_x509_certificate(end_entity.as_ref()).map_err(|_| BAD_ENCODING_ERR)?;
+
+    if !cert.validity().is_valid() {
+        return Err(InvalidCertificate(CertificateError::NotValidYet));
+    }
+
+    Ok(cert)
+}
+
+/// Verifies the signature of the given certificate.
+fn verify_cert_signature(
+    cert: &X509Certificate,
+    message: &[u8],
+    signature: &[u8],
+) -> std::result::Result<(), rustls::Error> {
+    let public_key = PublicKey::from_bytes(
+        &KeyPairType::Ed25519,
+        cert.tbs_certificate.subject_pki.subject_public_key.as_ref(),
+    )
+    .map_err(|_| BAD_ENCODING_ERR)?;
+
+    public_key
+        .verify(message, signature)
+        .map_err(|_| BAD_SIGNATURE_ERR)
+}
+
+#[derive(Debug)]
+struct SrvrCertVerifier {
+    peer_id: Option<PeerID>,
+}
+
+impl ServerCertVerifier for SrvrCertVerifier {
+    fn verify_server_cert(
+        &self,
+        end_entity: &CertificateDer<'_>,
+        _intermediates: &[CertificateDer<'_>],
+        _server_name: &ServerName,
+        _ocsp_response: &[u8],
+        _now: UnixTime,
+    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
+        let peer_id = match verify_cert(end_entity) {
+            Ok(pid) => pid,
+            Err(err) => {
+                error!("Failed to verify cert: {err}");
+                return Err(err);
+            }
+        };
+
+        // Verify that the peer id in the certificate's extension matches the
+        // one the client intends to connect to.
+        // Both should be equal for establishing a fully secure connection.
+        if let Some(pid) = &self.peer_id {
+            if pid != &peer_id {
+                return Err(InvalidCertificate(
+                    CertificateError::ApplicationVerificationFailure,
+                ));
+            }
+        }
+
+        Ok(ServerCertVerified::assertion())
+    }
+
+    fn verify_tls12_signature(
+        &self,
+        _message: &[u8],
+        _cert: &CertificateDer<'_>,
+        _dss: &DigitallySignedStruct,
+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
+        unreachable!("ONLY SUPPORT tls 13 VERSION")
+    }
+
+    fn verify_tls13_signature(
+        &self,
+        message: &[u8],
+        cert: &CertificateDer<'_>,
+        dss: &DigitallySignedStruct,
+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
+        let cert = parse_cert(cert)?;
+        verify_cert_signature(&cert, message, dss.signature())?;
+        Ok(HandshakeSignatureValid::assertion())
+    }
+
+    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+        SIGNATURE_SCHEMES.to_vec()
+    }
+}
+
+#[derive(Debug)]
+struct CliCertVerifier {}
+impl ClientCertVerifier for CliCertVerifier {
+    fn verify_client_cert(
+        &self,
+        end_entity: &CertificateDer<'_>,
+        _intermediates: &[CertificateDer<'_>],
+        _now: UnixTime,
+    ) -> std::result::Result<ClientCertVerified, rustls::Error> {
+        if let Err(err) = verify_cert(end_entity) {
+            error!("Failed to verify cert: {err}");
+            return Err(err);
+        };
+        Ok(ClientCertVerified::assertion())
+    }
+
+    fn root_hint_subjects(&self) -> &[DistinguishedName] {
+        &[]
+    }
+
+    fn verify_tls12_signature(
+        &self,
+        _message: &[u8],
+        _cert: &CertificateDer<'_>,
+        _dss: &DigitallySignedStruct,
+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
+        unreachable!("ONLY SUPPORT tls 13 VERSION")
+    }
+
+    fn verify_tls13_signature(
+        &self,
+        message: &[u8],
+        cert: &CertificateDer<'_>,
+        dss: &DigitallySignedStruct,
+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
+        let cert = parse_cert(cert)?;
+        verify_cert_signature(&cert, message, dss.signature())?;
+        Ok(HandshakeSignatureValid::assertion())
+    }
+
+    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+        SIGNATURE_SCHEMES.to_vec()
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn verify_generated_certificate() {
+        let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
+        let (cert, _) = generate_cert(&key_pair).unwrap();
+
+        let result = verify_cert(&cert);
+        assert!(result.is_ok());
+        let peer_id = result.unwrap();
+        assert_eq!(peer_id, PeerID::try_from(key_pair.public()).unwrap());
+        assert_eq!(peer_id.0, key_pair.public().as_bytes());
+    }
+}
+
\ No newline at end of file diff --git a/src/karyon_p2p/version.rs.html b/src/karyon_p2p/version.rs.html new file mode 100644 index 00000000..b018c710 --- /dev/null +++ b/src/karyon_p2p/version.rs.html @@ -0,0 +1,188 @@ +version.rs - source +
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
+83
+84
+85
+86
+87
+88
+89
+90
+91
+92
+93
+
use std::str::FromStr;
+
+use bincode::{Decode, Encode};
+use semver::VersionReq;
+
+use crate::{Error, Result};
+
+/// Represents the network version and protocol version used in karyon p2p.
+///
+/// # Example
+///
+/// ```
+/// use karyon_p2p::Version;
+///
+/// let version: Version = "0.2.0, >0.1.0".parse().unwrap();
+///
+/// let version: Version = "0.2.0".parse().unwrap();
+///
+/// ```
+#[derive(Debug, Clone)]
+pub struct Version {
+    pub v: VersionInt,
+    pub req: VersionReq,
+}
+
+impl Version {
+    /// Creates a new Version
+    pub fn new(v: VersionInt, req: VersionReq) -> Self {
+        Self { v, req }
+    }
+}
+
+#[derive(Debug, Decode, Encode, Clone)]
+pub struct VersionInt {
+    major: u64,
+    minor: u64,
+    patch: u64,
+}
+
+impl FromStr for Version {
+    type Err = Error;
+
+    fn from_str(s: &str) -> Result<Self> {
+        let v: Vec<&str> = s.split(", ").collect();
+        if v.is_empty() || v.len() > 2 {
+            return Err(Error::ParseError(format!("Invalid version{s}")));
+        }
+
+        let version: VersionInt = v[0].parse()?;
+        let req: VersionReq = if v.len() > 1 { v[1] } else { v[0] }.parse()?;
+
+        Ok(Self { v: version, req })
+    }
+}
+
+impl FromStr for VersionInt {
+    type Err = Error;
+
+    fn from_str(s: &str) -> Result<Self> {
+        let v: Vec<&str> = s.split('.').collect();
+        if v.len() < 2 || v.len() > 3 {
+            return Err(Error::ParseError(format!("Invalid version{s}")));
+        }
+
+        let major = v[0].parse::<u64>()?;
+        let minor = v[1].parse::<u64>()?;
+        let patch = v.get(2).unwrap_or(&"0").parse::<u64>()?;
+
+        Ok(Self {
+            major,
+            minor,
+            patch,
+        })
+    }
+}
+
+impl std::fmt::Display for VersionInt {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
+    }
+}
+
+impl From<VersionInt> for semver::Version {
+    fn from(v: VersionInt) -> Self {
+        semver::Version::new(v.major, v.minor, v.patch)
+    }
+}
+
+/// Check if a version satisfies a version request.
+pub fn version_match(version_req: &VersionReq, version: &VersionInt) -> bool {
+    let version: semver::Version = version.clone().into();
+    version_req.matches(&version)
+}
+
\ No newline at end of file diff --git a/static.files/COPYRIGHT-23e9bde6c69aea69.txt b/static.files/COPYRIGHT-23e9bde6c69aea69.txt new file mode 100644 index 00000000..1447df79 --- /dev/null +++ b/static.files/COPYRIGHT-23e9bde6c69aea69.txt @@ -0,0 +1,50 @@ +# REUSE-IgnoreStart + +These documentation pages include resources by third parties. This copyright +file applies only to those resources. The following third party resources are +included, and carry their own copyright notices and license terms: + +* Fira Sans (FiraSans-Regular.woff2, FiraSans-Medium.woff2): + + Copyright (c) 2014, Mozilla Foundation https://mozilla.org/ + with Reserved Font Name Fira Sans. + + Copyright (c) 2014, Telefonica S.A. + + Licensed under the SIL Open Font License, Version 1.1. + See FiraSans-LICENSE.txt. + +* rustdoc.css, main.js, and playpen.js: + + Copyright 2015 The Rust Developers. + Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE.txt) or + the MIT license (LICENSE-MIT.txt) at your option. + +* normalize.css: + + Copyright (c) Nicolas Gallagher and Jonathan Neal. + Licensed under the MIT license (see LICENSE-MIT.txt). + +* Source Code Pro (SourceCodePro-Regular.ttf.woff2, + SourceCodePro-Semibold.ttf.woff2, SourceCodePro-It.ttf.woff2): + + Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), + with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark + of Adobe Systems Incorporated in the United States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceCodePro-LICENSE.txt. + +* Source Serif 4 (SourceSerif4-Regular.ttf.woff2, SourceSerif4-Bold.ttf.woff2, + SourceSerif4-It.ttf.woff2): + + Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name + 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United + States and/or other countries. + + Licensed under the SIL Open Font License, Version 1.1. + See SourceSerif4-LICENSE.md. + +This copyright file is intended to be distributed with rustdoc output. + +# REUSE-IgnoreEnd diff --git a/static.files/FiraSans-LICENSE-db4b642586e02d97.txt b/static.files/FiraSans-LICENSE-db4b642586e02d97.txt new file mode 100644 index 00000000..d7e9c149 --- /dev/null +++ b/static.files/FiraSans-LICENSE-db4b642586e02d97.txt @@ -0,0 +1,98 @@ +// REUSE-IgnoreStart + +Digitized data copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. +with Reserved Font Name < Fira >, + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 b/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 new file mode 100644 index 00000000..7a1e5fc5 Binary files /dev/null and b/static.files/FiraSans-Medium-8f9a781e4970d388.woff2 differ diff --git a/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 b/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 new file mode 100644 index 00000000..e766e06c Binary files /dev/null and b/static.files/FiraSans-Regular-018c141bf0843ffd.woff2 differ diff --git a/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt b/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/static.files/LICENSE-APACHE-b91fa81cba47b86a.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/static.files/LICENSE-MIT-65090b722b3f6c56.txt b/static.files/LICENSE-MIT-65090b722b3f6c56.txt new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/static.files/LICENSE-MIT-65090b722b3f6c56.txt @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 b/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 new file mode 100644 index 00000000..1866ad4b Binary files /dev/null and b/static.files/NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2 differ diff --git a/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt b/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt new file mode 100644 index 00000000..4b3edc29 --- /dev/null +++ b/static.files/NanumBarunGothic-LICENSE-18c5adf4b52b4041.txt @@ -0,0 +1,103 @@ +// REUSE-IgnoreStart + +Copyright (c) 2010, NAVER Corporation (https://www.navercorp.com/), + +with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver NanumGothic, +NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumBrush, NanumPen, +Naver NanumPen, Naver NanumGothicEco, NanumGothicEco, Naver NanumMyeongjoEco, +NanumMyeongjoEco, Naver NanumGothicLight, NanumGothicLight, NanumBarunGothic, +Naver NanumBarunGothic, NanumSquareRound, NanumBarunPen, MaruBuri + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 b/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 new file mode 100644 index 00000000..462c34ef Binary files /dev/null and b/static.files/SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2 differ diff --git a/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt b/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt new file mode 100644 index 00000000..0d2941e1 --- /dev/null +++ b/static.files/SourceCodePro-LICENSE-d180d465a756484a.txt @@ -0,0 +1,97 @@ +// REUSE-IgnoreStart + +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +// REUSE-IgnoreEnd diff --git a/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 b/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 new file mode 100644 index 00000000..10b558e0 Binary files /dev/null and b/static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2 differ diff --git a/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 b/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 new file mode 100644 index 00000000..5ec64eef Binary files /dev/null and b/static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2 differ diff --git a/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 b/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 new file mode 100644 index 00000000..181a07f6 Binary files /dev/null and b/static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2 differ diff --git a/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 b/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 new file mode 100644 index 00000000..2ae08a7b Binary files /dev/null and b/static.files/SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2 differ diff --git a/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md b/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md new file mode 100644 index 00000000..175fa4f4 --- /dev/null +++ b/static.files/SourceSerif4-LICENSE-3bb119e13b1258b7.md @@ -0,0 +1,98 @@ + + +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. +Copyright 2014 - 2023 Adobe (http://www.adobe.com/), with Reserved Font Name ‘Source’. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + diff --git a/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 b/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 new file mode 100644 index 00000000..0263fc30 Binary files /dev/null and b/static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2 differ diff --git a/static.files/clipboard-7571035ce49a181d.svg b/static.files/clipboard-7571035ce49a181d.svg new file mode 100644 index 00000000..8adbd996 --- /dev/null +++ b/static.files/clipboard-7571035ce49a181d.svg @@ -0,0 +1 @@ + diff --git a/static.files/favicon-16x16-8b506e7a72182f1c.png b/static.files/favicon-16x16-8b506e7a72182f1c.png new file mode 100644 index 00000000..ea4b45ca Binary files /dev/null and b/static.files/favicon-16x16-8b506e7a72182f1c.png differ diff --git a/static.files/favicon-2c020d218678b618.svg b/static.files/favicon-2c020d218678b618.svg new file mode 100644 index 00000000..8b34b511 --- /dev/null +++ b/static.files/favicon-2c020d218678b618.svg @@ -0,0 +1,24 @@ + + + + + diff --git a/static.files/favicon-32x32-422f7d1d52889060.png b/static.files/favicon-32x32-422f7d1d52889060.png new file mode 100644 index 00000000..69b8613c Binary files /dev/null and b/static.files/favicon-32x32-422f7d1d52889060.png differ diff --git a/static.files/main-305769736d49e732.js b/static.files/main-305769736d49e732.js new file mode 100644 index 00000000..b8b91afa --- /dev/null +++ b/static.files/main-305769736d49e732.js @@ -0,0 +1,11 @@ +"use strict";window.RUSTDOC_TOOLTIP_HOVER_MS=300;window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS=450;function resourcePath(basename,extension){return getVar("root-path")+basename+getVar("resource-suffix")+extension}function hideMain(){addClass(document.getElementById(MAIN_ID),"hidden")}function showMain(){removeClass(document.getElementById(MAIN_ID),"hidden")}function blurHandler(event,parentElem,hideCallback){if(!parentElem.contains(document.activeElement)&&!parentElem.contains(event.relatedTarget)){hideCallback()}}window.rootPath=getVar("root-path");window.currentCrate=getVar("current-crate");function setMobileTopbar(){const mobileTopbar=document.querySelector(".mobile-topbar");const locationTitle=document.querySelector(".sidebar h2.location");if(mobileTopbar){const mobileTitle=document.createElement("h2");mobileTitle.className="location";if(hasClass(document.querySelector(".rustdoc"),"crate")){mobileTitle.innerText=`Crate ${window.currentCrate}`}else if(locationTitle){mobileTitle.innerHTML=locationTitle.innerHTML}mobileTopbar.appendChild(mobileTitle)}}function getVirtualKey(ev){if("key"in ev&&typeof ev.key!=="undefined"){return ev.key}const c=ev.charCode||ev.keyCode;if(c===27){return"Escape"}return String.fromCharCode(c)}const MAIN_ID="main-content";const SETTINGS_BUTTON_ID="settings-menu";const ALTERNATIVE_DISPLAY_ID="alternative-display";const NOT_DISPLAYED_ID="not-displayed";const HELP_BUTTON_ID="help-button";function getSettingsButton(){return document.getElementById(SETTINGS_BUTTON_ID)}function getHelpButton(){return document.getElementById(HELP_BUTTON_ID)}function getNakedUrl(){return window.location.href.split("?")[0].split("#")[0]}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}function getOrCreateSection(id,classes){let el=document.getElementById(id);if(!el){el=document.createElement("section");el.id=id;el.className=classes;insertAfter(el,document.getElementById(MAIN_ID))}return el}function getAlternativeDisplayElem(){return getOrCreateSection(ALTERNATIVE_DISPLAY_ID,"content hidden")}function getNotDisplayedElem(){return getOrCreateSection(NOT_DISPLAYED_ID,"hidden")}function switchDisplayedElement(elemToDisplay){const el=getAlternativeDisplayElem();if(el.children.length>0){getNotDisplayedElem().appendChild(el.firstElementChild)}if(elemToDisplay===null){addClass(el,"hidden");showMain();return}el.appendChild(elemToDisplay);hideMain();removeClass(el,"hidden")}function browserSupportsHistoryApi(){return window.history&&typeof window.history.pushState==="function"}function preLoadCss(cssUrl){const link=document.createElement("link");link.href=cssUrl;link.rel="preload";link.as="style";document.getElementsByTagName("head")[0].appendChild(link)}(function(){const isHelpPage=window.location.pathname.endsWith("/help.html");function loadScript(url){const script=document.createElement("script");script.src=url;document.head.append(script)}getSettingsButton().onclick=event=>{if(event.ctrlKey||event.altKey||event.metaKey){return}window.hideAllModals(false);addClass(getSettingsButton(),"rotate");event.preventDefault();loadScript(getVar("static-root-path")+getVar("settings-js"));setTimeout(()=>{const themes=getVar("themes").split(",");for(const theme of themes){if(theme!==""){preLoadCss(getVar("root-path")+theme+".css")}}},0)};window.searchState={loadingText:"Loading search results...",input:document.getElementsByClassName("search-input")[0],outputElement:()=>{let el=document.getElementById("search");if(!el){el=document.createElement("section");el.id="search";getNotDisplayedElem().appendChild(el)}return el},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:()=>{if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},isDisplayed:()=>searchState.outputElement().parentElement.id===ALTERNATIVE_DISPLAY_ID,focus:()=>{searchState.input.focus()},defocus:()=>{searchState.input.blur()},showResults:search=>{if(search===null||typeof search==="undefined"){search=searchState.outputElement()}switchDisplayedElement(search);searchState.mouseMovedAfterSearch=false;document.title=searchState.title},removeQueryParameters:()=>{document.title=searchState.titleBeforeSearch;if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.hash)}},hideResults:()=>{switchDisplayedElement(null);searchState.removeQueryParameters()},getQueryStringParams:()=>{const params={};window.location.search.substring(1).split("&").map(s=>{const pair=s.split("=");params[decodeURIComponent(pair[0])]=typeof pair[1]==="undefined"?null:decodeURIComponent(pair[1])});return params},setup:()=>{const search_input=searchState.input;if(!searchState.input){return}let searchLoaded=false;function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(getVar("static-root-path")+getVar("search-js"));loadScript(resourcePath("search-index",".js"))}}search_input.addEventListener("focus",()=>{search_input.origPlaceholder=search_input.placeholder;search_input.placeholder="Type your search here.";loadSearch()});if(search_input.value!==""){loadSearch()}const params=searchState.getQueryStringParams();if(params.search!==undefined){searchState.setLoadingSearch();loadSearch()}},setLoadingSearch:()=>{const search=searchState.outputElement();search.innerHTML="

"+searchState.loadingText+"

";searchState.showResults(search)},};const toggleAllDocsId="toggle-all-docs";let savedHash="";function handleHashes(ev){if(ev!==null&&searchState.isDisplayed()&&ev.newURL){switchDisplayedElement(null);const hash=ev.newURL.slice(ev.newURL.indexOf("#")+1);if(browserSupportsHistoryApi()){history.replaceState(null,"",getNakedUrl()+window.location.search+"#"+hash)}const elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}const pageId=window.location.hash.replace(/^#/,"");if(savedHash!==pageId){savedHash=pageId;if(pageId!==""){expandSection(pageId)}}if(savedHash.startsWith("impl-")){const splitAt=savedHash.indexOf("/");if(splitAt!==-1){const implId=savedHash.slice(0,splitAt);const assocId=savedHash.slice(splitAt+1);const implElem=document.getElementById(implId);if(implElem&&implElem.parentElement.tagName==="SUMMARY"&&implElem.parentElement.parentElement.tagName==="DETAILS"){onEachLazy(implElem.parentElement.parentElement.querySelectorAll(`[id^="${assocId}"]`),item=>{const numbered=/([^-]+)-([0-9]+)/.exec(item.id);if(item.id===assocId||(numbered&&numbered[1]===assocId)){openParentDetails(item);item.scrollIntoView();setTimeout(()=>{window.location.replace("#"+item.id)},0)}})}}}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName==="DETAILS"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function handleEscape(ev){searchState.clearInputTimeout();searchState.hideResults();ev.preventDefault();searchState.defocus();window.hideAllModals(true)}function handleShortcut(ev){const disableShortcuts=getSettingValue("disable-shortcuts")==="true";if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName==="INPUT"&&document.activeElement.type!=="checkbox"&&document.activeElement.type!=="radio"){switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case"Escape":handleEscape(ev);break;case"s":case"S":ev.preventDefault();searchState.focus();break;case"+":ev.preventDefault();expandAllDocs();break;case"-":ev.preventDefault();collapseAllDocs();break;case"?":showHelp();break;default:break}}}document.addEventListener("keypress",handleShortcut);document.addEventListener("keydown",handleShortcut);function addSidebarItems(){if(!window.SIDEBAR_ITEMS){return}const sidebar=document.getElementsByClassName("sidebar-elems")[0];function block(shortty,id,longty){const filtered=window.SIDEBAR_ITEMS[shortty];if(!filtered){return}const modpath=hasClass(document.querySelector(".rustdoc"),"mod")?"../":"";const h3=document.createElement("h3");h3.innerHTML=`${longty}`;const ul=document.createElement("ul");ul.className="block "+shortty;for(const name of filtered){let path;if(shortty==="mod"){path=`${modpath}${name}/index.html`}else{path=`${modpath}${shortty}.${name}.html`}let current_page=document.location.href.toString();if(current_page.endsWith("/")){current_page+="index.html"}const link=document.createElement("a");link.href=path;if(path===current_page){link.className="current"}link.textContent=name;const li=document.createElement("li");li.appendChild(link);ul.appendChild(li)}sidebar.appendChild(h3);sidebar.appendChild(ul)}if(sidebar){block("primitive","primitives","Primitive Types");block("mod","modules","Modules");block("macro","macros","Macros");block("struct","structs","Structs");block("enum","enums","Enums");block("constant","constants","Constants");block("static","static","Statics");block("trait","traits","Traits");block("fn","functions","Functions");block("type","types","Type Aliases");block("union","unions","Unions");block("foreigntype","foreign-types","Foreign Types");block("keyword","keywords","Keywords");block("opaque","opaque-types","Opaque Types");block("attr","attributes","Attribute Macros");block("derive","derives","Derive Macros");block("traitalias","trait-aliases","Trait Aliases")}}window.register_implementors=imp=>{const implementors=document.getElementById("implementors-list");const synthetic_implementors=document.getElementById("synthetic-implementors-list");const inlined_types=new Set();const TEXT_IDX=0;const SYNTHETIC_IDX=1;const TYPES_IDX=2;if(synthetic_implementors){onEachLazy(synthetic_implementors.getElementsByClassName("impl"),el=>{const aliases=el.getAttribute("data-aliases");if(!aliases){return}aliases.split(",").forEach(alias=>{inlined_types.add(alias)})})}let currentNbImpls=implementors.getElementsByClassName("impl").length;const traitName=document.querySelector(".main-heading h1 > .trait").textContent;const baseIdName="impl-"+traitName+"-";const libs=Object.getOwnPropertyNames(imp);const script=document.querySelector("script[data-ignore-extern-crates]");const ignoreExternCrates=new Set((script?script.getAttribute("data-ignore-extern-crates"):"").split(","));for(const lib of libs){if(lib===window.currentCrate||ignoreExternCrates.has(lib)){continue}const structs=imp[lib];struct_loop:for(const struct of structs){const list=struct[SYNTHETIC_IDX]?synthetic_implementors:implementors;if(struct[SYNTHETIC_IDX]){for(const struct_type of struct[TYPES_IDX]){if(inlined_types.has(struct_type)){continue struct_loop}inlined_types.add(struct_type)}}const code=document.createElement("h3");code.innerHTML=struct[TEXT_IDX];addClass(code,"code-header");onEachLazy(code.getElementsByTagName("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});const currentId=baseIdName+currentNbImpls;const anchor=document.createElement("a");anchor.href="#"+currentId;addClass(anchor,"anchor");const display=document.createElement("div");display.id=currentId;addClass(display,"impl");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}window.register_type_impls=imp=>{if(!imp||!imp[window.currentCrate]){return}window.pending_type_impls=null;const idMap=new Map();let implementations=document.getElementById("implementations-list");let trait_implementations=document.getElementById("trait-implementations-list");let trait_implementations_header=document.getElementById("trait-implementations");const script=document.querySelector("script[data-self-path]");const selfPath=script?script.getAttribute("data-self-path"):null;const mainContent=document.querySelector("#main-content");const sidebarSection=document.querySelector(".sidebar section");let methods=document.querySelector(".sidebar .block.method");let associatedTypes=document.querySelector(".sidebar .block.associatedtype");let associatedConstants=document.querySelector(".sidebar .block.associatedconstant");let sidebarTraitList=document.querySelector(".sidebar .block.trait-implementation");for(const impList of imp[window.currentCrate]){const types=impList.slice(2);const text=impList[0];const isTrait=impList[1]!==0;const traitName=impList[1];if(types.indexOf(selfPath)===-1){continue}let outputList=isTrait?trait_implementations:implementations;if(outputList===null){const outputListName=isTrait?"Trait Implementations":"Implementations";const outputListId=isTrait?"trait-implementations-list":"implementations-list";const outputListHeaderId=isTrait?"trait-implementations":"implementations";const outputListHeader=document.createElement("h2");outputListHeader.id=outputListHeaderId;outputListHeader.innerText=outputListName;outputList=document.createElement("div");outputList.id=outputListId;if(isTrait){const link=document.createElement("a");link.href=`#${outputListHeaderId}`;link.innerText="Trait Implementations";const h=document.createElement("h3");h.appendChild(link);trait_implementations=outputList;trait_implementations_header=outputListHeader;sidebarSection.appendChild(h);sidebarTraitList=document.createElement("ul");sidebarTraitList.className="block trait-implementation";sidebarSection.appendChild(sidebarTraitList);mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}else{implementations=outputList;if(trait_implementations){mainContent.insertBefore(outputListHeader,trait_implementations_header);mainContent.insertBefore(outputList,trait_implementations_header)}else{const mainContent=document.querySelector("#main-content");mainContent.appendChild(outputListHeader);mainContent.appendChild(outputList)}}}const template=document.createElement("template");template.innerHTML=text;onEachLazy(template.content.querySelectorAll("a"),elem=>{const href=elem.getAttribute("href");if(href&&!href.startsWith("#")&&!/^(?:[a-z+]+:)?\/\//.test(href)){elem.setAttribute("href",window.rootPath+href)}});onEachLazy(template.content.querySelectorAll("[id]"),el=>{let i=0;if(idMap.has(el.id)){i=idMap.get(el.id)}else if(document.getElementById(el.id)){i=1;while(document.getElementById(`${el.id}-${2 * i}`)){i=2*i}while(document.getElementById(`${el.id}-${i}`)){i+=1}}if(i!==0){const oldHref=`#${el.id}`;const newHref=`#${el.id}-${i}`;el.id=`${el.id}-${i}`;onEachLazy(template.content.querySelectorAll("a[href]"),link=>{if(link.getAttribute("href")===oldHref){link.href=newHref}})}idMap.set(el.id,i+1)});const templateAssocItems=template.content.querySelectorAll("section.tymethod, "+"section.method, section.associatedtype, section.associatedconstant");if(isTrait){const li=document.createElement("li");const a=document.createElement("a");a.href=`#${template.content.querySelector(".impl").id}`;a.textContent=traitName;li.appendChild(a);sidebarTraitList.append(li)}else{onEachLazy(templateAssocItems,item=>{let block=hasClass(item,"associatedtype")?associatedTypes:(hasClass(item,"associatedconstant")?associatedConstants:(methods));if(!block){const blockTitle=hasClass(item,"associatedtype")?"Associated Types":(hasClass(item,"associatedconstant")?"Associated Constants":("Methods"));const blockClass=hasClass(item,"associatedtype")?"associatedtype":(hasClass(item,"associatedconstant")?"associatedconstant":("method"));const blockHeader=document.createElement("h3");const blockLink=document.createElement("a");blockLink.href="#implementations";blockLink.innerText=blockTitle;blockHeader.appendChild(blockLink);block=document.createElement("ul");block.className=`block ${blockClass}`;const insertionReference=methods||sidebarTraitList;if(insertionReference){const insertionReferenceH=insertionReference.previousElementSibling;sidebarSection.insertBefore(blockHeader,insertionReferenceH);sidebarSection.insertBefore(block,insertionReferenceH)}else{sidebarSection.appendChild(blockHeader);sidebarSection.appendChild(block)}if(hasClass(item,"associatedtype")){associatedTypes=block}else if(hasClass(item,"associatedconstant")){associatedConstants=block}else{methods=block}}const li=document.createElement("li");const a=document.createElement("a");a.innerText=item.id.split("-")[0].split(".")[1];a.href=`#${item.id}`;li.appendChild(a);block.appendChild(li)})}outputList.appendChild(template.content)}for(const list of[methods,associatedTypes,associatedConstants,sidebarTraitList]){if(!list){continue}const newChildren=Array.prototype.slice.call(list.children);newChildren.sort((a,b)=>{const aI=a.innerText;const bI=b.innerText;return aIbI?1:0});list.replaceChildren(...newChildren)}};if(window.pending_type_impls){window.register_type_impls(window.pending_type_impls)}function addSidebarCrates(){if(!window.ALL_CRATES){return}const sidebarElems=document.getElementsByClassName("sidebar-elems")[0];if(!sidebarElems){return}const h3=document.createElement("h3");h3.innerHTML="Crates";const ul=document.createElement("ul");ul.className="block crate";for(const crate of window.ALL_CRATES){const link=document.createElement("a");link.href=window.rootPath+crate+"/index.html";link.textContent=crate;const li=document.createElement("li");if(window.rootPath!=="./"&&crate===window.currentCrate){li.className="current"}li.appendChild(link);ul.appendChild(li)}sidebarElems.appendChild(h3);sidebarElems.appendChild(ul)}function expandAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);removeClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hasClass(e,"type-contents-toggle")&&!hasClass(e,"more-examples-toggle")){e.open=true}});innerToggle.title="collapse all docs";innerToggle.children[0].innerText="\u2212"}function collapseAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);addClass(innerToggle,"will-expand");onEachLazy(document.getElementsByClassName("toggle"),e=>{if(e.parentNode.id!=="implementations-list"||(!hasClass(e,"implementors-toggle")&&!hasClass(e,"type-contents-toggle"))){e.open=false}});innerToggle.title="expand all docs";innerToggle.children[0].innerText="+"}function toggleAllDocs(){const innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}if(hasClass(innerToggle,"will-expand")){expandAllDocs()}else{collapseAllDocs()}}(function(){const toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}const hideMethodDocs=getSettingValue("auto-hide-method-docs")==="true";const hideImplementations=getSettingValue("auto-hide-trait-implementations")==="true";const hideLargeItemContents=getSettingValue("auto-hide-large-items")!=="false";function setImplementorsTogglesOpen(id,open){const list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName("implementors-toggle"),e=>{e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen("trait-implementations-list",false);setImplementorsTogglesOpen("blanket-implementations-list",false)}onEachLazy(document.getElementsByClassName("toggle"),e=>{if(!hideLargeItemContents&&hasClass(e,"type-contents-toggle")){e.open=true}if(hideMethodDocs&&hasClass(e,"method-toggle")){e.open=false}})}());window.rustdoc_add_line_numbers_to_examples=()=>{onEachLazy(document.getElementsByClassName("rust-example-rendered"),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");if(line_numbers.length>0){return}const count=x.textContent.split("\n").length;const elems=[];for(let i=0;i{onEachLazy(document.getElementsByClassName("rust-example-rendered"),x=>{const parent=x.parentNode;const line_numbers=parent.querySelectorAll(".example-line-numbers");for(const node of line_numbers){parent.removeChild(node)}})};if(getSettingValue("line-numbers")==="true"){window.rustdoc_add_line_numbers_to_examples()}function showSidebar(){window.hideAllModals(false);const sidebar=document.getElementsByClassName("sidebar")[0];addClass(sidebar,"shown")}function hideSidebar(){const sidebar=document.getElementsByClassName("sidebar")[0];removeClass(sidebar,"shown")}window.addEventListener("resize",()=>{if(window.CURRENT_TOOLTIP_ELEMENT){const base=window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE;const force_visible=base.TOOLTIP_FORCE_VISIBLE;hideTooltip(false);if(force_visible){showTooltip(base);base.TOOLTIP_FORCE_VISIBLE=true}}});const mainElem=document.getElementById(MAIN_ID);if(mainElem){mainElem.addEventListener("click",hideSidebar)}onEachLazy(document.querySelectorAll("a[href^='#']"),el=>{el.addEventListener("click",()=>{expandSection(el.hash.slice(1));hideSidebar()})});onEachLazy(document.querySelectorAll(".toggle > summary:not(.hideme)"),el=>{el.addEventListener("click",e=>{if(e.target.tagName!=="SUMMARY"&&e.target.tagName!=="A"){e.preventDefault()}})});function showTooltip(e){const notable_ty=e.getAttribute("data-notable-ty");if(!window.NOTABLE_TRAITS&¬able_ty){const data=document.getElementById("notable-traits-data");if(data){window.NOTABLE_TRAITS=JSON.parse(data.innerText)}else{throw new Error("showTooltip() called with notable without any notable traits!")}}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE===e){clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);return}window.hideAllModals(false);const wrapper=document.createElement("div");if(notable_ty){wrapper.innerHTML="
"+window.NOTABLE_TRAITS[notable_ty]+"
"}else{if(e.getAttribute("title")!==null){e.setAttribute("data-title",e.getAttribute("title"));e.removeAttribute("title")}if(e.getAttribute("data-title")!==null){const titleContent=document.createElement("div");titleContent.className="content";titleContent.appendChild(document.createTextNode(e.getAttribute("data-title")));wrapper.appendChild(titleContent)}}wrapper.className="tooltip popover";const focusCatcher=document.createElement("div");focusCatcher.setAttribute("tabindex","0");focusCatcher.onfocus=hideTooltip;wrapper.appendChild(focusCatcher);const pos=e.getBoundingClientRect();wrapper.style.top=(pos.top+window.scrollY+pos.height)+"px";wrapper.style.left=0;wrapper.style.right="auto";wrapper.style.visibility="hidden";const body=document.getElementsByTagName("body")[0];body.appendChild(wrapper);const wrapperPos=wrapper.getBoundingClientRect();const finalPos=pos.left+window.scrollX-wrapperPos.width+24;if(finalPos>0){wrapper.style.left=finalPos+"px"}else{wrapper.style.setProperty("--popover-arrow-offset",(wrapperPos.right-pos.right+4)+"px")}wrapper.style.visibility="";window.CURRENT_TOOLTIP_ELEMENT=wrapper;window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE=e;clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);wrapper.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}clearTooltipHoverTimeout(e)};wrapper.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&!e.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(wrapper,"fade-out")}}}function setTooltipHoverTimeout(element,show){clearTooltipHoverTimeout(element);if(!show&&!window.CURRENT_TOOLTIP_ELEMENT){return}if(show&&window.CURRENT_TOOLTIP_ELEMENT){return}if(window.CURRENT_TOOLTIP_ELEMENT&&window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE!==element){return}element.TOOLTIP_HOVER_TIMEOUT=setTimeout(()=>{if(show){showTooltip(element)}else if(!element.TOOLTIP_FORCE_VISIBLE){hideTooltip(false)}},show?window.RUSTDOC_TOOLTIP_HOVER_MS:window.RUSTDOC_TOOLTIP_HOVER_EXIT_MS)}function clearTooltipHoverTimeout(element){if(element.TOOLTIP_HOVER_TIMEOUT!==undefined){removeClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out");clearTimeout(element.TOOLTIP_HOVER_TIMEOUT);delete element.TOOLTIP_HOVER_TIMEOUT}}function tooltipBlurHandler(event){if(window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.contains(event.relatedTarget)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(document.activeElement)&&!window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.contains(event.relatedTarget)){setTimeout(()=>hideTooltip(false),0)}}function hideTooltip(focus){if(window.CURRENT_TOOLTIP_ELEMENT){if(window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE){if(focus){window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.focus()}window.CURRENT_TOOLTIP_ELEMENT.TOOLTIP_BASE.TOOLTIP_FORCE_VISIBLE=false}const body=document.getElementsByTagName("body")[0];body.removeChild(window.CURRENT_TOOLTIP_ELEMENT);clearTooltipHoverTimeout(window.CURRENT_TOOLTIP_ELEMENT);window.CURRENT_TOOLTIP_ELEMENT=null}}onEachLazy(document.getElementsByClassName("tooltip"),e=>{e.onclick=()=>{e.TOOLTIP_FORCE_VISIBLE=e.TOOLTIP_FORCE_VISIBLE?false:true;if(window.CURRENT_TOOLTIP_ELEMENT&&!e.TOOLTIP_FORCE_VISIBLE){hideTooltip(true)}else{showTooltip(e);window.CURRENT_TOOLTIP_ELEMENT.setAttribute("tabindex","0");window.CURRENT_TOOLTIP_ELEMENT.focus();window.CURRENT_TOOLTIP_ELEMENT.onblur=tooltipBlurHandler}return false};e.onpointerenter=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointermove=ev=>{if(ev.pointerType!=="mouse"){return}setTooltipHoverTimeout(e,true)};e.onpointerleave=ev=>{if(ev.pointerType!=="mouse"){return}if(!e.TOOLTIP_FORCE_VISIBLE&&window.CURRENT_TOOLTIP_ELEMENT&&!window.CURRENT_TOOLTIP_ELEMENT.contains(ev.relatedTarget)){setTooltipHoverTimeout(e,false);addClass(window.CURRENT_TOOLTIP_ELEMENT,"fade-out")}}});const sidebar_menu_toggle=document.getElementsByClassName("sidebar-menu-toggle")[0];if(sidebar_menu_toggle){sidebar_menu_toggle.addEventListener("click",()=>{const sidebar=document.getElementsByClassName("sidebar")[0];if(!hasClass(sidebar,"shown")){showSidebar()}else{hideSidebar()}})}function helpBlurHandler(event){blurHandler(event,getHelpButton(),window.hidePopoverMenus)}function buildHelpMenu(){const book_info=document.createElement("span");const channel=getVar("channel");book_info.className="top";book_info.innerHTML=`You can find more information in \ +the rustdoc book.`;const shortcuts=[["?","Show this help dialog"],["S","Focus the search field"],["↑","Move up in search results"],["↓","Move down in search results"],["← / →","Switch result tab (when results focused)"],["⏎","Go to active search result"],["+","Expand all sections"],["-","Collapse all sections"],].map(x=>"
"+x[0].split(" ").map((y,index)=>((index&1)===0?""+y+"":" "+y+" ")).join("")+"
"+x[1]+"
").join("");const div_shortcuts=document.createElement("div");addClass(div_shortcuts,"shortcuts");div_shortcuts.innerHTML="

Keyboard Shortcuts

"+shortcuts+"
";const infos=[`For a full list of all search features, take a look here.`,"Prefix searches with a type followed by a colon (e.g., fn:) to \ + restrict the search to a given item kind.","Accepted kinds are: fn, mod, struct, \ + enum, trait, type, macro, \ + and const.","Search functions by type signature (e.g., vec -> usize or \ + -> vec or String, enum:Cow -> bool)","You can look for items with an exact name by putting double quotes around \ + your request: \"string\"","Look for functions that accept or return \ + slices and \ + arrays by writing \ + square brackets (e.g., -> [u8] or [] -> Option)","Look for items inside another one by searching for a path: vec::Vec",].map(x=>"

"+x+"

").join("");const div_infos=document.createElement("div");addClass(div_infos,"infos");div_infos.innerHTML="

Search Tricks

"+infos;const rustdoc_version=document.createElement("span");rustdoc_version.className="bottom";const rustdoc_version_code=document.createElement("code");rustdoc_version_code.innerText="rustdoc "+getVar("rustdoc-version");rustdoc_version.appendChild(rustdoc_version_code);const container=document.createElement("div");if(!isHelpPage){container.className="popover"}container.id="help";container.style.display="none";const side_by_side=document.createElement("div");side_by_side.className="side-by-side";side_by_side.appendChild(div_shortcuts);side_by_side.appendChild(div_infos);container.appendChild(book_info);container.appendChild(side_by_side);container.appendChild(rustdoc_version);if(isHelpPage){const help_section=document.createElement("section");help_section.appendChild(container);document.getElementById("main-content").appendChild(help_section);container.style.display="block"}else{const help_button=getHelpButton();help_button.appendChild(container);container.onblur=helpBlurHandler;help_button.onblur=helpBlurHandler;help_button.children[0].onblur=helpBlurHandler}return container}window.hideAllModals=switchFocus=>{hideSidebar();window.hidePopoverMenus();hideTooltip(switchFocus)};window.hidePopoverMenus=()=>{onEachLazy(document.querySelectorAll(".search-form .popover"),elem=>{elem.style.display="none"})};function getHelpMenu(buildNeeded){let menu=getHelpButton().querySelector(".popover");if(!menu&&buildNeeded){menu=buildHelpMenu()}return menu}function showHelp(){getHelpButton().querySelector("a").focus();const menu=getHelpMenu(true);if(menu.style.display==="none"){window.hideAllModals();menu.style.display=""}}if(isHelpPage){showHelp();document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click",event=>{const target=event.target;if(target.tagName!=="A"||target.parentElement.id!==HELP_BUTTON_ID||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault()})}else{document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click",event=>{const target=event.target;if(target.tagName!=="A"||target.parentElement.id!==HELP_BUTTON_ID||event.ctrlKey||event.altKey||event.metaKey){return}event.preventDefault();const menu=getHelpMenu(true);const shouldShowHelp=menu.style.display==="none";if(shouldShowHelp){showHelp()}else{window.hidePopoverMenus()}})}setMobileTopbar();addSidebarItems();addSidebarCrates();onHashChange(null);window.addEventListener("hashchange",onHashChange);searchState.setup()}());(function(){const SIDEBAR_MIN=100;const SIDEBAR_MAX=500;const RUSTDOC_MOBILE_BREAKPOINT=700;const BODY_MIN=400;const SIDEBAR_VANISH_THRESHOLD=SIDEBAR_MIN/2;const sidebarButton=document.getElementById("sidebar-button");if(sidebarButton){sidebarButton.addEventListener("click",e=>{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false");e.preventDefault()})}let currentPointerId=null;let desiredSidebarSize=null;let pendingSidebarResizingFrame=false;const resizer=document.querySelector(".sidebar-resizer");const sidebar=document.querySelector(".sidebar");if(!resizer||!sidebar){return}const isSrcPage=hasClass(document.body,"src");function hideSidebar(){if(isSrcPage){window.rustdocCloseSourceSidebar();updateLocalStorage("src-sidebar-width",null);document.documentElement.style.removeProperty("--src-sidebar-width");sidebar.style.removeProperty("--src-sidebar-width");resizer.style.removeProperty("--src-sidebar-width")}else{addClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","true");updateLocalStorage("desktop-sidebar-width",null);document.documentElement.style.removeProperty("--desktop-sidebar-width");sidebar.style.removeProperty("--desktop-sidebar-width");resizer.style.removeProperty("--desktop-sidebar-width")}}function showSidebar(){if(isSrcPage){window.rustdocShowSourceSidebar()}else{removeClass(document.documentElement,"hide-sidebar");updateLocalStorage("hide-sidebar","false")}}function changeSidebarSize(size){if(isSrcPage){updateLocalStorage("src-sidebar-width",size);sidebar.style.setProperty("--src-sidebar-width",size+"px");resizer.style.setProperty("--src-sidebar-width",size+"px")}else{updateLocalStorage("desktop-sidebar-width",size);sidebar.style.setProperty("--desktop-sidebar-width",size+"px");resizer.style.setProperty("--desktop-sidebar-width",size+"px")}}function isSidebarHidden(){return isSrcPage?!hasClass(document.documentElement,"src-sidebar-expanded"):hasClass(document.documentElement,"hide-sidebar")}function resize(e){if(currentPointerId===null||currentPointerId!==e.pointerId){return}e.preventDefault();const pos=e.clientX-sidebar.offsetLeft-3;if(pos=SIDEBAR_MIN){if(isSidebarHidden()){showSidebar()}const constrainedPos=Math.min(pos,window.innerWidth-BODY_MIN,SIDEBAR_MAX);changeSidebarSize(constrainedPos);desiredSidebarSize=constrainedPos;if(pendingSidebarResizingFrame!==false){clearTimeout(pendingSidebarResizingFrame)}pendingSidebarResizingFrame=setTimeout(()=>{if(currentPointerId===null||pendingSidebarResizingFrame===false){return}pendingSidebarResizingFrame=false;document.documentElement.style.setProperty("--resizing-sidebar-width",desiredSidebarSize+"px")},100)}}window.addEventListener("resize",()=>{if(window.innerWidth=(window.innerWidth-BODY_MIN)){changeSidebarSize(window.innerWidth-BODY_MIN)}else if(desiredSidebarSize!==null&&desiredSidebarSize>SIDEBAR_MIN){changeSidebarSize(desiredSidebarSize)}});function stopResize(e){if(currentPointerId===null){return}if(e){e.preventDefault()}desiredSidebarSize=sidebar.getBoundingClientRect().width;removeClass(resizer,"active");window.removeEventListener("pointermove",resize,false);window.removeEventListener("pointerup",stopResize,false);removeClass(document.documentElement,"sidebar-resizing");document.documentElement.style.removeProperty("--resizing-sidebar-width");if(resizer.releasePointerCapture){resizer.releasePointerCapture(currentPointerId);currentPointerId=null}}function initResize(e){if(currentPointerId!==null||e.altKey||e.ctrlKey||e.metaKey||e.button!==0){return}if(resizer.setPointerCapture){resizer.setPointerCapture(e.pointerId);if(!resizer.hasPointerCapture(e.pointerId)){resizer.releasePointerCapture(e.pointerId);return}currentPointerId=e.pointerId}e.preventDefault();window.addEventListener("pointermove",resize,false);window.addEventListener("pointercancel",stopResize,false);window.addEventListener("pointerup",stopResize,false);addClass(resizer,"active");addClass(document.documentElement,"sidebar-resizing");const pos=e.clientX-sidebar.offsetLeft-3;document.documentElement.style.setProperty("--resizing-sidebar-width",pos+"px");desiredSidebarSize=null}resizer.addEventListener("pointerdown",initResize,false)}());(function(){let reset_button_timeout=null;const but=document.getElementById("copy-path");if(!but){return}but.onclick=()=>{const parent=but.parentElement;const path=[];onEach(parent.childNodes,child=>{if(child.tagName==="A"){path.push(child.textContent)}});const el=document.createElement("textarea");el.value=path.join("::");el.setAttribute("readonly","");el.style.position="absolute";el.style.left="-9999px";document.body.appendChild(el);el.select();document.execCommand("copy");document.body.removeChild(el);but.children[0].style.display="none";let tmp;if(but.childNodes.length<2){tmp=document.createTextNode("✓");but.appendChild(tmp)}else{onEachLazy(but.childNodes,e=>{if(e.nodeType===Node.TEXT_NODE){tmp=e;return true}});tmp.textContent="✓"}if(reset_button_timeout!==null){window.clearTimeout(reset_button_timeout)}function reset_button(){tmp.textContent="";reset_button_timeout=null;but.children[0].style.display=""}reset_button_timeout=window.setTimeout(reset_button,1000)}}()) \ No newline at end of file diff --git a/static.files/normalize-76eba96aa4d2e634.css b/static.files/normalize-76eba96aa4d2e634.css new file mode 100644 index 00000000..469959f1 --- /dev/null +++ b/static.files/normalize-76eba96aa4d2e634.css @@ -0,0 +1,2 @@ + /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ +html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:0.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type="button"],[type="reset"],[type="submit"],button{-webkit-appearance:button}[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} \ No newline at end of file diff --git a/static.files/noscript-feafe1bb7466e4bd.css b/static.files/noscript-feafe1bb7466e4bd.css new file mode 100644 index 00000000..7bbe07f1 --- /dev/null +++ b/static.files/noscript-feafe1bb7466e4bd.css @@ -0,0 +1 @@ + #main-content .attributes{margin-left:0 !important;}#copy-path,#sidebar-button,.sidebar-resizer{display:none;}nav.sub{display:none;}.src .sidebar{display:none;}.notable-traits{display:none;}:root{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--test-arrow-color:#f5f5f5;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#f5f5f5;--test-arrow-hover-background-color:rgb(78,139,202);--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}@media (prefers-color-scheme:dark){:root{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--test-arrow-color:#dedede;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#dedede;--test-arrow-hover-background-color:#4e8bca;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}} \ No newline at end of file diff --git a/static.files/rust-logo-151179464ae7ed46.svg b/static.files/rust-logo-151179464ae7ed46.svg new file mode 100644 index 00000000..62424d8f --- /dev/null +++ b/static.files/rust-logo-151179464ae7ed46.svg @@ -0,0 +1,61 @@ + + + diff --git a/static.files/rustdoc-ac92e1bbe349e143.css b/static.files/rustdoc-ac92e1bbe349e143.css new file mode 100644 index 00000000..27e3d9d5 --- /dev/null +++ b/static.files/rustdoc-ac92e1bbe349e143.css @@ -0,0 +1,18 @@ + :root{--nav-sub-mobile-padding:8px;--search-typename-width:6.75rem;--desktop-sidebar-width:200px;--src-sidebar-width:300px;--desktop-sidebar-z-index:100;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:400;src:local('Fira Sans'),url("FiraSans-Regular-018c141bf0843ffd.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Fira Sans';font-style:normal;font-weight:500;src:local('Fira Sans Medium'),url("FiraSans-Medium-8f9a781e4970d388.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:400;src:local('Source Serif 4'),url("SourceSerif4-Regular-46f98efaafac5295.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:italic;font-weight:400;src:local('Source Serif 4 Italic'),url("SourceSerif4-It-acdfaf1a8af734b1.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Serif 4';font-style:normal;font-weight:700;src:local('Source Serif 4 Bold'),url("SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:400;src:url("SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:italic;font-weight:400;src:url("SourceCodePro-It-1cc31594bf4f1f79.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'Source Code Pro';font-style:normal;font-weight:600;src:url("SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2") format("woff2");font-display:swap;}@font-face {font-family:'NanumBarunGothic';src:url("NanumBarunGothic-0f09457c7a19b7c6.ttf.woff2") format("woff2");font-display:swap;unicode-range:U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF;}*{box-sizing:border-box;}body{font:1rem/1.5 "Source Serif 4",NanumBarunGothic,serif;margin:0;position:relative;overflow-wrap:break-word;overflow-wrap:anywhere;font-feature-settings:"kern","liga";background-color:var(--main-background-color);color:var(--main-color);}h1{font-size:1.5rem;}h2{font-size:1.375rem;}h3{font-size:1.25rem;}h1,h2,h3,h4,h5,h6{font-weight:500;}h1,h2,h3,h4{margin:25px 0 15px 0;padding-bottom:6px;}.docblock h3,.docblock h4,h5,h6{margin:15px 0 5px 0;}.docblock>h2:first-child,.docblock>h3:first-child,.docblock>h4:first-child,.docblock>h5:first-child,.docblock>h6:first-child{margin-top:0;}.main-heading h1{margin:0;padding:0;flex-grow:1;overflow-wrap:break-word;overflow-wrap:anywhere;}.main-heading{display:flex;flex-wrap:wrap;padding-bottom:6px;margin-bottom:15px;}.content h2,.top-doc .docblock>h3,.top-doc .docblock>h4{border-bottom:1px solid var(--headings-border-bottom-color);}h1,h2{line-height:1.25;padding-top:3px;padding-bottom:9px;}h3.code-header{font-size:1.125rem;}h4.code-header{font-size:1rem;}.code-header{font-weight:600;margin:0;padding:0;white-space:pre-wrap;}#crate-search,h1,h2,h3,h4,h5,h6,.sidebar,.mobile-topbar,.search-input,.search-results .result-name,.item-name>a,.out-of-band,span.since,a.src,#help-button>a,summary.hideme,.scraped-example-list,ul.all-items{font-family:"Fira Sans",Arial,NanumBarunGothic,sans-serif;}#toggle-all-docs,a.anchor,.section-header a,#src-sidebar a,.rust a,.sidebar h2 a,.sidebar h3 a,.mobile-topbar h2 a,h1 a,.search-results a,.stab,.result-name i{color:var(--main-color);}span.enum,a.enum,span.struct,a.struct,span.union,a.union,span.primitive,a.primitive,span.type,a.type,span.foreigntype,a.foreigntype{color:var(--type-link-color);}span.trait,a.trait,span.traitalias,a.traitalias{color:var(--trait-link-color);}span.associatedtype,a.associatedtype,span.constant,a.constant,span.static,a.static{color:var(--assoc-item-link-color);}span.fn,a.fn,span.method,a.method,span.tymethod,a.tymethod{color:var(--function-link-color);}span.attr,a.attr,span.derive,a.derive,span.macro,a.macro{color:var(--macro-link-color);}span.mod,a.mod{color:var(--mod-link-color);}span.keyword,a.keyword{color:var(--keyword-link-color);}a{color:var(--link-color);text-decoration:none;}ol,ul{padding-left:24px;}ul ul,ol ul,ul ol,ol ol{margin-bottom:.625em;}p,.docblock>.warning{margin:0 0 .75em 0;}p:last-child,.docblock>.warning:last-child{margin:0;}button{padding:1px 6px;cursor:pointer;}button#toggle-all-docs{padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.rustdoc{display:flex;flex-direction:row;flex-wrap:nowrap;}main{position:relative;flex-grow:1;padding:10px 15px 40px 45px;min-width:0;}.src main{padding:15px;}.width-limiter{max-width:960px;margin-right:auto;}details:not(.toggle) summary{margin-bottom:.6em;}code,pre,a.test-arrow,.code-header{font-family:"Source Code Pro",monospace;}.docblock code,.docblock-short code{border-radius:3px;padding:0 0.125em;}.docblock pre code,.docblock-short pre code{padding:0;}pre{padding:14px;line-height:1.5;}pre.item-decl{overflow-x:auto;}.item-decl .type-contents-toggle{contain:initial;}.src .content pre{padding:20px;}.rustdoc.src .example-wrap pre.src-line-numbers{padding:20px 0 20px 4px;}img{max-width:100%;}.sub-logo-container,.logo-container{line-height:0;display:block;}.sub-logo-container{margin-right:32px;}.sub-logo-container>img{height:60px;width:60px;object-fit:contain;}.rust-logo{filter:var(--rust-logo-filter);}.sidebar{font-size:0.875rem;flex:0 0 var(--desktop-sidebar-width);width:var(--desktop-sidebar-width);overflow-y:scroll;overscroll-behavior:contain;position:sticky;height:100vh;top:0;left:0;z-index:var(--desktop-sidebar-z-index);}.rustdoc.src .sidebar{flex-basis:50px;border-right:1px solid;overflow-x:hidden;overflow-y:hidden;}.hide-sidebar .sidebar,.hide-sidebar .sidebar-resizer{display:none;}.sidebar-resizer{touch-action:none;width:9px;cursor:col-resize;z-index:calc(var(--desktop-sidebar-z-index) + 1);position:fixed;height:100%;left:calc(var(--desktop-sidebar-width) + 1px);}.rustdoc.src .sidebar-resizer{left:49px;}.src-sidebar-expanded .rustdoc.src .sidebar-resizer{left:var(--src-sidebar-width);}.sidebar-resizing{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;}.sidebar-resizing*{cursor:col-resize !important;}.sidebar-resizing .sidebar{position:fixed;}.sidebar-resizing>body{padding-left:var(--resizing-sidebar-width);}.sidebar-resizer:hover,.sidebar-resizer:active,.sidebar-resizer:focus,.sidebar-resizer.active{width:10px;margin:0;left:var(--desktop-sidebar-width);border-left:solid 1px var(--sidebar-resizer-hover);}.src-sidebar-expanded .rustdoc.src .sidebar-resizer:hover,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:active,.src-sidebar-expanded .rustdoc.src .sidebar-resizer:focus,.src-sidebar-expanded .rustdoc.src .sidebar-resizer.active{left:calc(var(--src-sidebar-width) - 1px);}@media (pointer:coarse){.sidebar-resizer{display:none !important;}}.sidebar-resizer.active{padding:0 140px;width:2px;margin-left:-140px;border-left:none;}.sidebar-resizer.active:before{border-left:solid 2px var(--sidebar-resizer-active);display:block;height:100%;content:"";}.sidebar,.mobile-topbar,.sidebar-menu-toggle,#src-sidebar-toggle,#src-sidebar{background-color:var(--sidebar-background-color);}#src-sidebar-toggle>button:hover,#src-sidebar-toggle>button:focus{background-color:var(--sidebar-background-color-hover);}.src .sidebar>*:not(#src-sidebar-toggle){visibility:hidden;}.src-sidebar-expanded .src .sidebar{overflow-y:auto;flex-basis:var(--src-sidebar-width);width:var(--src-sidebar-width);}.src-sidebar-expanded .src .sidebar>*:not(#src-sidebar-toggle){visibility:visible;}#all-types{margin-top:1em;}*{scrollbar-width:initial;scrollbar-color:var(--scrollbar-color);}.sidebar{scrollbar-width:thin;scrollbar-color:var(--scrollbar-color);}::-webkit-scrollbar{width:12px;}.sidebar::-webkit-scrollbar{width:8px;}::-webkit-scrollbar-track{-webkit-box-shadow:inset 0;background-color:var(--scrollbar-track-background-color);}.sidebar::-webkit-scrollbar-track{background-color:var(--scrollbar-track-background-color);}::-webkit-scrollbar-thumb,.sidebar::-webkit-scrollbar-thumb{background-color:var(--scrollbar-thumb-background-color);}.hidden{display:none !important;}.logo-container>img{height:48px;width:48px;}ul.block,.block li{padding:0;margin:0;list-style:none;}.sidebar-elems a,.sidebar>h2 a{display:block;padding:0.25rem;margin-left:-0.25rem;margin-right:0.25rem;}.sidebar h2{overflow-wrap:anywhere;padding:0;margin:0.7rem 0;}.sidebar h3{font-size:1.125rem;padding:0;margin:0;}.sidebar-elems,.sidebar>.version,.sidebar>h2{padding-left:24px;}.sidebar a{color:var(--sidebar-link-color);}.sidebar .current,.sidebar .current a,.sidebar-crate a.logo-container:hover+h2 a,.sidebar a:hover:not(.logo-container){background-color:var(--sidebar-current-link-background-color);}.sidebar-elems .block{margin-bottom:2em;}.sidebar-elems .block li a{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;}.sidebar-crate{display:flex;align-items:center;justify-content:center;margin:14px 32px 1rem;row-gap:10px;column-gap:32px;flex-wrap:wrap;}.sidebar-crate h2{flex-grow:1;margin:0 -8px;align-self:start;}.sidebar-crate .logo-container{margin:0 -16px 0 -16px;text-align:center;}.sidebar-crate h2 a{display:block;margin:0 calc(-24px + 0.25rem) 0 -0.5rem;padding:calc((16px - 0.57rem ) / 2 ) 0.25rem;padding-left:0.5rem;}.sidebar-crate h2 .version{display:block;font-weight:normal;font-size:1rem;overflow-wrap:break-word;margin-top:calc((-16px + 0.57rem ) / 2 );}.sidebar-crate+.version{margin-top:-1rem;margin-bottom:1rem;}.mobile-topbar{display:none;}.rustdoc .example-wrap{display:flex;position:relative;margin-bottom:10px;}.rustdoc .example-wrap:last-child{margin-bottom:0px;}.rustdoc .example-wrap pre{margin:0;flex-grow:1;}.rustdoc:not(.src) .example-wrap pre{overflow:auto hidden;}.rustdoc .example-wrap pre.example-line-numbers,.rustdoc .example-wrap pre.src-line-numbers{flex-grow:0;min-width:fit-content;overflow:initial;text-align:right;-webkit-user-select:none;user-select:none;padding:14px 8px;color:var(--src-line-numbers-span-color);}.rustdoc .example-wrap pre.src-line-numbers{padding:14px 0;}.src-line-numbers a,.src-line-numbers span{color:var(--src-line-numbers-span-color);padding:0 8px;}.src-line-numbers :target{background-color:transparent;border-right:none;padding:0 8px;}.src-line-numbers .line-highlighted{background-color:var(--src-line-number-highlighted-background-color);}.search-loading{text-align:center;}.docblock-short{overflow-wrap:break-word;overflow-wrap:anywhere;}.docblock :not(pre)>code,.docblock-short code{white-space:pre-wrap;}.top-doc .docblock h2{font-size:1.375rem;}.top-doc .docblock h3{font-size:1.25rem;}.top-doc .docblock h4,.top-doc .docblock h5{font-size:1.125rem;}.top-doc .docblock h6{font-size:1rem;}.docblock h5{font-size:1rem;}.docblock h6{font-size:0.875rem;}.docblock{margin-left:24px;position:relative;}.docblock>:not(.more-examples-toggle):not(.example-wrap){max-width:100%;overflow-x:auto;}.out-of-band{flex-grow:0;font-size:1.125rem;}.docblock code,.docblock-short code,pre,.rustdoc.src .example-wrap{background-color:var(--code-block-background-color);}#main-content{position:relative;}.docblock table{margin:.5em 0;border-collapse:collapse;}.docblock table td,.docblock table th{padding:.5em;border:1px solid var(--border-color);}.docblock table tbody tr:nth-child(2n){background:var(--table-alt-row-background-color);}div.where{white-space:pre-wrap;font-size:0.875rem;}.item-info{display:block;margin-left:24px;}.item-info code{font-size:0.875rem;}#main-content>.item-info{margin-left:0;}nav.sub{flex-grow:1;flex-flow:row nowrap;margin:4px 0 25px 0;display:flex;align-items:center;}.search-form{position:relative;display:flex;height:34px;flex-grow:1;}.src nav.sub{margin:0 0 15px 0;}.section-header{display:block;position:relative;}.section-header:hover>.anchor,.impl:hover>.anchor,.trait-impl:hover>.anchor,.variant:hover>.anchor{display:initial;}.anchor{display:none;position:absolute;left:-0.5em;background:none !important;}.anchor.field{left:-5px;}.section-header>.anchor{left:-15px;padding-right:8px;}h2.section-header>.anchor{padding-right:6px;}.main-heading a:hover,.example-wrap .rust a:hover,.all-items a:hover,.docblock a:not(.test-arrow):not(.scrape-help):not(.tooltip):hover,.docblock-short a:not(.test-arrow):not(.scrape-help):not(.tooltip):hover,.item-info a{text-decoration:underline;}.crate.block li.current a{font-weight:500;}table,.item-table{overflow-wrap:break-word;}.item-table{display:table;padding:0;margin:0;}.item-table>li{display:table-row;}.item-table>li>div{display:table-cell;}.item-table>li>.item-name{padding-right:1.25rem;}.search-results-title{margin-top:0;white-space:nowrap;display:flex;align-items:baseline;}#crate-search-div{position:relative;min-width:5em;}#crate-search{min-width:115px;padding:0 23px 0 4px;max-width:100%;text-overflow:ellipsis;border:1px solid var(--border-color);border-radius:4px;outline:none;cursor:pointer;-moz-appearance:none;-webkit-appearance:none;text-indent:0.01px;background-color:var(--main-background-color);color:inherit;line-height:1.5;font-weight:500;}#crate-search:hover,#crate-search:focus{border-color:var(--crate-search-hover-border);}#crate-search-div::after{pointer-events:none;width:100%;height:100%;position:absolute;top:0;left:0;content:"";background-repeat:no-repeat;background-size:20px;background-position:calc(100% - 2px) 56%;background-image:url('data:image/svg+xml, \ + ');filter:var(--crate-search-div-filter);}#crate-search-div:hover::after,#crate-search-div:focus-within::after{filter:var(--crate-search-div-hover-filter);}#crate-search>option{font-size:1rem;}.search-input{-webkit-appearance:none;outline:none;border:1px solid var(--border-color);border-radius:2px;padding:8px;font-size:1rem;flex-grow:1;background-color:var(--button-background-color);color:var(--search-color);}.search-input:focus{border-color:var(--search-input-focused-border-color);}.search-results{display:none;}.search-results.active{display:block;}.search-results>a{display:flex;margin-left:2px;margin-right:2px;border-bottom:1px solid var(--search-result-border-color);gap:1em;}.search-results>a>div.desc{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;flex:2;}.search-results a:hover,.search-results a:focus{background-color:var(--search-result-link-focus-background-color);}.search-results .result-name{display:flex;align-items:center;justify-content:start;flex:3;}.search-results .result-name .alias{color:var(--search-results-alias-color);}.search-results .result-name .grey{color:var(--search-results-grey-color);}.search-results .result-name .typename{color:var(--search-results-grey-color);font-size:0.875rem;width:var(--search-typename-width);}.search-results .result-name .path{word-break:break-all;max-width:calc(100% - var(--search-typename-width));display:inline-block;}.search-results .result-name .path>*{display:inline;}.popover{position:absolute;top:100%;right:0;z-index:calc(var(--desktop-sidebar-z-index) + 1);margin-top:7px;border-radius:3px;border:1px solid var(--border-color);background-color:var(--main-background-color);color:var(--main-color);--popover-arrow-offset:11px;}.popover::before{content:'';position:absolute;right:var(--popover-arrow-offset);border:solid var(--border-color);border-width:1px 1px 0 0;background-color:var(--main-background-color);padding:4px;transform:rotate(-45deg);top:-5px;}.setting-line{margin:1.2em 0.6em;}.setting-radio input,.setting-check input{margin-right:0.3em;height:1.2rem;width:1.2rem;border:2px solid var(--settings-input-border-color);outline:none;-webkit-appearance:none;cursor:pointer;}.setting-radio input{border-radius:50%;}.setting-radio span,.setting-check span{padding-bottom:1px;}.setting-radio{margin-top:0.1em;margin-bottom:0.1em;min-width:3.8em;padding:0.3em;display:inline-flex;align-items:center;cursor:pointer;}.setting-radio+.setting-radio{margin-left:0.5em;}.setting-check{margin-right:20px;display:flex;align-items:center;cursor:pointer;}.setting-radio input:checked{box-shadow:inset 0 0 0 3px var(--main-background-color);background-color:var(--settings-input-color);}.setting-check input:checked{background-color:var(--settings-input-color);border-width:1px;content:url('data:image/svg+xml,\ + \ + ');}.setting-radio input:focus,.setting-check input:focus{box-shadow:0 0 1px 1px var(--settings-input-color);}.setting-radio input:checked:focus{box-shadow:inset 0 0 0 3px var(--main-background-color),0 0 2px 2px var(--settings-input-color);}.setting-radio input:hover,.setting-check input:hover{border-color:var(--settings-input-color) !important;}#help.popover{max-width:600px;--popover-arrow-offset:48px;}#help dt{float:left;clear:left;margin-right:0.5rem;}#help span.top,#help span.bottom{text-align:center;display:block;font-size:1.125rem;}#help span.top{margin:10px 0;border-bottom:1px solid var(--border-color);padding-bottom:4px;margin-bottom:6px;}#help span.bottom{clear:both;border-top:1px solid var(--border-color);}.side-by-side>div{width:50%;float:left;padding:0 20px 20px 17px;}.item-info .stab{display:block;padding:3px;margin-bottom:5px;}.item-name .stab{margin-left:0.3125em;}.stab{padding:0 2px;font-size:0.875rem;font-weight:normal;color:var(--main-color);background-color:var(--stab-background-color);width:fit-content;white-space:pre-wrap;border-radius:3px;display:inline;vertical-align:baseline;}.stab.portability>code{background:none;color:var(--stab-code-color);}.stab .emoji,.item-info .stab::before{font-size:1.25rem;}.stab .emoji{margin-right:0.3rem;}.item-info .stab::before{content:"\0";width:0;display:inline-block;color:transparent;}.emoji{text-shadow:1px 0 0 black,-1px 0 0 black,0 1px 0 black,0 -1px 0 black;}.since{font-weight:normal;font-size:initial;}.rightside{padding-left:12px;float:right;}.rightside:not(a),.out-of-band{color:var(--right-side-color);}pre.rust{tab-size:4;-moz-tab-size:4;}pre.rust .kw{color:var(--code-highlight-kw-color);}pre.rust .kw-2{color:var(--code-highlight-kw-2-color);}pre.rust .lifetime{color:var(--code-highlight-lifetime-color);}pre.rust .prelude-ty{color:var(--code-highlight-prelude-color);}pre.rust .prelude-val{color:var(--code-highlight-prelude-val-color);}pre.rust .string{color:var(--code-highlight-string-color);}pre.rust .number{color:var(--code-highlight-number-color);}pre.rust .bool-val{color:var(--code-highlight-literal-color);}pre.rust .self{color:var(--code-highlight-self-color);}pre.rust .attr{color:var(--code-highlight-attribute-color);}pre.rust .macro,pre.rust .macro-nonterminal{color:var(--code-highlight-macro-color);}pre.rust .question-mark{font-weight:bold;color:var(--code-highlight-question-mark-color);}pre.rust .comment{color:var(--code-highlight-comment-color);}pre.rust .doccomment{color:var(--code-highlight-doc-comment-color);}.rustdoc.src .example-wrap pre.rust a{background:var(--codeblock-link-background);}.example-wrap.compile_fail,.example-wrap.should_panic{border-left:2px solid var(--codeblock-error-color);}.ignore.example-wrap{border-left:2px solid var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover,.example-wrap.should_panic:hover{border-left:2px solid var(--codeblock-error-hover-color);}.example-wrap.ignore:hover{border-left:2px solid var(--codeblock-ignore-hover-color);}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip{color:var(--codeblock-error-color);}.example-wrap.ignore .tooltip{color:var(--codeblock-ignore-color);}.example-wrap.compile_fail:hover .tooltip,.example-wrap.should_panic:hover .tooltip{color:var(--codeblock-error-hover-color);}.example-wrap.ignore:hover .tooltip{color:var(--codeblock-ignore-hover-color);}.example-wrap .tooltip{position:absolute;display:block;left:-25px;top:5px;margin:0;line-height:1;}.example-wrap.compile_fail .tooltip,.example-wrap.should_panic .tooltip,.example-wrap.ignore .tooltip{font-weight:bold;font-size:1.25rem;}.content .docblock .warning{border-left:2px solid var(--warning-border-color);padding:14px;position:relative;overflow-x:visible !important;}.content .docblock .warning::before{color:var(--warning-border-color);content:"ⓘ";position:absolute;left:-25px;top:5px;font-weight:bold;font-size:1.25rem;}a.test-arrow{visibility:hidden;position:absolute;padding:5px 10px 5px 10px;border-radius:5px;font-size:1.375rem;top:5px;right:5px;z-index:1;color:var(--test-arrow-color);background-color:var(--test-arrow-background-color);}a.test-arrow:hover{color:var(--test-arrow-hover-color);background-color:var(--test-arrow-hover-background-color);}.example-wrap:hover .test-arrow{visibility:visible;}.code-attribute{font-weight:300;color:var(--code-attribute-color);}.item-spacer{width:100%;height:12px;display:block;}.out-of-band>span.since{font-size:1.25rem;}.sub-variant h4{font-size:1rem;font-weight:400;margin-top:0;margin-bottom:0;}.sub-variant{margin-left:24px;margin-bottom:40px;}.sub-variant>.sub-variant-field{margin-left:24px;}:target{padding-right:3px;background-color:var(--target-background-color);border-right:3px solid var(--target-border-color);}.code-header a.tooltip{color:inherit;margin-right:15px;position:relative;}.code-header a.tooltip:hover{color:var(--link-color);}a.tooltip:hover::after{position:absolute;top:calc(100% - 10px);left:-15px;right:-15px;height:20px;content:"\00a0";}.fade-out{opacity:0;transition:opacity 0.45s cubic-bezier(0,0,0.1,1.0);}.popover.tooltip .content{margin:0.25em 0.5em;}.popover.tooltip .content pre,.popover.tooltip .content code{background:transparent;margin:0;padding:0;font-size:1.25rem;white-space:pre-wrap;}.popover.tooltip .content>h3:first-child{margin:0 0 5px 0;}.search-failed{text-align:center;margin-top:20px;display:none;}.search-failed.active{display:block;}.search-failed>ul{text-align:left;max-width:570px;margin-left:auto;margin-right:auto;}#search-tabs{display:flex;flex-direction:row;gap:1px;margin-bottom:4px;}#search-tabs button{text-align:center;font-size:1.125rem;border:0;border-top:2px solid;flex:1;line-height:1.5;color:inherit;}#search-tabs button:not(.selected){background-color:var(--search-tab-button-not-selected-background);border-top-color:var(--search-tab-button-not-selected-border-top-color);}#search-tabs button:hover,#search-tabs button.selected{background-color:var(--search-tab-button-selected-background);border-top-color:var(--search-tab-button-selected-border-top-color);}#search-tabs .count{font-size:1rem;font-variant-numeric:tabular-nums;color:var(--search-tab-title-count-color);}#search .error code{border-radius:3px;background-color:var(--search-error-code-background-color);}.search-corrections{font-weight:normal;}#src-sidebar-toggle{position:sticky;top:0;left:0;font-size:1.25rem;border-bottom:1px solid;display:flex;height:40px;justify-content:stretch;align-items:stretch;z-index:10;}#src-sidebar{width:100%;overflow:auto;}#src-sidebar>.title{font-size:1.5rem;text-align:center;border-bottom:1px solid var(--border-color);margin-bottom:6px;}#src-sidebar div.files>a:hover,details.dir-entry summary:hover,#src-sidebar div.files>a:focus,details.dir-entry summary:focus{background-color:var(--src-sidebar-background-hover);}#src-sidebar div.files>a.selected{background-color:var(--src-sidebar-background-selected);}#src-sidebar-toggle>button{font-size:inherit;font-weight:bold;background:none;color:inherit;text-align:center;border:none;outline:none;flex:1 1;-webkit-appearance:none;opacity:1;}#settings-menu,#help-button{margin-left:4px;display:flex;}#sidebar-button{display:none;}.hide-sidebar #sidebar-button{display:flex;margin-right:4px;position:fixed;left:6px;height:34px;width:34px;background-color:var(--main-background-color);z-index:1;}#settings-menu>a,#help-button>a,#sidebar-button>a{display:flex;align-items:center;justify-content:center;background-color:var(--button-background-color);border:1px solid var(--border-color);border-radius:2px;color:var(--settings-button-color);font-size:20px;width:33px;}#settings-menu>a:hover,#settings-menu>a:focus,#help-button>a:hover,#help-button>a:focus,#sidebar-button>a:hover,#sidebar-button>a:focus{border-color:var(--settings-button-border-focus);}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}#copy-path{color:var(--copy-path-button-color);background:var(--main-background-color);height:34px;margin-left:10px;padding:0;padding-left:2px;border:0;width:33px;}#copy-path>img{filter:var(--copy-path-img-filter);}#copy-path:hover>img{filter:var(--copy-path-img-hover-filter);}@keyframes rotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}#settings-menu.rotate>a img{animation:rotating 2s linear infinite;}kbd{display:inline-block;padding:3px 5px;font:15px monospace;line-height:10px;vertical-align:middle;border:solid 1px var(--border-color);border-radius:3px;color:var(--kbd-color);background-color:var(--kbd-background);box-shadow:inset 0 -1px 0 var(--kbd-box-shadow-color);}ul.all-items>li{list-style:none;}details.dir-entry{padding-left:4px;}details.dir-entry>summary{margin:0 0 0 -4px;padding:0 0 0 4px;cursor:pointer;}details.dir-entry div.folders,details.dir-entry div.files{padding-left:23px;}details.dir-entry a{display:block;}details.toggle{contain:layout;position:relative;}details.toggle>summary.hideme{cursor:pointer;font-size:1rem;}details.toggle>summary{list-style:none;outline:none;}details.toggle>summary::-webkit-details-marker,details.toggle>summary::marker{display:none;}details.toggle>summary.hideme>span{margin-left:9px;}details.toggle>summary::before{background:url('data:image/svg+xml,') no-repeat top left;content:"";cursor:pointer;width:16px;height:16px;display:inline-block;vertical-align:middle;opacity:.5;filter:var(--toggle-filter);}details.toggle>summary.hideme>span,.more-examples-toggle summary,.more-examples-toggle .hide-more{color:var(--toggles-color);}details.toggle>summary::after{content:"Expand";overflow:hidden;width:0;height:0;position:absolute;}details.toggle>summary.hideme::after{content:"";}details.toggle>summary:focus::before,details.toggle>summary:hover::before{opacity:1;}details.toggle>summary:focus-visible::before{outline:1px dotted #000;outline-offset:1px;}details.non-exhaustive{margin-bottom:8px;}details.toggle>summary.hideme::before{position:relative;}details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;top:4px;}.impl-items>details.toggle>summary:not(.hideme)::before{position:absolute;left:-24px;}details.toggle[open] >summary.hideme{position:absolute;}details.toggle[open] >summary.hideme>span{display:none;}details.toggle[open] >summary::before{background:url('data:image/svg+xml,') no-repeat top left;}details.toggle[open] >summary::after{content:"Collapse";}.docblock summary>*{display:inline-block;}.docblock>.example-wrap:first-child .tooltip{margin-top:16px;}@media (max-width:850px){#search-tabs .count{display:block;}}@media (max-width:700px){*[id]{scroll-margin-top:45px;}.hide-sidebar #sidebar-button{position:static;}.rustdoc{display:block;}main{padding-left:15px;padding-top:0px;}.main-heading{flex-direction:column;}.out-of-band{text-align:left;margin-left:initial;padding:initial;}.out-of-band .since::before{content:"Since ";}.sidebar .logo-container,.sidebar .location,.sidebar-resizer{display:none;}.sidebar{position:fixed;top:45px;left:-1000px;z-index:11;height:calc(100vh - 45px);width:200px;}.src main,.rustdoc.src .sidebar{top:0;padding:0;height:100vh;border:0;}.sidebar.shown,.src-sidebar-expanded .src .sidebar,.rustdoc:not(.src) .sidebar:focus-within{left:0;}.mobile-topbar h2{padding-bottom:0;margin:auto 0.5em auto auto;overflow:hidden;font-size:24px;}.mobile-topbar h2 a{display:block;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;}.mobile-topbar .logo-container>img{max-width:35px;max-height:35px;margin:5px 0 5px 20px;}.mobile-topbar{display:flex;flex-direction:row;position:sticky;z-index:10;font-size:2rem;height:45px;width:100%;left:0;top:0;}.hide-sidebar .mobile-topbar{display:none;}.sidebar-menu-toggle{width:45px;font-size:32px;border:none;color:var(--main-color);}.hide-sidebar .sidebar-menu-toggle{display:none;}.sidebar-elems{margin-top:1em;}.anchor{display:none !important;}#main-content>details.toggle>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}#src-sidebar-toggle{position:fixed;left:1px;top:100px;width:30px;font-size:1.5rem;padding:0;z-index:10;border-top-right-radius:3px;border-bottom-right-radius:3px;border:1px solid;border-left:0;}.src-sidebar-expanded #src-sidebar-toggle{left:unset;top:unset;width:unset;border-top-right-radius:unset;border-bottom-right-radius:unset;position:sticky;border:0;border-bottom:1px solid;}#copy-path,#help-button{display:none;}#sidebar-button>a:before{content:url('data:image/svg+xml,\ + \ + \ + ');width:22px;height:22px;}.item-table,.item-row,.item-table>li,.item-table>li>div,.search-results>a,.search-results>a>div{display:block;}.search-results>a{padding:5px 0px;}.search-results>a>div.desc,.item-table>li>div.desc{padding-left:2em;}.search-results .result-name{display:block;}.search-results .result-name .typename{width:initial;margin-right:0;}.search-results .result-name .typename,.search-results .result-name .path{display:inline;}.src-sidebar-expanded .src .sidebar{max-width:100vw;width:100vw;}details.toggle:not(.top-doc)>summary{margin-left:10px;}.impl-items>details.toggle>summary:not(.hideme)::before,#main-content>details.toggle:not(.top-doc)>summary::before,#main-content>div>details.toggle>summary::before{left:-11px;}.impl-items>.item-info{margin-left:34px;}.src nav.sub{margin:0;padding:var(--nav-sub-mobile-padding);}}@media (min-width:701px){.scraped-example-title{position:absolute;z-index:10;background:var(--main-background-color);bottom:8px;right:5px;padding:2px 4px;box-shadow:0 0 4px var(--main-background-color);}}@media print{nav.sidebar,nav.sub,.out-of-band,a.src,#copy-path,details.toggle[open] >summary::before,details.toggle>summary::before,details.toggle.top-doc>summary{display:none;}.docblock{margin-left:0;}main{padding:10px;}}@media (max-width:464px){.docblock{margin-left:12px;}.docblock code{overflow-wrap:break-word;overflow-wrap:anywhere;}nav.sub{flex-direction:column;}.search-form{align-self:stretch;}.sub-logo-container>img{height:35px;width:35px;margin-bottom:var(--nav-sub-mobile-padding);}}.variant,.implementors-toggle>summary,.impl,#implementors-list>.docblock,.impl-items>section,.impl-items>.toggle>summary,.methods>section,.methods>.toggle>summary{margin-bottom:0.75em;}.variants>.docblock,.implementors-toggle>.docblock,.impl-items>.toggle[open]:not(:last-child),.methods>.toggle[open]:not(:last-child),.implementors-toggle[open]:not(:last-child){margin-bottom:2em;}#trait-implementations-list .impl-items>.toggle:not(:last-child),#synthetic-implementations-list .impl-items>.toggle:not(:last-child),#blanket-implementations-list .impl-items>.toggle:not(:last-child){margin-bottom:1em;}.scraped-example-list .scrape-help{margin-left:10px;padding:0 4px;font-weight:normal;font-size:12px;position:relative;bottom:1px;border:1px solid var(--scrape-example-help-border-color);border-radius:50px;color:var(--scrape-example-help-color);}.scraped-example-list .scrape-help:hover{border-color:var(--scrape-example-help-hover-border-color);color:var(--scrape-example-help-hover-color);}.scraped-example{position:relative;}.scraped-example .code-wrapper{position:relative;display:flex;flex-direction:row;flex-wrap:wrap;width:100%;}.scraped-example:not(.expanded) .code-wrapper{max-height:calc(1.5em * 5 + 10px);}.scraped-example:not(.expanded) .code-wrapper pre{overflow-y:hidden;padding-bottom:0;max-height:calc(1.5em * 5 + 10px);}.more-scraped-examples .scraped-example:not(.expanded) .code-wrapper,.more-scraped-examples .scraped-example:not(.expanded) .code-wrapper pre{max-height:calc(1.5em * 10 + 10px);}.scraped-example .code-wrapper .next,.scraped-example .code-wrapper .prev,.scraped-example .code-wrapper .expand{color:var(--main-color);position:absolute;top:0.25em;z-index:1;padding:0;background:none;border:none;-webkit-appearance:none;opacity:1;}.scraped-example .code-wrapper .prev{right:2.25em;}.scraped-example .code-wrapper .next{right:1.25em;}.scraped-example .code-wrapper .expand{right:0.25em;}.scraped-example:not(.expanded) .code-wrapper::before,.scraped-example:not(.expanded) .code-wrapper::after{content:" ";width:100%;height:5px;position:absolute;z-index:1;}.scraped-example:not(.expanded) .code-wrapper::before{top:0;background:linear-gradient(to bottom,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example:not(.expanded) .code-wrapper::after{bottom:0;background:linear-gradient(to top,var(--scrape-example-code-wrapper-background-start),var(--scrape-example-code-wrapper-background-end));}.scraped-example .code-wrapper .example-wrap{width:100%;overflow-y:hidden;margin-bottom:0;}.scraped-example:not(.expanded) .code-wrapper .example-wrap{overflow-x:hidden;}.scraped-example .example-wrap .rust span.highlight{background:var(--scrape-example-code-line-highlight);}.scraped-example .example-wrap .rust span.highlight.focus{background:var(--scrape-example-code-line-highlight-focus);}.more-examples-toggle{max-width:calc(100% + 25px);margin-top:10px;margin-left:-25px;}.more-examples-toggle .hide-more{margin-left:25px;cursor:pointer;}.more-scraped-examples{margin-left:25px;position:relative;}.toggle-line{position:absolute;top:5px;bottom:0;right:calc(100% + 10px);padding:0 4px;cursor:pointer;}.toggle-line-inner{min-width:2px;height:100%;background:var(--scrape-example-toggle-line-background);}.toggle-line:hover .toggle-line-inner{background:var(--scrape-example-toggle-line-hover-background);}.more-scraped-examples .scraped-example,.example-links{margin-top:20px;}.more-scraped-examples .scraped-example:first-child{margin-top:5px;}.example-links ul{margin-bottom:0;}:root[data-theme="light"]{--main-background-color:white;--main-color:black;--settings-input-color:#2196f3;--settings-input-border-color:#717171;--settings-button-color:#000;--settings-button-border-focus:#717171;--sidebar-background-color:#f5f5f5;--sidebar-background-color-hover:#e0e0e0;--code-block-background-color:#f5f5f5;--scrollbar-track-background-color:#dcdcdc;--scrollbar-thumb-background-color:rgba(36,37,39,0.6);--scrollbar-color:rgba(36,37,39,0.6) #d9d9d9;--headings-border-bottom-color:#ddd;--border-color:#e0e0e0;--button-background-color:#fff;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:none;--search-input-focused-border-color:#66afe9;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(35%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ad378a;--trait-link-color:#6e4fc9;--assoc-item-link-color:#3873ad;--function-link-color:#ad7c37;--macro-link-color:#068000;--keyword-link-color:#3873ad;--mod-link-color:#3873ad;--link-color:#3873ad;--sidebar-link-color:#356da4;--sidebar-current-link-background-color:#fff;--search-result-link-focus-background-color:#ccc;--search-result-border-color:#aaa3;--search-color:#000;--search-error-code-background-color:#d0cccc;--search-results-alias-color:#000;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#e6e6e6;--search-tab-button-not-selected-background:#e6e6e6;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#fff;--stab-background-color:#fff5d6;--stab-code-color:#000;--code-highlight-kw-color:#8959a8;--code-highlight-kw-2-color:#4271ae;--code-highlight-lifetime-color:#b76514;--code-highlight-prelude-color:#4271ae;--code-highlight-prelude-val-color:#c82829;--code-highlight-number-color:#718c00;--code-highlight-string-color:#718c00;--code-highlight-literal-color:#c82829;--code-highlight-attribute-color:#c82829;--code-highlight-self-color:#c82829;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8e908c;--code-highlight-doc-comment-color:#4d4d4c;--src-line-numbers-span-color:#c67e2d;--src-line-number-highlighted-background-color:#fdffd3;--test-arrow-color:#f5f5f5;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#f5f5f5;--test-arrow-hover-background-color:rgb(78,139,202);--target-background-color:#fdffd3;--target-border-color:#ad7c37;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:initial;--crate-search-div-filter:invert(100%) sepia(0%) saturate(4223%) hue-rotate(289deg) brightness(114%) contrast(76%);--crate-search-div-hover-filter:invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%);--crate-search-hover-border:#717171;--src-sidebar-background-selected:#fff;--src-sidebar-background-hover:#e0e0e0;--table-alt-row-background-color:#f5f5f5;--codeblock-link-background:#eee;--scrape-example-toggle-line-background:#ccc;--scrape-example-toggle-line-hover-background:#999;--scrape-example-code-line-highlight:#fcffd6;--scrape-example-code-line-highlight-focus:#f6fdb0;--scrape-example-help-border-color:#555;--scrape-example-help-color:#333;--scrape-example-help-hover-border-color:#000;--scrape-example-help-hover-color:#000;--scrape-example-code-wrapper-background-start:rgba(255,255,255,1);--scrape-example-code-wrapper-background-end:rgba(255,255,255,0);--sidebar-resizer-hover:hsl(207,90%,66%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="dark"]{--main-background-color:#353535;--main-color:#ddd;--settings-input-color:#2196f3;--settings-input-border-color:#999;--settings-button-color:#000;--settings-button-border-focus:#ffb900;--sidebar-background-color:#505050;--sidebar-background-color-hover:#676767;--code-block-background-color:#2A2A2A;--scrollbar-track-background-color:#717171;--scrollbar-thumb-background-color:rgba(32,34,37,.6);--scrollbar-color:rgba(32,34,37,.6) #5a5a5a;--headings-border-bottom-color:#d2d2d2;--border-color:#e0e0e0;--button-background-color:#f0f0f0;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--search-input-focused-border-color:#008dfd;--copy-path-button-color:#999;--copy-path-img-filter:invert(50%);--copy-path-img-hover-filter:invert(65%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#2dbfb8;--trait-link-color:#b78cf2;--assoc-item-link-color:#d2991d;--function-link-color:#2bab63;--macro-link-color:#09bd00;--keyword-link-color:#d2991d;--mod-link-color:#d2991d;--link-color:#d2991d;--sidebar-link-color:#fdbf35;--sidebar-current-link-background-color:#444;--search-result-link-focus-background-color:#616161;--search-result-border-color:#aaa3;--search-color:#111;--search-error-code-background-color:#484848;--search-results-alias-color:#fff;--search-results-grey-color:#ccc;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:#252525;--search-tab-button-not-selected-background:#252525;--search-tab-button-selected-border-top-color:#0089ff;--search-tab-button-selected-background:#353535;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ab8ac1;--code-highlight-kw-2-color:#769acb;--code-highlight-lifetime-color:#d97f26;--code-highlight-prelude-color:#769acb;--code-highlight-prelude-val-color:#ee6868;--code-highlight-number-color:#83a300;--code-highlight-string-color:#83a300;--code-highlight-literal-color:#ee6868;--code-highlight-attribute-color:#ee6868;--code-highlight-self-color:#ee6868;--code-highlight-macro-color:#3e999f;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#8d8d8b;--code-highlight-doc-comment-color:#8ca375;--src-line-numbers-span-color:#3b91e2;--src-line-number-highlighted-background-color:#0a042f;--test-arrow-color:#dedede;--test-arrow-background-color:rgba(78,139,202,0.2);--test-arrow-hover-color:#dedede;--test-arrow-hover-background-color:#4e8bca;--target-background-color:#494a3d;--target-border-color:#bb7410;--kbd-color:#000;--kbd-background:#fafbfc;--kbd-box-shadow-color:#c6cbd1;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(94%) sepia(0%) saturate(721%) hue-rotate(255deg) brightness(90%) contrast(90%);--crate-search-div-hover-filter:invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%);--crate-search-hover-border:#2196f3;--src-sidebar-background-selected:#333;--src-sidebar-background-hover:#444;--table-alt-row-background-color:#2a2a2a;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(53,53,53,1);--scrape-example-code-wrapper-background-end:rgba(53,53,53,0);--sidebar-resizer-hover:hsl(207,30%,54%);--sidebar-resizer-active:hsl(207,90%,54%);}:root[data-theme="ayu"]{--main-background-color:#0f1419;--main-color:#c5c5c5;--settings-input-color:#ffb454;--settings-input-border-color:#999;--settings-button-color:#fff;--settings-button-border-focus:#e0e0e0;--sidebar-background-color:#14191f;--sidebar-background-color-hover:rgba(70,70,70,0.33);--code-block-background-color:#191f26;--scrollbar-track-background-color:transparent;--scrollbar-thumb-background-color:#5c6773;--scrollbar-color:#5c6773 #24292f;--headings-border-bottom-color:#5c6773;--border-color:#5c6773;--button-background-color:#141920;--right-side-color:grey;--code-attribute-color:#999;--toggles-color:#999;--toggle-filter:invert(100%);--search-input-focused-border-color:#5c6773;--copy-path-button-color:#fff;--copy-path-img-filter:invert(70%);--copy-path-img-hover-filter:invert(100%);--codeblock-error-hover-color:rgb(255,0,0);--codeblock-error-color:rgba(255,0,0,.5);--codeblock-ignore-hover-color:rgb(255,142,0);--codeblock-ignore-color:rgba(255,142,0,.6);--warning-border-color:#ff8e00;--type-link-color:#ffa0a5;--trait-link-color:#39afd7;--assoc-item-link-color:#39afd7;--function-link-color:#fdd687;--macro-link-color:#a37acc;--keyword-link-color:#39afd7;--mod-link-color:#39afd7;--link-color:#39afd7;--sidebar-link-color:#53b1db;--sidebar-current-link-background-color:transparent;--search-result-link-focus-background-color:#3c3c3c;--search-result-border-color:#aaa3;--search-color:#fff;--search-error-code-background-color:#4f4c4c;--search-results-alias-color:#c5c5c5;--search-results-grey-color:#999;--search-tab-title-count-color:#888;--search-tab-button-not-selected-border-top-color:none;--search-tab-button-not-selected-background:transparent !important;--search-tab-button-selected-border-top-color:none;--search-tab-button-selected-background:#141920 !important;--stab-background-color:#314559;--stab-code-color:#e6e1cf;--code-highlight-kw-color:#ff7733;--code-highlight-kw-2-color:#ff7733;--code-highlight-lifetime-color:#ff7733;--code-highlight-prelude-color:#69f2df;--code-highlight-prelude-val-color:#ff7733;--code-highlight-number-color:#b8cc52;--code-highlight-string-color:#b8cc52;--code-highlight-literal-color:#ff7733;--code-highlight-attribute-color:#e6e1cf;--code-highlight-self-color:#36a3d9;--code-highlight-macro-color:#a37acc;--code-highlight-question-mark-color:#ff9011;--code-highlight-comment-color:#788797;--code-highlight-doc-comment-color:#a1ac88;--src-line-numbers-span-color:#5c6773;--src-line-number-highlighted-background-color:rgba(255,236,164,0.06);--test-arrow-color:#788797;--test-arrow-background-color:rgba(57,175,215,0.09);--test-arrow-hover-color:#c5c5c5;--test-arrow-hover-background-color:rgba(57,175,215,0.368);--target-background-color:rgba(255,236,164,0.06);--target-border-color:rgba(255,180,76,0.85);--kbd-color:#c5c5c5;--kbd-background:#314559;--kbd-box-shadow-color:#5c6773;--rust-logo-filter:drop-shadow(1px 0 0px #fff) drop-shadow(0 1px 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 -1px 0 #fff);--crate-search-div-filter:invert(41%) sepia(12%) saturate(487%) hue-rotate(171deg) brightness(94%) contrast(94%);--crate-search-div-hover-filter:invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%);--crate-search-hover-border:#e0e0e0;--src-sidebar-background-selected:#14191f;--src-sidebar-background-hover:#14191f;--table-alt-row-background-color:#191f26;--codeblock-link-background:#333;--scrape-example-toggle-line-background:#999;--scrape-example-toggle-line-hover-background:#c5c5c5;--scrape-example-code-line-highlight:#5b3b01;--scrape-example-code-line-highlight-focus:#7c4b0f;--scrape-example-help-border-color:#aaa;--scrape-example-help-color:#eee;--scrape-example-help-hover-border-color:#fff;--scrape-example-help-hover-color:#fff;--scrape-example-code-wrapper-background-start:rgba(15,20,25,1);--scrape-example-code-wrapper-background-end:rgba(15,20,25,0);--sidebar-resizer-hover:hsl(34,50%,33%);--sidebar-resizer-active:hsl(34,100%,66%);}:root[data-theme="ayu"] h1,:root[data-theme="ayu"] h2,:root[data-theme="ayu"] h3,:root[data-theme="ayu"] h4,:where(:root[data-theme="ayu"]) h1 a,:root[data-theme="ayu"] .sidebar h2 a,:root[data-theme="ayu"] .sidebar h3 a,:root[data-theme="ayu"] #source-sidebar>.title{color:#fff;}:root[data-theme="ayu"] .docblock code{color:#ffb454;}:root[data-theme="ayu"] .docblock a>code{color:#39AFD7 !important;}:root[data-theme="ayu"] .code-header,:root[data-theme="ayu"] .docblock pre>code,:root[data-theme="ayu"] pre,:root[data-theme="ayu"] pre>code,:root[data-theme="ayu"] .item-info code,:root[data-theme="ayu"] .rustdoc.source .example-wrap{color:#e6e1cf;}:root[data-theme="ayu"] .sidebar .current,:root[data-theme="ayu"] .sidebar .current a,:root[data-theme="ayu"] .sidebar a:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:hover,:root[data-theme="ayu"] details.dir-entry summary:hover,:root[data-theme="ayu"] #src-sidebar div.files>a:focus,:root[data-theme="ayu"] details.dir-entry summary:focus,:root[data-theme="ayu"] #src-sidebar div.files>a.selected{color:#ffb44c;}:root[data-theme="ayu"] .sidebar-elems .location{color:#ff7733;}:root[data-theme="ayu"] .src-line-numbers .line-highlighted{color:#708090;padding-right:7px;border-right:1px solid #ffb44c;}:root[data-theme="ayu"] .search-results a:hover,:root[data-theme="ayu"] .search-results a:focus{color:#fff !important;background-color:#3c3c3c;}:root[data-theme="ayu"] .search-results a{color:#0096cf;}:root[data-theme="ayu"] .search-results a div.desc{color:#c5c5c5;}:root[data-theme="ayu"] .result-name .primitive>i,:root[data-theme="ayu"] .result-name .keyword>i{color:#788797;}:root[data-theme="ayu"] #search-tabs>button.selected{border-bottom:1px solid #ffb44c !important;border-top:none;}:root[data-theme="ayu"] #search-tabs>button:not(.selected){border:none;background-color:transparent !important;}:root[data-theme="ayu"] #search-tabs>button:hover{border-bottom:1px solid rgba(242,151,24,0.3);}:root[data-theme="ayu"] #settings-menu>a img,:root[data-theme="ayu"] #sidebar-button>a:before{filter:invert(100);} \ No newline at end of file diff --git a/static.files/scrape-examples-ef1e698c1d417c0c.js b/static.files/scrape-examples-ef1e698c1d417c0c.js new file mode 100644 index 00000000..ba830e37 --- /dev/null +++ b/static.files/scrape-examples-ef1e698c1d417c0c.js @@ -0,0 +1 @@ +"use strict";(function(){const DEFAULT_MAX_LINES=5;const HIDDEN_MAX_LINES=10;function scrollToLoc(elt,loc,isHidden){const lines=elt.querySelector(".src-line-numbers");let scrollOffset;const maxLines=isHidden?HIDDEN_MAX_LINES:DEFAULT_MAX_LINES;if(loc[1]-loc[0]>maxLines){const line=Math.max(0,loc[0]-1);scrollOffset=lines.children[line].offsetTop}else{const wrapper=elt.querySelector(".code-wrapper");const halfHeight=wrapper.offsetHeight/2;const offsetTop=lines.children[loc[0]].offsetTop;const lastLine=lines.children[loc[1]];const offsetBot=lastLine.offsetTop+lastLine.offsetHeight;const offsetMid=(offsetTop+offsetBot)/2;scrollOffset=offsetMid-halfHeight}lines.scrollTo(0,scrollOffset);elt.querySelector(".rust").scrollTo(0,scrollOffset)}function updateScrapedExample(example,isHidden){const locs=JSON.parse(example.attributes.getNamedItem("data-locs").textContent);let locIndex=0;const highlights=Array.prototype.slice.call(example.querySelectorAll(".highlight"));const link=example.querySelector(".scraped-example-title a");if(locs.length>1){const onChangeLoc=changeIndex=>{removeClass(highlights[locIndex],"focus");changeIndex();scrollToLoc(example,locs[locIndex][0],isHidden);addClass(highlights[locIndex],"focus");const url=locs[locIndex][1];const title=locs[locIndex][2];link.href=url;link.innerHTML=title};example.querySelector(".prev").addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex-1+locs.length)%locs.length})});example.querySelector(".next").addEventListener("click",()=>{onChangeLoc(()=>{locIndex=(locIndex+1)%locs.length})})}const expandButton=example.querySelector(".expand");if(expandButton){expandButton.addEventListener("click",()=>{if(hasClass(example,"expanded")){removeClass(example,"expanded");scrollToLoc(example,locs[0][0],isHidden)}else{addClass(example,"expanded")}})}scrollToLoc(example,locs[0][0],isHidden)}const firstExamples=document.querySelectorAll(".scraped-example-list > .scraped-example");onEachLazy(firstExamples,el=>updateScrapedExample(el,false));onEachLazy(document.querySelectorAll(".more-examples-toggle"),toggle=>{onEachLazy(toggle.querySelectorAll(".toggle-line, .hide-more"),button=>{button.addEventListener("click",()=>{toggle.open=false})});const moreExamples=toggle.querySelectorAll(".scraped-example");toggle.querySelector("summary").addEventListener("click",()=>{setTimeout(()=>{onEachLazy(moreExamples,el=>updateScrapedExample(el,true))})},{once:true})})})() \ No newline at end of file diff --git a/static.files/search-2b6ce74ff89ae146.js b/static.files/search-2b6ce74ff89ae146.js new file mode 100644 index 00000000..05459703 --- /dev/null +++ b/static.files/search-2b6ce74ff89ae146.js @@ -0,0 +1,5 @@ +"use strict";if(!Array.prototype.toSpliced){Array.prototype.toSpliced=function(){const me=this.slice();Array.prototype.splice.apply(me,arguments);return me}}(function(){const itemTypes=["keyword","primitive","mod","externcrate","import","struct","enum","fn","type","static","trait","impl","tymethod","method","structfield","variant","macro","associatedtype","constant","associatedconstant","union","foreigntype","existential","attr","derive","traitalias","generic",];const longItemTypes=["keyword","primitive type","module","extern crate","re-export","struct","enum","function","type alias","static","trait","","trait method","method","struct field","enum variant","macro","assoc type","constant","assoc const","union","foreign type","existential type","attribute macro","derive macro","trait alias",];const TY_GENERIC=itemTypes.indexOf("generic");const ROOT_PATH=typeof window!=="undefined"?window.rootPath:"../";function printTab(nb){let iter=0;let foundCurrentTab=false;let foundCurrentResultSet=false;onEachLazy(document.getElementById("search-tabs").childNodes,elem=>{if(nb===iter){addClass(elem,"selected");foundCurrentTab=true}else{removeClass(elem,"selected")}iter+=1});const isTypeSearch=(nb>0||iter===1);iter=0;onEachLazy(document.getElementById("results").childNodes,elem=>{if(nb===iter){addClass(elem,"active");foundCurrentResultSet=true}else{removeClass(elem,"active")}iter+=1});if(foundCurrentTab&&foundCurrentResultSet){searchState.currentTab=nb;const correctionsElem=document.getElementsByClassName("search-corrections");if(isTypeSearch){removeClass(correctionsElem[0],"hidden")}else{addClass(correctionsElem[0],"hidden")}}else if(nb!==0){printTab(0)}}const editDistanceState={current:[],prev:[],prevPrev:[],calculate:function calculate(a,b,limit){if(a.lengthlimit){return limit+1}while(b.length>0&&b[0]===a[0]){a=a.substring(1);b=b.substring(1)}while(b.length>0&&b[b.length-1]===a[a.length-1]){a=a.substring(0,a.length-1);b=b.substring(0,b.length-1)}if(b.length===0){return minDist}const aLength=a.length;const bLength=b.length;for(let i=0;i<=bLength;++i){this.current[i]=0;this.prev[i]=i;this.prevPrev[i]=Number.MAX_VALUE}for(let i=1;i<=aLength;++i){this.current[0]=i;const aIdx=i-1;for(let j=1;j<=bLength;++j){const bIdx=j-1;const substitutionCost=a[aIdx]===b[bIdx]?0:1;this.current[j]=Math.min(this.prev[j]+1,this.current[j-1]+1,this.prev[j-1]+substitutionCost);if((i>1)&&(j>1)&&(a[aIdx]===b[bIdx-1])&&(a[aIdx-1]===b[bIdx])){this.current[j]=Math.min(this.current[j],this.prevPrev[j-2]+1)}}const prevPrevTmp=this.prevPrev;this.prevPrev=this.prev;this.prev=this.current;this.current=prevPrevTmp}const distance=this.prev[bLength];return distance<=limit?distance:(limit+1)},};function editDistance(a,b,limit){return editDistanceState.calculate(a,b,limit)}function initSearch(rawSearchIndex){const MAX_RESULTS=200;const NO_TYPE_FILTER=-1;let searchIndex;let functionTypeFingerprint;let currentResults;let typeNameIdMap;const ALIASES=new Map();let typeNameIdOfArray;let typeNameIdOfSlice;let typeNameIdOfArrayOrSlice;function buildTypeMapIndex(name,isAssocType){if(name===""||name===null){return null}if(typeNameIdMap.has(name)){const obj=typeNameIdMap.get(name);obj.assocOnly=isAssocType&&obj.assocOnly;return obj.id}else{const id=typeNameIdMap.size;typeNameIdMap.set(name,{id,assocOnly:isAssocType});return id}}function isSpecialStartCharacter(c){return"<\"".indexOf(c)!==-1}function isEndCharacter(c){return"=,>-]".indexOf(c)!==-1}function isErrorCharacter(c){return"()".indexOf(c)!==-1}function itemTypeFromName(typename){const index=itemTypes.findIndex(i=>i===typename);if(index<0){throw["Unknown type filter ",typename]}return index}function getStringElem(query,parserState,isInGenerics){if(isInGenerics){throw["Unexpected ","\""," in generics"]}else if(query.literalSearch){throw["Cannot have more than one literal search element"]}else if(parserState.totalElems-parserState.genericsElems>0){throw["Cannot use literal search when there is more than one element"]}parserState.pos+=1;const start=parserState.pos;const end=getIdentEndPosition(parserState);if(parserState.pos>=parserState.length){throw["Unclosed ","\""]}else if(parserState.userQuery[end]!=="\""){throw["Unexpected ",parserState.userQuery[end]," in a string element"]}else if(start===end){throw["Cannot have empty string element"]}parserState.pos+=1;query.literalSearch=true}function isPathStart(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="::"}function isReturnArrow(parserState){return parserState.userQuery.slice(parserState.pos,parserState.pos+2)==="->"}function isIdentCharacter(c){return(c==="_"||(c>="0"&&c<="9")||(c>="a"&&c<="z")||(c>="A"&&c<="Z"))}function isSeparatorCharacter(c){return c===","||c==="="}function isPathSeparator(c){return c===":"||c===" "}function prevIs(parserState,lookingFor){let pos=parserState.pos;while(pos>0){const c=parserState.userQuery[pos-1];if(c===lookingFor){return true}else if(c!==" "){break}pos-=1}return false}function isLastElemGeneric(elems,parserState){return(elems.length>0&&elems[elems.length-1].generics.length>0)||prevIs(parserState,">")}function skipWhitespace(parserState){while(parserState.pos0){throw["Cannot have more than one element if you use quotes"]}const typeFilter=parserState.typeFilter;parserState.typeFilter=null;if(name==="!"){if(typeFilter!==null&&typeFilter!=="primitive"){throw["Invalid search type: primitive never type ","!"," and ",typeFilter," both specified",]}if(generics.length!==0){throw["Never type ","!"," does not accept generic parameters",]}const bindingName=parserState.isInBinding;parserState.isInBinding=null;return{name:"never",id:null,fullPath:["never"],pathWithoutLast:[],pathLast:"never",normalizedPathLast:"never",generics:[],bindings:new Map(),typeFilter:"primitive",bindingName,}}const quadcolon=/::\s*::/.exec(path);if(path.startsWith("::")){throw["Paths cannot start with ","::"]}else if(path.endsWith("::")){throw["Paths cannot end with ","::"]}else if(quadcolon!==null){throw["Unexpected ",quadcolon[0]]}const pathSegments=path.split(/(?:::\s*)|(?:\s+(?:::\s*)?)/);if(pathSegments.length===0||(pathSegments.length===1&&pathSegments[0]==="")){if(generics.length>0||prevIs(parserState,">")){throw["Found generics without a path"]}else{throw["Unexpected ",parserState.userQuery[parserState.pos]]}}for(const[i,pathSegment]of pathSegments.entries()){if(pathSegment==="!"){if(i!==0){throw["Never type ","!"," is not associated item"]}pathSegments[i]="never"}}parserState.totalElems+=1;if(isInGenerics){parserState.genericsElems+=1}const bindingName=parserState.isInBinding;parserState.isInBinding=null;const bindings=new Map();const pathLast=pathSegments[pathSegments.length-1];return{name:name.trim(),id:null,fullPath:pathSegments,pathWithoutLast:pathSegments.slice(0,pathSegments.length-1),pathLast,normalizedPathLast:pathLast.replace(/_/g,""),generics:generics.filter(gen=>{if(gen.bindingName!==null){bindings.set(gen.bindingName.name,[gen,...gen.bindingName.generics]);return false}return true}),bindings,typeFilter,bindingName,}}function getIdentEndPosition(parserState){const start=parserState.pos;let end=parserState.pos;let foundExclamation=-1;while(parserState.pos=end){throw["Found generics without a path"]}parserState.pos+=1;getItemsBefore(query,parserState,generics,">")}if(isStringElem){skipWhitespace(parserState)}if(start>=end&&generics.length===0){return}if(parserState.userQuery[parserState.pos]==="="){if(parserState.isInBinding){throw["Cannot write ","="," twice in a binding"]}if(!isInGenerics){throw["Type parameter ","="," must be within generics list"]}const name=parserState.userQuery.slice(start,end).trim();if(name==="!"){throw["Type parameter ","="," key cannot be ","!"," never type"]}if(name.includes("!")){throw["Type parameter ","="," key cannot be ","!"," macro"]}if(name.includes("::")){throw["Type parameter ","="," key cannot contain ","::"," path"]}if(name.includes(":")){throw["Type parameter ","="," key cannot contain ",":"," type"]}parserState.isInBinding={name,generics}}else{elems.push(createQueryElement(query,parserState,parserState.userQuery.slice(start,end),generics,isInGenerics))}}}function getItemsBefore(query,parserState,elems,endChar){let foundStopChar=true;let start=parserState.pos;const oldTypeFilter=parserState.typeFilter;parserState.typeFilter=null;const oldIsInBinding=parserState.isInBinding;parserState.isInBinding=null;let extra="";if(endChar===">"){extra="<"}else if(endChar==="]"){extra="["}else if(endChar===""){extra="->"}else{extra=endChar}while(parserState.pos"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(endChar!==""){throw["Expected ",",",", ","=",", or ",endChar,...extra,", found ",c,]}throw["Expected ",","," or ","=",...extra,", found ",c,]}const posBefore=parserState.pos;start=parserState.pos;getNextElem(query,parserState,elems,endChar!=="");if(endChar!==""&&parserState.pos>=parserState.length){throw["Unclosed ",extra]}if(posBefore===parserState.pos){parserState.pos+=1}foundStopChar=false}if(parserState.pos>=parserState.length&&endChar!==""){throw["Unclosed ",extra]}parserState.pos+=1;parserState.typeFilter=oldTypeFilter;parserState.isInBinding=oldIsInBinding}function checkExtraTypeFilterCharacters(start,parserState){const query=parserState.userQuery.slice(start,parserState.pos).trim();for(const c in query){if(!isIdentCharacter(query[c])){throw["Unexpected ",query[c]," in type filter (before ",":",")",]}}}function parseInput(query,parserState){let foundStopChar=true;let start=parserState.pos;while(parserState.pos"){if(isReturnArrow(parserState)){break}throw["Unexpected ",c," (did you mean ","->","?)"]}throw["Unexpected ",c]}else if(c===":"&&!isPathStart(parserState)){if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}else if(query.elems.length===0){throw["Expected type filter before ",":"]}else if(query.literalSearch){throw["Cannot use quotes on type filter"]}const typeFilterElem=query.elems.pop();checkExtraTypeFilterCharacters(start,parserState);parserState.typeFilter=typeFilterElem.name;parserState.pos+=1;parserState.totalElems-=1;query.literalSearch=false;foundStopChar=true;continue}else if(c===" "){skipWhitespace(parserState);continue}if(!foundStopChar){let extra="";if(isLastElemGeneric(query.elems,parserState)){extra=[" after ",">"]}else if(prevIs(parserState,"\"")){throw["Cannot have more than one element if you use quotes"]}if(parserState.typeFilter!==null){throw["Expected ",","," or ","->",...extra,", found ",c,]}throw["Expected ",",",", ",":"," or ","->",...extra,", found ",c,]}const before=query.elems.length;start=parserState.pos;getNextElem(query,parserState,query.elems,false);if(query.elems.length===before){parserState.pos+=1}foundStopChar=false}if(parserState.typeFilter!==null){throw["Unexpected ",":"," (expected path after type filter ",parserState.typeFilter+":",")",]}while(parserState.pos"]}break}else{parserState.pos+=1}}}function newParsedQuery(userQuery){return{original:userQuery,userQuery:userQuery.toLowerCase(),elems:[],returned:[],foundElems:0,totalElems:0,literalSearch:false,error:null,correction:null,proposeCorrectionFrom:null,proposeCorrectionTo:null,typeFingerprint:new Uint32Array(4),}}function buildUrl(search,filterCrates){let extra="?search="+encodeURIComponent(search);if(filterCrates!==null){extra+="&filter-crate="+encodeURIComponent(filterCrates)}return getNakedUrl()+extra+window.location.hash}function getFilterCrates(){const elem=document.getElementById("crate-search");if(elem&&elem.value!=="all crates"&&rawSearchIndex.has(elem.value)){return elem.value}return null}function parseQuery(userQuery){function convertTypeFilterOnElem(elem){if(elem.typeFilter!==null){let typeFilter=elem.typeFilter;if(typeFilter==="const"){typeFilter="constant"}elem.typeFilter=itemTypeFromName(typeFilter)}else{elem.typeFilter=NO_TYPE_FILTER}for(const elem2 of elem.generics){convertTypeFilterOnElem(elem2)}for(const constraints of elem.bindings.values()){for(const constraint of constraints){convertTypeFilterOnElem(constraint)}}}userQuery=userQuery.trim().replace(/\r|\n|\t/g," ");const parserState={length:userQuery.length,pos:0,totalElems:0,genericsElems:0,typeFilter:null,isInBinding:null,userQuery:userQuery.toLowerCase(),};let query=newParsedQuery(userQuery);try{parseInput(query,parserState);for(const elem of query.elems){convertTypeFilterOnElem(elem)}for(const elem of query.returned){convertTypeFilterOnElem(elem)}}catch(err){query=newParsedQuery(userQuery);query.error=err;return query}if(!query.literalSearch){query.literalSearch=parserState.totalElems>1}query.foundElems=query.elems.length+query.returned.length;query.totalElems=parserState.totalElems;return query}function createQueryResults(results_in_args,results_returned,results_others,parsedQuery){return{"in_args":results_in_args,"returned":results_returned,"others":results_others,"query":parsedQuery,}}function execQuery(parsedQuery,filterCrates,currentCrate){const results_others=new Map(),results_in_args=new Map(),results_returned=new Map();function transformResults(results){const duplicates=new Set();const out=[];for(const result of results){if(result.id!==-1){const obj=searchIndex[result.id];obj.dist=result.dist;const res=buildHrefAndPath(obj);obj.displayPath=pathSplitter(res[0]);obj.fullPath=obj.displayPath+obj.name;obj.fullPath+="|"+obj.ty;if(duplicates.has(obj.fullPath)){continue}duplicates.add(obj.fullPath);obj.href=res[1];out.push(obj);if(out.length>=MAX_RESULTS){break}}}return out}function sortResults(results,isType,preferredCrate){if(results.size===0){return[]}const userQuery=parsedQuery.userQuery;const result_list=[];for(const result of results.values()){result.item=searchIndex[result.id];result.word=searchIndex[result.id].word;result_list.push(result)}result_list.sort((aaa,bbb)=>{let a,b;a=(aaa.word!==userQuery);b=(bbb.word!==userQuery);if(a!==b){return a-b}a=(aaa.index<0);b=(bbb.index<0);if(a!==b){return a-b}a=aaa.path_dist;b=bbb.path_dist;if(a!==b){return a-b}a=aaa.index;b=bbb.index;if(a!==b){return a-b}a=(aaa.dist);b=(bbb.dist);if(a!==b){return a-b}a=aaa.item.deprecated;b=bbb.item.deprecated;if(a!==b){return a-b}a=(aaa.item.crate!==preferredCrate);b=(bbb.item.crate!==preferredCrate);if(a!==b){return a-b}a=aaa.word.length;b=bbb.word.length;if(a!==b){return a-b}a=aaa.word;b=bbb.word;if(a!==b){return(a>b?+1:-1)}a=(aaa.item.desc==="");b=(bbb.item.desc==="");if(a!==b){return a-b}a=aaa.item.ty;b=bbb.item.ty;if(a!==b){return a-b}a=aaa.item.path;b=bbb.item.path;if(a!==b){return(a>b?+1:-1)}return 0});return transformResults(result_list)}function unifyFunctionTypes(fnTypesIn,queryElems,whereClause,mgensIn,solutionCb){const mgens=mgensIn===null?null:new Map(mgensIn);if(queryElems.length===0){return!solutionCb||solutionCb(mgens)}if(!fnTypesIn||fnTypesIn.length===0){return false}const ql=queryElems.length;const fl=fnTypesIn.length;if(ql===1&&queryElems[0].generics.length===0&&queryElems[0].bindings.size===0){const queryElem=queryElems[0];for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,whereClause,mgens)){continue}if(fnType.id<0&&queryElem.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==queryElem.id){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,queryElem.id);if(!solutionCb||solutionCb(mgensScratch)){return true}}else if(!solutionCb||solutionCb(mgens?new Map(mgens):null)){return true}}for(const fnType of fnTypesIn){if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens)){continue}if(fnType.id<0){if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){continue}const mgensScratch=new Map(mgens);mgensScratch.set(fnType.id,0);if(unifyFunctionTypes(whereClause[(-fnType.id)-1],queryElems,whereClause,mgensScratch,solutionCb)){return true}}else if(unifyFunctionTypes([...fnType.generics,...Array.from(fnType.bindings.values()).flat()],queryElems,whereClause,mgens?new Map(mgens):null,solutionCb)){return true}}return false}const fnTypes=fnTypesIn.slice();const flast=fl-1;const qlast=ql-1;const queryElem=queryElems[qlast];let queryElemsTmp=null;for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsMatchCandidate(fnType,queryElem,whereClause,mgens)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==queryElem.id){continue}mgensScratch.set(fnType.id,queryElem.id)}else{mgensScratch=mgens}fnTypes[i]=fnTypes[flast];fnTypes.length=flast;if(!queryElemsTmp){queryElemsTmp=queryElems.slice(0,qlast)}const passesUnification=unifyFunctionTypes(fnTypes,queryElemsTmp,whereClause,mgensScratch,mgensScratch=>{if(fnType.generics.length===0&&queryElem.generics.length===0&&fnType.bindings.size===0&&queryElem.bindings.size===0){return!solutionCb||solutionCb(mgensScratch)}const solution=unifyFunctionTypeCheckBindings(fnType,queryElem,whereClause,mgensScratch);if(!solution){return false}const simplifiedGenerics=solution.simplifiedGenerics;for(const simplifiedMgens of solution.mgens){const passesUnification=unifyFunctionTypes(simplifiedGenerics,queryElem.generics,whereClause,simplifiedMgens,solutionCb);if(passesUnification){return true}}return false});if(passesUnification){return true}fnTypes[flast]=fnTypes[i];fnTypes[i]=fnType;fnTypes.length=fl}for(let i=flast;i>=0;i-=1){const fnType=fnTypes[i];if(!unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens)){continue}let mgensScratch;if(fnType.id<0){mgensScratch=new Map(mgens);if(mgensScratch.has(fnType.id)&&mgensScratch.get(fnType.id)!==0){continue}mgensScratch.set(fnType.id,0)}else{mgensScratch=mgens}const generics=fnType.id<0?whereClause[(-fnType.id)-1]:fnType.generics;const bindings=fnType.bindings?Array.from(fnType.bindings.values()).flat():[];const passesUnification=unifyFunctionTypes(fnTypes.toSpliced(i,1,...generics,...bindings),queryElems,whereClause,mgensScratch,solutionCb);if(passesUnification){return true}}return false}function unifyFunctionTypeIsMatchCandidate(fnType,queryElem,whereClause,mgensIn){if(!typePassesFilter(queryElem.typeFilter,fnType.ty)){return false}if(fnType.id<0&&queryElem.id<0){if(mgensIn){if(mgensIn.has(fnType.id)&&mgensIn.get(fnType.id)!==queryElem.id){return false}for(const[fid,qid]of mgensIn.entries()){if(fnType.id!==fid&&queryElem.id===qid){return false}if(fnType.id===fid&&queryElem.id!==qid){return false}}}return true}else{if(queryElem.id===typeNameIdOfArrayOrSlice&&(fnType.id===typeNameIdOfSlice||fnType.id===typeNameIdOfArray)){}else if(fnType.id!==queryElem.id||queryElem.id===null){return false}if((fnType.generics.length+fnType.bindings.size)===0&&queryElem.generics.length!==0){return false}if(fnType.bindings.size0){const fnTypePath=fnType.path!==undefined&&fnType.path!==null?fnType.path.split("::"):[];if(queryElemPathLength>fnTypePath.length){return false}let i=0;for(const path of fnTypePath){if(path===queryElem.pathWithoutLast[i]){i+=1;if(i>=queryElemPathLength){break}}}if(i0){let mgensSolutionSet=[mgensIn];for(const[name,constraints]of queryElem.bindings.entries()){if(mgensSolutionSet.length===0){return false}if(!fnType.bindings.has(name)){return false}const fnTypeBindings=fnType.bindings.get(name);mgensSolutionSet=mgensSolutionSet.flatMap(mgens=>{const newSolutions=[];unifyFunctionTypes(fnTypeBindings,constraints,whereClause,mgens,newMgens=>{newSolutions.push(newMgens);return false});return newSolutions})}if(mgensSolutionSet.length===0){return false}const binds=Array.from(fnType.bindings.entries()).flatMap(entry=>{const[name,constraints]=entry;if(queryElem.bindings.has(name)){return[]}else{return constraints}});if(simplifiedGenerics.length>0){simplifiedGenerics=[...simplifiedGenerics,...binds]}else{simplifiedGenerics=binds}return{simplifiedGenerics,mgens:mgensSolutionSet}}return{simplifiedGenerics,mgens:[mgensIn]}}function unifyFunctionTypeIsUnboxCandidate(fnType,queryElem,whereClause,mgens){if(fnType.id<0&&queryElem.id>=0){if(!whereClause){return false}if(mgens&&mgens.has(fnType.id)&&mgens.get(fnType.id)!==0){return false}const mgensTmp=new Map(mgens);mgensTmp.set(fnType.id,null);return checkIfInList(whereClause[(-fnType.id)-1],queryElem,whereClause,mgensTmp)}else if(fnType.generics.length>0||fnType.bindings.size>0){const simplifiedGenerics=[...fnType.generics,...Array.from(fnType.bindings.values()).flat(),];return checkIfInList(simplifiedGenerics,queryElem,whereClause,mgens)}return false}function checkIfInList(list,elem,whereClause,mgens){for(const entry of list){if(checkType(entry,elem,whereClause,mgens)){return true}}return false}function checkType(row,elem,whereClause,mgens){if(row.bindings.size===0&&elem.bindings.size===0){if(elem.id<0){return row.id<0||checkIfInList(row.generics,elem,whereClause,mgens)}if(row.id>0&&elem.id>0&&elem.pathWithoutLast.length===0&&typePassesFilter(elem.typeFilter,row.ty)&&elem.generics.length===0&&elem.id!==typeNameIdOfArrayOrSlice){return row.id===elem.id||checkIfInList(row.generics,elem,whereClause,mgens)}}return unifyFunctionTypes([row],[elem],whereClause,mgens)}function checkPath(contains,ty,maxEditDistance){if(contains.length===0){return 0}let ret_dist=maxEditDistance+1;const path=ty.path.split("::");if(ty.parent&&ty.parent.name){path.push(ty.parent.name.toLowerCase())}const length=path.length;const clength=contains.length;pathiter:for(let i=length-clength;i>=0;i-=1){let dist_total=0;for(let x=0;xmaxEditDistance){continue pathiter}dist_total+=dist}ret_dist=Math.min(ret_dist,Math.round(dist_total/clength))}return ret_dist}function typePassesFilter(filter,type){if(filter<=NO_TYPE_FILTER||filter===type)return true;const name=itemTypes[type];switch(itemTypes[filter]){case"constant":return name==="associatedconstant";case"fn":return name==="method"||name==="tymethod";case"type":return name==="primitive"||name==="associatedtype";case"trait":return name==="traitalias"}return false}function createAliasFromItem(item){return{crate:item.crate,name:item.name,path:item.path,desc:item.desc,ty:item.ty,parent:item.parent,type:item.type,is_alias:true,deprecated:item.deprecated,implDisambiguator:item.implDisambiguator,}}function handleAliases(ret,query,filterCrates,currentCrate){const lowerQuery=query.toLowerCase();const aliases=[];const crateAliases=[];if(filterCrates!==null){if(ALIASES.has(filterCrates)&&ALIASES.get(filterCrates).has(lowerQuery)){const query_aliases=ALIASES.get(filterCrates).get(lowerQuery);for(const alias of query_aliases){aliases.push(createAliasFromItem(searchIndex[alias]))}}}else{for(const[crate,crateAliasesIndex]of ALIASES){if(crateAliasesIndex.has(lowerQuery)){const pushTo=crate===currentCrate?crateAliases:aliases;const query_aliases=crateAliasesIndex.get(lowerQuery);for(const alias of query_aliases){pushTo.push(createAliasFromItem(searchIndex[alias]))}}}}const sortFunc=(aaa,bbb)=>{if(aaa.path{alias.alias=query;const res=buildHrefAndPath(alias);alias.displayPath=pathSplitter(res[0]);alias.fullPath=alias.displayPath+alias.name;alias.href=res[1];ret.others.unshift(alias);if(ret.others.length>MAX_RESULTS){ret.others.pop()}};aliases.forEach(pushFunc);crateAliases.forEach(pushFunc)}function addIntoResults(results,fullId,id,index,dist,path_dist,maxEditDistance){if(dist<=maxEditDistance||index!==-1){if(results.has(fullId)){const result=results.get(fullId);if(result.dontValidate||result.dist<=dist){return}}results.set(fullId,{id:id,index:index,dontValidate:parsedQuery.literalSearch,dist:dist,path_dist:path_dist,})}}function handleSingleArg(row,pos,elem,results_others,results_in_args,results_returned,maxEditDistance){if(!row||(filterCrates!==null&&row.crate!==filterCrates)){return}let path_dist=0;const fullId=row.id;const tfpDist=compareTypeFingerprints(fullId,parsedQuery.typeFingerprint);if(tfpDist!==null){const in_args=row.type&&row.type.inputs&&checkIfInList(row.type.inputs,elem,row.type.where_clause);const returned=row.type&&row.type.output&&checkIfInList(row.type.output,elem,row.type.where_clause);if(in_args){results_in_args.max_dist=Math.max(results_in_args.max_dist||0,tfpDist);const maxDist=results_in_args.sizenormalizedIndex&&normalizedIndex!==-1)){index=normalizedIndex}if(elem.fullPath.length>1){path_dist=checkPath(elem.pathWithoutLast,row,maxEditDistance);if(path_dist>maxEditDistance){return}}if(parsedQuery.literalSearch){if(row.word===elem.pathLast){addIntoResults(results_others,fullId,pos,index,0,path_dist)}return}const dist=editDistance(row.normalizedName,elem.normalizedPathLast,maxEditDistance);if(index===-1&&dist+path_dist>maxEditDistance){return}addIntoResults(results_others,fullId,pos,index,dist,path_dist,maxEditDistance)}function handleArgs(row,pos,results){if(!row||(filterCrates!==null&&row.crate!==filterCrates)||!row.type){return}const tfpDist=compareTypeFingerprints(row.id,parsedQuery.typeFingerprint);if(tfpDist===null){return}if(results.size>=MAX_RESULTS&&tfpDist>results.max_dist){return}if(!unifyFunctionTypes(row.type.inputs,parsedQuery.elems,row.type.where_clause,null,mgens=>{return unifyFunctionTypes(row.type.output,parsedQuery.returned,row.type.where_clause,mgens)})){return}results.max_dist=Math.max(results.max_dist||0,tfpDist);addIntoResults(results,row.id,pos,0,tfpDist,0,Number.MAX_VALUE)}function innerRunQuery(){let queryLen=0;for(const elem of parsedQuery.elems){queryLen+=elem.name.length}for(const elem of parsedQuery.returned){queryLen+=elem.name.length}const maxEditDistance=Math.floor(queryLen/3);const genericSymbols=new Map();function convertNameToId(elem,isAssocType){if(typeNameIdMap.has(elem.normalizedPathLast)&&(isAssocType||!typeNameIdMap.get(elem.normalizedPathLast).assocOnly)){elem.id=typeNameIdMap.get(elem.normalizedPathLast).id}else if(!parsedQuery.literalSearch){let match=null;let matchDist=maxEditDistance+1;let matchName="";for(const[name,{id,assocOnly}]of typeNameIdMap){const dist=editDistance(name,elem.normalizedPathLast,maxEditDistance);if(dist<=matchDist&&dist<=maxEditDistance&&(isAssocType||!assocOnly)){if(dist===matchDist&&matchName>name){continue}match=id;matchDist=dist;matchName=name}}if(match!==null){parsedQuery.correction=matchName}elem.id=match}if((elem.id===null&&parsedQuery.totalElems>1&&elem.typeFilter===-1&&elem.generics.length===0&&elem.bindings.size===0)||elem.typeFilter===TY_GENERIC){if(genericSymbols.has(elem.name)){elem.id=genericSymbols.get(elem.name)}else{elem.id=-(genericSymbols.size+1);genericSymbols.set(elem.name,elem.id)}if(elem.typeFilter===-1&&elem.name.length>=3){const maxPartDistance=Math.floor(elem.name.length/3);let matchDist=maxPartDistance+1;let matchName="";for(const name of typeNameIdMap.keys()){const dist=editDistance(name,elem.name,maxPartDistance);if(dist<=matchDist&&dist<=maxPartDistance){if(dist===matchDist&&matchName>name){continue}matchDist=dist;matchName=name}}if(matchName!==""){parsedQuery.proposeCorrectionFrom=elem.name;parsedQuery.proposeCorrectionTo=matchName}}elem.typeFilter=TY_GENERIC}if(elem.generics.length>0&&elem.typeFilter===TY_GENERIC){parsedQuery.error=["Generic type parameter ",elem.name," does not accept generic parameters",]}for(const elem2 of elem.generics){convertNameToId(elem2)}elem.bindings=new Map(Array.from(elem.bindings.entries()).map(entry=>{const[name,constraints]=entry;if(!typeNameIdMap.has(name)){parsedQuery.error=["Type parameter ",name," does not exist",];return[null,[]]}for(const elem2 of constraints){convertNameToId(elem2)}return[typeNameIdMap.get(name).id,constraints]}))}const fps=new Set();for(const elem of parsedQuery.elems){convertNameToId(elem);buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}for(const elem of parsedQuery.returned){convertNameToId(elem);buildFunctionTypeFingerprint(elem,parsedQuery.typeFingerprint,fps)}if(parsedQuery.foundElems===1&&parsedQuery.returned.length===0){if(parsedQuery.elems.length===1){const elem=parsedQuery.elems[0];for(let i=0,nSearchIndex=searchIndex.length;i0){const sortQ=(a,b)=>{const ag=a.generics.length===0&&a.bindings.size===0;const bg=b.generics.length===0&&b.bindings.size===0;if(ag!==bg){return ag-bg}const ai=a.id>0;const bi=b.id>0;return ai-bi};parsedQuery.elems.sort(sortQ);parsedQuery.returned.sort(sortQ);for(let i=0,nSearchIndex=searchIndex.length;i");if(tmp.endsWith("")){return tmp.slice(0,tmp.length-6)}return tmp}function addTab(array,query,display){const extraClass=display?" active":"";const output=document.createElement("div");if(array.length>0){output.className="search-results "+extraClass;array.forEach(item=>{const name=item.name;const type=itemTypes[item.ty];const longType=longItemTypes[item.ty];const typeName=longType.length!==0?`${longType}`:"?";const link=document.createElement("a");link.className="result-"+type;link.href=item.href;const resultName=document.createElement("div");resultName.className="result-name";resultName.insertAdjacentHTML("beforeend",`${typeName}`);link.appendChild(resultName);let alias=" ";if(item.is_alias){alias=`
\ +${item.alias} - see \ +
`}resultName.insertAdjacentHTML("beforeend",`
${alias}\ +${item.displayPath}${name}\ +
`);const description=document.createElement("div");description.className="desc";description.insertAdjacentHTML("beforeend",item.desc);link.appendChild(description);output.appendChild(link)})}else if(query.error===null){output.className="search-failed"+extraClass;output.innerHTML="No results :(
"+"Try on DuckDuckGo?

"+"Or try looking in one of these:"}return[output,array.length]}function makeTabHeader(tabNb,text,nbElems){const fmtNbElems=nbElems<10?`\u{2007}(${nbElems})\u{2007}\u{2007}`:nbElems<100?`\u{2007}(${nbElems})\u{2007}`:`\u{2007}(${nbElems})`;if(searchState.currentTab===tabNb){return""}return""}function showResults(results,go_to_first,filterCrates){const search=searchState.outputElement();if(go_to_first||(results.others.length===1&&getSettingValue("go-to-only-result")==="true")){window.onunload=()=>{};searchState.removeQueryParameters();const elem=document.createElement("a");elem.href=results.others[0].href;removeClass(elem,"active");document.body.appendChild(elem);elem.click();return}if(results.query===undefined){results.query=parseQuery(searchState.input.value)}currentResults=results.query.userQuery;const ret_others=addTab(results.others,results.query,true);const ret_in_args=addTab(results.in_args,results.query,false);const ret_returned=addTab(results.returned,results.query,false);let currentTab=searchState.currentTab;if((currentTab===0&&ret_others[1]===0)||(currentTab===1&&ret_in_args[1]===0)||(currentTab===2&&ret_returned[1]===0)){if(ret_others[1]!==0){currentTab=0}else if(ret_in_args[1]!==0){currentTab=1}else if(ret_returned[1]!==0){currentTab=2}}let crates="";if(rawSearchIndex.size>1){crates=" in 
"}let output=`

Results${crates}

`;if(results.query.error!==null){const error=results.query.error;error.forEach((value,index)=>{value=value.split("<").join("<").split(">").join(">");if(index%2!==0){error[index]=`${value.replaceAll(" ", " ")}`}else{error[index]=value}});output+=`

Query parser error: "${error.join("")}".

`;output+="
"+makeTabHeader(0,"In Names",ret_others[1])+"
";currentTab=0}else if(results.query.foundElems<=1&&results.query.returned.length===0){output+="
"+makeTabHeader(0,"In Names",ret_others[1])+makeTabHeader(1,"In Parameters",ret_in_args[1])+makeTabHeader(2,"In Return Types",ret_returned[1])+"
"}else{const signatureTabTitle=results.query.elems.length===0?"In Function Return Types":results.query.returned.length===0?"In Function Parameters":"In Function Signatures";output+="
"+makeTabHeader(0,signatureTabTitle,ret_others[1])+"
";currentTab=0}if(results.query.correction!==null){const orig=results.query.returned.length>0?results.query.returned[0].name:results.query.elems[0].name;output+="

"+`Type "${orig}" not found. `+"Showing results for closest type name "+`"${results.query.correction}" instead.

`}if(results.query.proposeCorrectionFrom!==null){const orig=results.query.proposeCorrectionFrom;const targ=results.query.proposeCorrectionTo;output+="

"+`Type "${orig}" not found and used as generic parameter. `+`Consider searching for "${targ}" instead.

`}const resultsElem=document.createElement("div");resultsElem.id="results";resultsElem.appendChild(ret_others[0]);resultsElem.appendChild(ret_in_args[0]);resultsElem.appendChild(ret_returned[0]);search.innerHTML=output;const crateSearch=document.getElementById("crate-search");if(crateSearch){crateSearch.addEventListener("input",updateCrate)}search.appendChild(resultsElem);searchState.showResults(search);const elems=document.getElementById("search-tabs").childNodes;searchState.focusedByTab=[];let i=0;for(const elem of elems){const j=i;elem.onclick=()=>printTab(j);searchState.focusedByTab.push(null);i+=1}printTab(currentTab)}function updateSearchHistory(url){if(!browserSupportsHistoryApi()){return}const params=searchState.getQueryStringParams();if(!history.state&&!params.search){history.pushState(null,"",url)}else{history.replaceState(null,"",url)}}function search(forced){const query=parseQuery(searchState.input.value.trim());let filterCrates=getFilterCrates();if(!forced&&query.userQuery===currentResults){if(query.userQuery.length>0){putBackSearch()}return}searchState.setLoadingSearch();const params=searchState.getQueryStringParams();if(filterCrates===null&¶ms["filter-crate"]!==undefined){filterCrates=params["filter-crate"]}searchState.title="Results for "+query.original+" - Rust";updateSearchHistory(buildUrl(query.original,filterCrates));showResults(execQuery(query,filterCrates,window.currentCrate),params.go_to_first,filterCrates)}function buildItemSearchTypeAll(types,lowercasePaths){return types.map(type=>buildItemSearchType(type,lowercasePaths))}function buildItemSearchType(type,lowercasePaths,isAssocType){const PATH_INDEX_DATA=0;const GENERICS_DATA=1;const BINDINGS_DATA=2;let pathIndex,generics,bindings;if(typeof type==="number"){pathIndex=type;generics=[];bindings=new Map()}else{pathIndex=type[PATH_INDEX_DATA];generics=buildItemSearchTypeAll(type[GENERICS_DATA],lowercasePaths);if(type.length>BINDINGS_DATA){bindings=new Map(type[BINDINGS_DATA].map(binding=>{const[assocType,constraints]=binding;return[buildItemSearchType(assocType,lowercasePaths,true).id,buildItemSearchTypeAll(constraints,lowercasePaths),]}))}else{bindings=new Map()}}if(pathIndex<0){return{id:pathIndex,ty:TY_GENERIC,path:null,generics,bindings,}}if(pathIndex===0){return{id:null,ty:null,path:null,generics,bindings,}}const item=lowercasePaths[pathIndex-1];return{id:buildTypeMapIndex(item.name,isAssocType),ty:item.ty,path:item.path,generics,bindings,}}function buildFunctionSearchType(functionSearchType,lowercasePaths){const INPUTS_DATA=0;const OUTPUT_DATA=1;if(functionSearchType===0){return null}let inputs,output;if(typeof functionSearchType[INPUTS_DATA]==="number"){inputs=[buildItemSearchType(functionSearchType[INPUTS_DATA],lowercasePaths)]}else{inputs=buildItemSearchTypeAll(functionSearchType[INPUTS_DATA],lowercasePaths)}if(functionSearchType.length>1){if(typeof functionSearchType[OUTPUT_DATA]==="number"){output=[buildItemSearchType(functionSearchType[OUTPUT_DATA],lowercasePaths)]}else{output=buildItemSearchTypeAll(functionSearchType[OUTPUT_DATA],lowercasePaths)}}else{output=[]}const where_clause=[];const l=functionSearchType.length;for(let i=2;i{k=(~~k+0x7ed55d16)+(k<<12);k=(k ^ 0xc761c23c)^(k>>>19);k=(~~k+0x165667b1)+(k<<5);k=(~~k+0xd3a2646c)^(k<<9);k=(~~k+0xfd7046c5)+(k<<3);return(k ^ 0xb55a4f09)^(k>>>16)};const hashint2=k=>{k=~k+(k<<15);k ^=k>>>12;k+=k<<2;k ^=k>>>4;k=Math.imul(k,2057);return k ^(k>>16)};if(input!==null){const h0a=hashint1(input);const h0b=hashint2(input);const h1a=~~(h0a+Math.imul(h0b,2));const h1b=~~(h0a+Math.imul(h0b,3));const h2a=~~(h0a+Math.imul(h0b,4));const h2b=~~(h0a+Math.imul(h0b,5));output[0]|=(1<<(h0a%32))|(1<<(h1b%32));output[1]|=(1<<(h1a%32))|(1<<(h2b%32));output[2]|=(1<<(h2a%32))|(1<<(h0b%32));fps.add(input)}for(const g of type.generics){buildFunctionTypeFingerprint(g,output,fps)}const fb={id:null,ty:0,generics:[],bindings:new Map(),};for(const[k,v]of type.bindings.entries()){fb.id=k;fb.generics=v;buildFunctionTypeFingerprint(fb,output,fps)}output[3]=fps.size}function compareTypeFingerprints(fullId,queryFingerprint){const fh0=functionTypeFingerprint[fullId*4];const fh1=functionTypeFingerprint[(fullId*4)+1];const fh2=functionTypeFingerprint[(fullId*4)+2];const[qh0,qh1,qh2]=queryFingerprint;const[in0,in1,in2]=[fh0&qh0,fh1&qh1,fh2&qh2];if((in0 ^ qh0)||(in1 ^ qh1)||(in2 ^ qh2)){return null}return functionTypeFingerprint[(fullId*4)+3]}function buildIndex(rawSearchIndex){searchIndex=[];typeNameIdMap=new Map();const charA="A".charCodeAt(0);let currentIndex=0;let id=0;typeNameIdOfArray=buildTypeMapIndex("array");typeNameIdOfSlice=buildTypeMapIndex("slice");typeNameIdOfArrayOrSlice=buildTypeMapIndex("[]");for(const crate of rawSearchIndex.values()){id+=crate.t.length+1}functionTypeFingerprint=new Uint32Array((id+1)*4);id=0;for(const[crate,crateCorpus]of rawSearchIndex){const crateRow={crate:crate,ty:3,name:crate,path:"",desc:crateCorpus.doc,parent:undefined,type:null,id:id,word:crate,normalizedName:crate.indexOf("_")===-1?crate:crate.replace(/_/g,""),deprecated:null,implDisambiguator:null,};id+=1;searchIndex.push(crateRow);currentIndex+=1;const itemTypes=crateCorpus.t;const itemNames=crateCorpus.n;const itemPaths=new Map(crateCorpus.q);const itemDescs=crateCorpus.d;const itemParentIdxs=crateCorpus.i;const itemFunctionSearchTypes=crateCorpus.f;const deprecatedItems=new Set(crateCorpus.c);const implDisambiguator=new Map(crateCorpus.b);const paths=crateCorpus.p;const aliases=crateCorpus.a;const lowercasePaths=[];let len=paths.length;let lastPath=itemPaths.get(0);for(let i=0;i2){path=itemPaths.has(elem[2])?itemPaths.get(elem[2]):lastPath;lastPath=path}lowercasePaths.push({ty:ty,name:name.toLowerCase(),path:path});paths[i]={ty:ty,name:name,path:path}}lastPath="";len=itemTypes.length;for(let i=0;i0?paths[itemParentIdxs[i]-1]:undefined,type,id:id,word,normalizedName:word.indexOf("_")===-1?word:word.replace(/_/g,""),deprecated:deprecatedItems.has(i),implDisambiguator:implDisambiguator.has(i)?implDisambiguator.get(i):null,};id+=1;searchIndex.push(row);lastPath=row.path}if(aliases){const currentCrateAliases=new Map();ALIASES.set(crate,currentCrateAliases);for(const alias_name in aliases){if(!Object.prototype.hasOwnProperty.call(aliases,alias_name)){continue}let currentNameAliases;if(currentCrateAliases.has(alias_name)){currentNameAliases=currentCrateAliases.get(alias_name)}else{currentNameAliases=[];currentCrateAliases.set(alias_name,currentNameAliases)}for(const local_alias of aliases[alias_name]){currentNameAliases.push(local_alias+currentIndex)}}}currentIndex+=itemTypes.length}}function onSearchSubmit(e){e.preventDefault();searchState.clearInputTimeout();search()}function putBackSearch(){const search_input=searchState.input;if(!searchState.input){return}if(search_input.value!==""&&!searchState.isDisplayed()){searchState.showResults();if(browserSupportsHistoryApi()){history.replaceState(null,"",buildUrl(search_input.value,getFilterCrates()))}document.title=searchState.title}}function registerSearchEvents(){const params=searchState.getQueryStringParams();if(searchState.input.value===""){searchState.input.value=params.search||""}const searchAfter500ms=()=>{searchState.clearInputTimeout();if(searchState.input.value.length===0){searchState.hideResults()}else{searchState.timeout=setTimeout(search,500)}};searchState.input.onkeyup=searchAfter500ms;searchState.input.oninput=searchAfter500ms;document.getElementsByClassName("search-form")[0].onsubmit=onSearchSubmit;searchState.input.onchange=e=>{if(e.target!==document.activeElement){return}searchState.clearInputTimeout();setTimeout(search,0)};searchState.input.onpaste=searchState.input.onchange;searchState.outputElement().addEventListener("keydown",e=>{if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey){return}if(e.which===38){const previous=document.activeElement.previousElementSibling;if(previous){previous.focus()}else{searchState.focus()}e.preventDefault()}else if(e.which===40){const next=document.activeElement.nextElementSibling;if(next){next.focus()}const rect=document.activeElement.getBoundingClientRect();if(window.innerHeight-rect.bottom{if(e.which===40){focusSearchResult();e.preventDefault()}});searchState.input.addEventListener("focus",()=>{putBackSearch()});searchState.input.addEventListener("blur",()=>{searchState.input.placeholder=searchState.input.origPlaceholder});if(browserSupportsHistoryApi()){const previousTitle=document.title;window.addEventListener("popstate",e=>{const params=searchState.getQueryStringParams();document.title=previousTitle;currentResults=null;if(params.search&¶ms.search.length>0){searchState.input.value=params.search;e.preventDefault();search()}else{searchState.input.value="";searchState.hideResults()}})}window.onpageshow=()=>{const qSearch=searchState.getQueryStringParams().search;if(searchState.input.value===""&&qSearch){searchState.input.value=qSearch}search()}}function updateCrate(ev){if(ev.target.value==="all crates"){const query=searchState.input.value.trim();updateSearchHistory(buildUrl(query,null))}currentResults=null;search(true)}buildIndex(rawSearchIndex);if(typeof window!=="undefined"){registerSearchEvents();if(window.searchState.getQueryStringParams().search){search()}}if(typeof exports!=="undefined"){exports.initSearch=initSearch;exports.execQuery=execQuery;exports.parseQuery=parseQuery}}if(typeof window!=="undefined"){window.initSearch=initSearch;if(window.searchIndex!==undefined){initSearch(window.searchIndex)}}else{initSearch(new Map())}})() \ No newline at end of file diff --git a/static.files/settings-4313503d2e1961c2.js b/static.files/settings-4313503d2e1961c2.js new file mode 100644 index 00000000..ab425fe4 --- /dev/null +++ b/static.files/settings-4313503d2e1961c2.js @@ -0,0 +1,17 @@ +"use strict";(function(){const isSettingsPage=window.location.pathname.endsWith("/settings.html");function changeSetting(settingName,value){if(settingName==="theme"){const useSystem=value==="system preference"?"true":"false";updateLocalStorage("use-system-theme",useSystem)}updateLocalStorage(settingName,value);switch(settingName){case"theme":case"preferred-dark-theme":case"preferred-light-theme":updateTheme();updateLightAndDark();break;case"line-numbers":if(value===true){window.rustdoc_add_line_numbers_to_examples()}else{window.rustdoc_remove_line_numbers_from_examples()}break;case"hide-sidebar":if(value===true){addClass(document.documentElement,"hide-sidebar")}else{removeClass(document.documentElement,"hide-sidebar")}break}}function showLightAndDark(){removeClass(document.getElementById("preferred-light-theme"),"hidden");removeClass(document.getElementById("preferred-dark-theme"),"hidden")}function hideLightAndDark(){addClass(document.getElementById("preferred-light-theme"),"hidden");addClass(document.getElementById("preferred-dark-theme"),"hidden")}function updateLightAndDark(){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||(useSystem===null&&getSettingValue("theme")===null)){showLightAndDark()}else{hideLightAndDark()}}function setEvents(settingsElement){updateLightAndDark();onEachLazy(settingsElement.querySelectorAll("input[type=\"checkbox\"]"),toggle=>{const settingId=toggle.id;const settingValue=getSettingValue(settingId);if(settingValue!==null){toggle.checked=settingValue==="true"}toggle.onchange=()=>{changeSetting(toggle.id,toggle.checked)}});onEachLazy(settingsElement.querySelectorAll("input[type=\"radio\"]"),elem=>{const settingId=elem.name;let settingValue=getSettingValue(settingId);if(settingId==="theme"){const useSystem=getSettingValue("use-system-theme");if(useSystem==="true"||settingValue===null){settingValue=useSystem==="false"?"light":"system preference"}}if(settingValue!==null&&settingValue!=="null"){elem.checked=settingValue===elem.value}elem.addEventListener("change",ev=>{changeSetting(ev.target.name,ev.target.value)})})}function buildSettingsPageSections(settings){let output="";for(const setting of settings){const js_data_name=setting["js_name"];const setting_name=setting["name"];if(setting["options"]!==undefined){output+=`\ +
+
${setting_name}
+
`;onEach(setting["options"],option=>{const checked=option===setting["default"]?" checked":"";const full=`${js_data_name}-${option.replace(/ /g,"-")}`;output+=`\ + `});output+=`\ +
+
`}else{const checked=setting["default"]===true?" checked":"";output+=`\ +
\ + \ +
`}}return output}function buildSettingsPage(){const theme_names=getVar("themes").split(",").filter(t=>t);theme_names.push("light","dark","ayu");const settings=[{"name":"Theme","js_name":"theme","default":"system preference","options":theme_names.concat("system preference"),},{"name":"Preferred light theme","js_name":"preferred-light-theme","default":"light","options":theme_names,},{"name":"Preferred dark theme","js_name":"preferred-dark-theme","default":"dark","options":theme_names,},{"name":"Auto-hide item contents for large items","js_name":"auto-hide-large-items","default":true,},{"name":"Auto-hide item methods' documentation","js_name":"auto-hide-method-docs","default":false,},{"name":"Auto-hide trait implementation documentation","js_name":"auto-hide-trait-implementations","default":false,},{"name":"Directly go to item in search if there is only one result","js_name":"go-to-only-result","default":false,},{"name":"Show line numbers on code examples","js_name":"line-numbers","default":false,},{"name":"Hide persistent navigation bar","js_name":"hide-sidebar","default":false,},{"name":"Disable keyboard shortcuts","js_name":"disable-shortcuts","default":false,},];const elementKind=isSettingsPage?"section":"div";const innerHTML=`
${buildSettingsPageSections(settings)}
`;const el=document.createElement(elementKind);el.id="settings";if(!isSettingsPage){el.className="popover"}el.innerHTML=innerHTML;if(isSettingsPage){document.getElementById(MAIN_ID).appendChild(el)}else{el.setAttribute("tabindex","-1");getSettingsButton().appendChild(el)}return el}const settingsMenu=buildSettingsPage();function displaySettings(){settingsMenu.style.display="";onEachLazy(settingsMenu.querySelectorAll("input[type='checkbox']"),el=>{const val=getSettingValue(el.id);const checked=val==="true";if(checked!==el.checked&&val!==null){el.checked=checked}})}function settingsBlurHandler(event){blurHandler(event,getSettingsButton(),window.hidePopoverMenus)}if(isSettingsPage){getSettingsButton().onclick=event=>{event.preventDefault()}}else{const settingsButton=getSettingsButton();const settingsMenu=document.getElementById("settings");settingsButton.onclick=event=>{if(settingsMenu.contains(event.target)){return}event.preventDefault();const shouldDisplaySettings=settingsMenu.style.display==="none";window.hideAllModals();if(shouldDisplaySettings){displaySettings()}};settingsButton.onblur=settingsBlurHandler;settingsButton.querySelector("a").onblur=settingsBlurHandler;onEachLazy(settingsMenu.querySelectorAll("input"),el=>{el.onblur=settingsBlurHandler});settingsMenu.onblur=settingsBlurHandler}setTimeout(()=>{setEvents(settingsMenu);if(!isSettingsPage){displaySettings()}removeClass(getSettingsButton(),"rotate")},0)})() \ No newline at end of file diff --git a/static.files/src-script-39ed315d46fb705f.js b/static.files/src-script-39ed315d46fb705f.js new file mode 100644 index 00000000..ef74f361 --- /dev/null +++ b/static.files/src-script-39ed315d46fb705f.js @@ -0,0 +1 @@ +"use strict";(function(){const rootPath=getVar("root-path");const NAME_OFFSET=0;const DIRS_OFFSET=1;const FILES_OFFSET=2;const RUSTDOC_MOBILE_BREAKPOINT=700;function closeSidebarIfMobile(){if(window.innerWidth{removeClass(document.documentElement,"src-sidebar-expanded");getToggleLabel().innerText=">";updateLocalStorage("source-sidebar-show","false")};window.rustdocShowSourceSidebar=()=>{addClass(document.documentElement,"src-sidebar-expanded");getToggleLabel().innerText="<";updateLocalStorage("source-sidebar-show","true")};function toggleSidebar(){const child=this.parentNode.children[0];if(child.innerText===">"){window.rustdocShowSourceSidebar()}else{window.rustdocCloseSourceSidebar()}}function createSidebarToggle(){const sidebarToggle=document.createElement("div");sidebarToggle.id="src-sidebar-toggle";const inner=document.createElement("button");if(getCurrentValue("source-sidebar-show")==="true"){inner.innerText="<"}else{inner.innerText=">"}inner.onclick=toggleSidebar;sidebarToggle.appendChild(inner);return sidebarToggle}function createSrcSidebar(){const container=document.querySelector("nav.sidebar");const sidebarToggle=createSidebarToggle();container.insertBefore(sidebarToggle,container.firstChild);const sidebar=document.createElement("div");sidebar.id="src-sidebar";let hasFoundFile=false;const title=document.createElement("div");title.className="title";title.innerText="Files";sidebar.appendChild(title);for(const[key,source]of srcIndex){source[NAME_OFFSET]=key;hasFoundFile=createDirEntry(source,sidebar,"",hasFoundFile)}container.appendChild(sidebar);const selected_elem=sidebar.getElementsByClassName("selected")[0];if(typeof selected_elem!=="undefined"){selected_elem.focus()}}function highlightSrcLines(){const match=window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);if(!match){return}let from=parseInt(match[1],10);let to=from;if(typeof match[2]!=="undefined"){to=parseInt(match[2],10)}if(to{onEachLazy(e.getElementsByTagName("a"),i_e=>{removeClass(i_e,"line-highlighted")})});for(let i=from;i<=to;++i){elem=document.getElementById(i);if(!elem){break}addClass(elem,"line-highlighted")}}const handleSrcHighlight=(function(){let prev_line_id=0;const set_fragment=name=>{const x=window.scrollX,y=window.scrollY;if(browserSupportsHistoryApi()){history.replaceState(null,null,"#"+name);highlightSrcLines()}else{location.replace("#"+name)}window.scrollTo(x,y)};return ev=>{let cur_line_id=parseInt(ev.target.id,10);if(isNaN(cur_line_id)||ev.ctrlKey||ev.altKey||ev.metaKey){return}ev.preventDefault();if(ev.shiftKey&&prev_line_id){if(prev_line_id>cur_line_id){const tmp=prev_line_id;prev_line_id=cur_line_id;cur_line_id=tmp}set_fragment(prev_line_id+"-"+cur_line_id)}else{prev_line_id=cur_line_id;set_fragment(cur_line_id)}}}());window.addEventListener("hashchange",highlightSrcLines);onEachLazy(document.getElementsByClassName("src-line-numbers"),el=>{el.addEventListener("click",handleSrcHighlight)});highlightSrcLines();window.createSrcSidebar=createSrcSidebar})() \ No newline at end of file diff --git a/static.files/storage-f2adc0d6ca4d09fb.js b/static.files/storage-f2adc0d6ca4d09fb.js new file mode 100644 index 00000000..17233608 --- /dev/null +++ b/static.files/storage-f2adc0d6ca4d09fb.js @@ -0,0 +1 @@ +"use strict";const builtinThemes=["light","dark","ayu"];const darkThemes=["dark","ayu"];window.currentTheme=document.getElementById("themeStyle");const settingsDataset=(function(){const settingsElement=document.getElementById("default-settings");return settingsElement&&settingsElement.dataset?settingsElement.dataset:null})();function getSettingValue(settingName){const current=getCurrentValue(settingName);if(current===null&&settingsDataset!==null){const def=settingsDataset[settingName.replace(/-/g,"_")];if(def!==undefined){return def}}return current}const localStoredTheme=getSettingValue("theme");function hasClass(elem,className){return elem&&elem.classList&&elem.classList.contains(className)}function addClass(elem,className){if(elem&&elem.classList){elem.classList.add(className)}}function removeClass(elem,className){if(elem&&elem.classList){elem.classList.remove(className)}}function onEach(arr,func){for(const elem of arr){if(func(elem)){return true}}return false}function onEachLazy(lazyArray,func){return onEach(Array.prototype.slice.call(lazyArray),func)}function updateLocalStorage(name,value){try{window.localStorage.setItem("rustdoc-"+name,value)}catch(e){}}function getCurrentValue(name){try{return window.localStorage.getItem("rustdoc-"+name)}catch(e){return null}}const getVar=(function getVar(name){const el=document.querySelector("head > meta[name='rustdoc-vars']");return el?el.attributes["data-"+name].value:null});function switchTheme(newThemeName,saveTheme){if(saveTheme){updateLocalStorage("theme",newThemeName)}document.documentElement.setAttribute("data-theme",newThemeName);if(builtinThemes.indexOf(newThemeName)!==-1){if(window.currentTheme){window.currentTheme.parentNode.removeChild(window.currentTheme);window.currentTheme=null}}else{const newHref=getVar("root-path")+newThemeName+getVar("resource-suffix")+".css";if(!window.currentTheme){if(document.readyState==="loading"){document.write(``);window.currentTheme=document.getElementById("themeStyle")}else{window.currentTheme=document.createElement("link");window.currentTheme.rel="stylesheet";window.currentTheme.id="themeStyle";window.currentTheme.href=newHref;document.documentElement.appendChild(window.currentTheme)}}else if(newHref!==window.currentTheme.href){window.currentTheme.href=newHref}}}const updateTheme=(function(){const mql=window.matchMedia("(prefers-color-scheme: dark)");function updateTheme(){if(getSettingValue("use-system-theme")!=="false"){const lightTheme=getSettingValue("preferred-light-theme")||"light";const darkTheme=getSettingValue("preferred-dark-theme")||"dark";updateLocalStorage("use-system-theme","true");switchTheme(mql.matches?darkTheme:lightTheme,true)}else{switchTheme(getSettingValue("theme"),false)}}mql.addEventListener("change",updateTheme);return updateTheme})();if(getSettingValue("use-system-theme")!=="false"&&window.matchMedia){if(getSettingValue("use-system-theme")===null&&getSettingValue("preferred-dark-theme")===null&&darkThemes.indexOf(localStoredTheme)>=0){updateLocalStorage("preferred-dark-theme",localStoredTheme)}}updateTheme();if(getSettingValue("source-sidebar-show")==="true"){addClass(document.documentElement,"src-sidebar-expanded")}if(getSettingValue("hide-sidebar")==="true"){addClass(document.documentElement,"hide-sidebar")}function updateSidebarWidth(){const desktopSidebarWidth=getSettingValue("desktop-sidebar-width");if(desktopSidebarWidth&&desktopSidebarWidth!=="null"){document.documentElement.style.setProperty("--desktop-sidebar-width",desktopSidebarWidth+"px")}const srcSidebarWidth=getSettingValue("src-sidebar-width");if(srcSidebarWidth&&srcSidebarWidth!=="null"){document.documentElement.style.setProperty("--src-sidebar-width",srcSidebarWidth+"px")}}updateSidebarWidth();window.addEventListener("pageshow",ev=>{if(ev.persisted){setTimeout(updateTheme,0);setTimeout(updateSidebarWidth,0)}}) \ No newline at end of file diff --git a/static.files/wheel-7b819b6101059cd0.svg b/static.files/wheel-7b819b6101059cd0.svg new file mode 100644 index 00000000..83c07f63 --- /dev/null +++ b/static.files/wheel-7b819b6101059cd0.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/trait.impl/bincode/de/trait.BorrowDecode.js b/trait.impl/bincode/de/trait.BorrowDecode.js new file mode 100644 index 00000000..02155036 --- /dev/null +++ b/trait.impl/bincode/de/trait.BorrowDecode.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl<'__de> BorrowDecode<'__de> for Addr"]], +"karyon_p2p":[["impl<'__de> BorrowDecode<'__de> for ShutdownMsg"],["impl<'__de> BorrowDecode<'__de> for Entry"],["impl<'__de> BorrowDecode<'__de> for PingMsg"],["impl<'__de> BorrowDecode<'__de> for PingMsg"],["impl<'__de> BorrowDecode<'__de> for PeersMsg"],["impl<'__de> BorrowDecode<'__de> for PeerMsg"],["impl<'__de> BorrowDecode<'__de> for VersionInt"],["impl<'__de> BorrowDecode<'__de> for FindPeerMsg"],["impl<'__de> BorrowDecode<'__de> for PeerID"],["impl<'__de> BorrowDecode<'__de> for PongMsg"],["impl<'__de> BorrowDecode<'__de> for NetMsgHeader"],["impl<'__de> BorrowDecode<'__de> for NetMsg"],["impl<'__de> BorrowDecode<'__de> for ProtocolMsg"],["impl<'__de> BorrowDecode<'__de> for PingProtocolMsg"],["impl<'__de> BorrowDecode<'__de> for PongMsg"],["impl<'__de> BorrowDecode<'__de> for NetMsgCmd"],["impl<'__de> BorrowDecode<'__de> for VerAckMsg"],["impl<'__de> BorrowDecode<'__de> for VerMsg"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/bincode/de/trait.Decode.js b/trait.impl/bincode/de/trait.Decode.js new file mode 100644 index 00000000..8116799c --- /dev/null +++ b/trait.impl/bincode/de/trait.Decode.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl Decode for Addr"]], +"karyon_p2p":[["impl Decode for PingMsg"],["impl Decode for VerAckMsg"],["impl Decode for PeersMsg"],["impl Decode for PingProtocolMsg"],["impl Decode for PongMsg"],["impl Decode for NetMsgCmd"],["impl Decode for ProtocolMsg"],["impl Decode for PongMsg"],["impl Decode for VersionInt"],["impl Decode for NetMsgHeader"],["impl Decode for PeerID"],["impl Decode for Entry"],["impl Decode for ShutdownMsg"],["impl Decode for PeerMsg"],["impl Decode for FindPeerMsg"],["impl Decode for NetMsg"],["impl Decode for PingMsg"],["impl Decode for VerMsg"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/bincode/enc/trait.Encode.js b/trait.impl/bincode/enc/trait.Encode.js new file mode 100644 index 00000000..30144f38 --- /dev/null +++ b/trait.impl/bincode/enc/trait.Encode.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl Encode for Addr"]], +"karyon_p2p":[["impl Encode for VerAckMsg"],["impl Encode for Entry"],["impl Encode for PeerMsg"],["impl Encode for PongMsg"],["impl Encode for NetMsgHeader"],["impl Encode for PingMsg"],["impl Encode for PongMsg"],["impl Encode for ShutdownMsg"],["impl Encode for PeerID"],["impl Encode for PeersMsg"],["impl Encode for PingMsg"],["impl Encode for VersionInt"],["impl Encode for PingProtocolMsg"],["impl Encode for ProtocolMsg"],["impl Encode for VerMsg"],["impl Encode for NetMsg"],["impl Encode for NetMsgCmd"],["impl Encode for FindPeerMsg"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/clone/trait.Clone.js b/trait.impl/core/clone/trait.Clone.js new file mode 100644 index 00000000..ddd7178e --- /dev/null +++ b/trait.impl/core/clone/trait.Clone.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Clone for Event"],["impl Clone for Ed25519KeyPair"],["impl Clone for KeyPair"]], +"karyon_jsonrpc":[["impl Clone for CodecConfig"]], +"karyon_net":[["impl Clone for Endpoint"],["impl Clone for Addr"]], +"karyon_p2p":[["impl Clone for ConnDirection"],["impl Clone for Version"],["impl Clone for PeerMsg"],["impl Clone for PingMsg"],["impl Clone for ShutdownMsg"],["impl Clone for Entry"],["impl Clone for ConnEvent"],["impl Clone for NetMsgHeader"],["impl Clone for PeerPoolEvent"],["impl Clone for VersionInt"],["impl Clone for ProtocolMsg"],["impl Clone for PeerID"],["impl Clone for Bucket"],["impl Clone for ProtocolEvent"],["impl Clone for MonitorEvent"],["impl Clone for NetMsg"],["impl Clone for DiscoveryEvent"],["impl Clone for VerAckMsg"],["impl Clone for PingMsg"],["impl Clone for VerMsg"],["impl Clone for PingProtocolMsg"],["impl Clone for BucketEntry"],["impl Clone for NetMsgCmd"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.Eq.js b/trait.impl/core/cmp/trait.Eq.js new file mode 100644 index 00000000..7f215d39 --- /dev/null +++ b/trait.impl/core/cmp/trait.Eq.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl Eq for Addr"],["impl Eq for Endpoint"]], +"karyon_p2p":[["impl Eq for PeerMsg"],["impl Eq for PeerID"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/cmp/trait.PartialEq.js b/trait.impl/core/cmp/trait.PartialEq.js new file mode 100644 index 00000000..b9e7472a --- /dev/null +++ b/trait.impl/core/cmp/trait.PartialEq.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl PartialEq for Addr"],["impl PartialEq for Endpoint"]], +"karyon_p2p":[["impl PartialEq for PeerID"],["impl PartialEq for PeerMsg"],["impl PartialEq for Entry"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/convert/trait.From.js b/trait.impl/core/convert/trait.From.js new file mode 100644 index 00000000..0c4d5ca2 --- /dev/null +++ b/trait.impl/core/convert/trait.From.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl From<Error> for Error"],["impl From<DecodeError> for Error"],["impl From<EncodeError> for Error"],["impl From<Error> for Error"],["impl From<RecvError> for Error"],["impl<T> From<SendError<T>> for Error"]], +"karyon_jsonrpc":[["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<Error> for Error"]], +"karyon_net":[["impl From<Error> for Error"],["impl From<UnixListener> for Box<dyn ConnListener>"],["impl<T> From<SendError<T>> for Error"],["impl From<TcpStream> for Box<dyn Connection>"],["impl From<TlsListener> for Box<dyn ConnListener>"],["impl From<Error> for Error"],["impl From<RecvError> for Error"],["impl From<UdpSocket> for Box<dyn Connection>"],["impl From<Error> for Error"],["impl From<UnixStream> for Box<dyn Connection>"],["impl From<TlsStream<TcpStream>> for Box<dyn Connection>"],["impl From<InvalidDnsNameError> for Error"],["impl From<TcpListener> for Box<dyn ConnListener>"]], +"karyon_p2p":[["impl From<ConnEvent> for MonitorEvent"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<InvalidDnsNameError> for Error"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<ParseFloatError> for Error"],["impl From<ParseIntError> for Error"],["impl From<PeerPoolEvent> for MonitorEvent"],["impl From<VersionInt> for Version"],["impl From<Error> for Error"],["impl From<Entry> for PeerMsg"],["impl From<X509Error> for Error"],["impl From<RecvError> for Error"],["impl From<PeerMsg> for Entry"],["impl From<ASN1Error> for Error"],["impl From<[u8; 32]> for PeerID"],["impl<T> From<SendError<T>> for Error"],["impl From<Error> for Error"],["impl From<DiscoveryEvent> for MonitorEvent"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/convert/trait.TryFrom.js b/trait.impl/core/convert/trait.TryFrom.js new file mode 100644 index 00000000..68d5e4d4 --- /dev/null +++ b/trait.impl/core/convert/trait.TryFrom.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl TryFrom<Endpoint> for PathBuf"],["impl TryFrom<Endpoint> for SocketAddr"],["impl TryFrom<Endpoint> for SocketAddr"],["impl TryFrom<Addr> for IpAddr"]], +"karyon_p2p":[["impl TryFrom<PublicKey> for PeerID"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/default/trait.Default.js b/trait.impl/core/default/trait.Default.js new file mode 100644 index 00000000..283bc338 --- /dev/null +++ b/trait.impl/core/default/trait.Default.js @@ -0,0 +1,5 @@ +(function() {var implementors = { +"karyon_core":[["impl Default for CondWait"],["impl Default for CondVar"]], +"karyon_jsonrpc":[["impl Default for ServerConfig"],["impl Default for CodecConfig"],["impl Default for ClientConfig"]], +"karyon_p2p":[["impl Default for Config"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/error/trait.Error.js b/trait.impl/core/error/trait.Error.js new file mode 100644 index 00000000..76d86a22 --- /dev/null +++ b/trait.impl/core/error/trait.Error.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Error for Error"]], +"karyon_jsonrpc":[["impl Error for Error"]], +"karyon_net":[["impl Error for Error"]], +"karyon_p2p":[["impl Error for Error"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Debug.js b/trait.impl/core/fmt/trait.Debug.js new file mode 100644 index 00000000..eee13a6c --- /dev/null +++ b/trait.impl/core/fmt/trait.Debug.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl<T: Debug> Debug for TaskResult<T>"],["impl Debug for Ed25519PublicKey"],["impl Debug for Error"],["impl Debug for Event"],["impl<T1: Debug, T2: Debug> Debug for Either<T1, T2>"],["impl Debug for PublicKey"],["impl<F1: Debug, F2: Debug> Debug for Select<F1, F2>"]], +"karyon_jsonrpc":[["impl Debug for Response"],["impl Debug for Request"],["impl Debug for Error"],["impl Debug for Notification"],["impl Debug for Error"]], +"karyon_net":[["impl Debug for Endpoint"],["impl Debug for Addr"],["impl Debug for Error"]], +"karyon_p2p":[["impl Debug for ProtocolEvent"],["impl Debug for CliCertVerifier"],["impl Debug for PeerMsg"],["impl Debug for PeersMsg"],["impl Debug for PingProtocolMsg"],["impl Debug for AddEntryResult"],["impl Debug for ConnEvent"],["impl Debug for Version"],["impl Debug for PeerID"],["impl Debug for PongMsg"],["impl Debug for ProtocolMsg"],["impl Debug for NetMsgCmd"],["impl Debug for SrvrCertVerifier"],["impl Debug for PeerPoolEvent"],["impl Debug for DiscoveryEvent"],["impl Debug for PingMsg"],["impl Debug for BucketEntry"],["impl Debug for NetMsgHeader"],["impl Debug for ConnDirection"],["impl Debug for Entry"],["impl Debug for PongMsg"],["impl Debug for Bucket"],["impl Debug for FindPeerMsg"],["impl Debug for ShutdownMsg"],["impl Debug for VerMsg"],["impl Debug for NetMsg"],["impl Debug for Error"],["impl Debug for VersionInt"],["impl Debug for PingMsg"],["impl Debug for MonitorEvent"],["impl Debug for RoutingTable"],["impl Debug for VerAckMsg"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/fmt/trait.Display.js b/trait.impl/core/fmt/trait.Display.js new file mode 100644 index 00000000..867c806f --- /dev/null +++ b/trait.impl/core/fmt/trait.Display.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Display for Event"],["impl<T: Debug> Display for TaskResult<T>"],["impl Display for Error"]], +"karyon_jsonrpc":[["impl Display for Error"],["impl Display for Response"],["impl Display for Error"],["impl Display for Notification"],["impl Display for Request"]], +"karyon_net":[["impl Display for Error"],["impl Display for Addr"],["impl Display for Endpoint"]], +"karyon_p2p":[["impl Display for ConnDirection"],["impl Display for MonitorEvent"],["impl Display for DiscoveryEvent"],["impl Display for ConnEvent"],["impl Display for PeerID"],["impl Display for Error"],["impl Display for PeerPoolEvent"],["impl Display for VersionInt"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/future/future/trait.Future.js b/trait.impl/core/future/future/trait.Future.js new file mode 100644 index 00000000..acdda03c --- /dev/null +++ b/trait.impl/core/future/future/trait.Future.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_core":[["impl<T1, T2, F1, F2> Future for Select<F1, F2>
where\n F1: Future<Output = T1>,\n F2: Future<Output = T2>,
"],["impl<'a, T> Future for CondVarAwait<'a, T>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/hash/trait.Hash.js b/trait.impl/core/hash/trait.Hash.js new file mode 100644 index 00000000..c0ea584f --- /dev/null +++ b/trait.impl/core/hash/trait.Hash.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl Hash for Addr"],["impl Hash for Endpoint"]], +"karyon_p2p":[["impl Hash for PeerID"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Freeze.js b/trait.impl/core/marker/trait.Freeze.js new file mode 100644 index 00000000..1ac98434 --- /dev/null +++ b/trait.impl/core/marker/trait.Freeze.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl !Freeze for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl !Freeze for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> Freeze for CondVarAwait<'a, T>",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl Freeze for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl !Freeze for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<F1, F2> Freeze for Select<F1, F2>
where\n F1: Freeze,\n F2: Freeze,
",1,["karyon_core::async_util::select::Select"]],["impl<T1, T2> Freeze for Either<T1, T2>
where\n T1: Freeze,\n T2: Freeze,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> !Freeze for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> Freeze for TaskResult<T>
where\n T: Freeze,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl Freeze for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl Freeze for Error",1,["karyon_core::error::Error"]],["impl<T> !Freeze for EventSys<T>",1,["karyon_core::event::EventSys"]],["impl<T, E> Freeze for EventListener<T, E>
where\n T: Freeze,
",1,["karyon_core::event::EventListener"]],["impl Freeze for Event",1,["karyon_core::event::Event"]],["impl<T> !Freeze for Publisher<T>",1,["karyon_core::pubsub::Publisher"]],["impl<T> Freeze for Subscription<T>",1,["karyon_core::pubsub::Subscription"]],["impl Freeze for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl Freeze for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl Freeze for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl Freeze for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl Freeze for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl Freeze for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]]], +"karyon_jsonrpc":[["impl Freeze for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl Freeze for Client",1,["karyon_jsonrpc::client::Client"]],["impl Freeze for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl Freeze for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl Freeze for Error",1,["karyon_jsonrpc::error::Error"]],["impl Freeze for Request",1,["karyon_jsonrpc::message::Request"]],["impl Freeze for Response",1,["karyon_jsonrpc::message::Response"]],["impl Freeze for Error",1,["karyon_jsonrpc::message::Error"]],["impl Freeze for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl Freeze for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> !Freeze for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl Freeze for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl Freeze for Addr",1,["karyon_net::endpoint::Addr"]],["impl Freeze for Error",1,["karyon_net::error::Error"]],["impl !Freeze for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl !Freeze for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl Freeze for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl Freeze for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl !Freeze for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl Freeze for Backend",1,["karyon_p2p::backend::Backend"]],["impl Freeze for Codec",1,["karyon_p2p::codec::Codec"]],["impl Freeze for Config",1,["karyon_p2p::config::Config"]],["impl Freeze for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl Freeze for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl !Freeze for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl !Freeze for Connector",1,["karyon_p2p::connector::Connector"]],["impl !Freeze for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl Freeze for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl Freeze for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl !Freeze for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl !Freeze for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl Freeze for Error",1,["karyon_p2p::error::Error"]],["impl !Freeze for Listener",1,["karyon_p2p::listener::Listener"]],["impl Freeze for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl Freeze for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl Freeze for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl Freeze for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl Freeze for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl Freeze for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl Freeze for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl Freeze for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl Freeze for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl Freeze for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl Freeze for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl Freeze for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl Freeze for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl !Freeze for Peer",1,["karyon_p2p::peer::Peer"]],["impl !Freeze for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl Freeze for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl !Freeze for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl Freeze for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl Freeze for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl Freeze for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl Freeze for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl Freeze for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl !Freeze for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl Freeze for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl Freeze for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl Freeze for Version",1,["karyon_p2p::version::Version"]],["impl Freeze for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl Freeze for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl Freeze for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl Freeze for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl Freeze for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl Freeze for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl Freeze for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Send.js b/trait.impl/core/marker/trait.Send.js new file mode 100644 index 00000000..b7c22bab --- /dev/null +++ b/trait.impl/core/marker/trait.Send.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Send for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl Send for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> Send for CondVarAwait<'a, T>
where\n T: Send,
",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl Send for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl Send for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<F1, F2> Send for Select<F1, F2>
where\n F1: Send,\n F2: Send,
",1,["karyon_core::async_util::select::Select"]],["impl<T1, T2> Send for Either<T1, T2>
where\n T1: Send,\n T2: Send,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> Send for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> Send for TaskResult<T>
where\n T: Send,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl Send for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl Send for Error",1,["karyon_core::error::Error"]],["impl<T> Send for EventSys<T>
where\n T: Send,
",1,["karyon_core::event::EventSys"]],["impl<T, E> Send for EventListener<T, E>
where\n E: Send,\n T: Send,
",1,["karyon_core::event::EventListener"]],["impl Send for Event",1,["karyon_core::event::Event"]],["impl<T> Send for Publisher<T>
where\n T: Send,
",1,["karyon_core::pubsub::Publisher"]],["impl<T> Send for Subscription<T>
where\n T: Send,
",1,["karyon_core::pubsub::Subscription"]],["impl Send for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl Send for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl Send for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl Send for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl Send for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl Send for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]]], +"karyon_jsonrpc":[["impl Send for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl Send for Client",1,["karyon_jsonrpc::client::Client"]],["impl Send for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl Send for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl Send for Error",1,["karyon_jsonrpc::error::Error"]],["impl Send for Request",1,["karyon_jsonrpc::message::Request"]],["impl Send for Response",1,["karyon_jsonrpc::message::Response"]],["impl Send for Error",1,["karyon_jsonrpc::message::Error"]],["impl Send for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl Send for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> Send for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl Send for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl Send for Addr",1,["karyon_net::endpoint::Addr"]],["impl Send for Error",1,["karyon_net::error::Error"]],["impl Send for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl Send for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl Send for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl Send for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl Send for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl Send for Backend",1,["karyon_p2p::backend::Backend"]],["impl Send for Codec",1,["karyon_p2p::codec::Codec"]],["impl Send for Config",1,["karyon_p2p::config::Config"]],["impl Send for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl Send for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl Send for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl Send for Connector",1,["karyon_p2p::connector::Connector"]],["impl Send for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl Send for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl Send for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl Send for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl Send for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl Send for Error",1,["karyon_p2p::error::Error"]],["impl Send for Listener",1,["karyon_p2p::listener::Listener"]],["impl Send for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl Send for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl Send for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl Send for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl Send for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl Send for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl Send for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl Send for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl Send for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl Send for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl Send for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl Send for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl Send for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl Send for Peer",1,["karyon_p2p::peer::Peer"]],["impl Send for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl Send for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl Send for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl Send for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl Send for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl Send for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl Send for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl Send for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl Send for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl Send for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl Send for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl Send for Version",1,["karyon_p2p::version::Version"]],["impl Send for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl Send for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl Send for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl Send for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl Send for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl Send for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl Send for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.StructuralEq.js b/trait.impl/core/marker/trait.StructuralEq.js new file mode 100644 index 00000000..d4be072b --- /dev/null +++ b/trait.impl/core/marker/trait.StructuralEq.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl StructuralEq for Addr"],["impl StructuralEq for Endpoint"]], +"karyon_p2p":[["impl StructuralEq for PeerMsg"],["impl StructuralEq for PeerID"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.StructuralPartialEq.js b/trait.impl/core/marker/trait.StructuralPartialEq.js new file mode 100644 index 00000000..a2aa7441 --- /dev/null +++ b/trait.impl/core/marker/trait.StructuralPartialEq.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl StructuralPartialEq for Addr"],["impl StructuralPartialEq for Endpoint"]], +"karyon_p2p":[["impl StructuralPartialEq for PeerMsg"],["impl StructuralPartialEq for PeerID"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Sync.js b/trait.impl/core/marker/trait.Sync.js new file mode 100644 index 00000000..0ee22241 --- /dev/null +++ b/trait.impl/core/marker/trait.Sync.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Sync for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl Sync for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> Sync for CondVarAwait<'a, T>
where\n T: Sync,
",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl Sync for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl Sync for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<F1, F2> Sync for Select<F1, F2>
where\n F1: Sync,\n F2: Sync,
",1,["karyon_core::async_util::select::Select"]],["impl<T1, T2> Sync for Either<T1, T2>
where\n T1: Sync,\n T2: Sync,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> Sync for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> Sync for TaskResult<T>
where\n T: Sync,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl Sync for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl Sync for Error",1,["karyon_core::error::Error"]],["impl<T> Sync for EventSys<T>
where\n T: Send,
",1,["karyon_core::event::EventSys"]],["impl<T, E> Sync for EventListener<T, E>
where\n E: Sync,\n T: Send + Sync,
",1,["karyon_core::event::EventListener"]],["impl Sync for Event",1,["karyon_core::event::Event"]],["impl<T> Sync for Publisher<T>
where\n T: Send,
",1,["karyon_core::pubsub::Publisher"]],["impl<T> Sync for Subscription<T>
where\n T: Send,
",1,["karyon_core::pubsub::Subscription"]],["impl Sync for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl Sync for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl Sync for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl Sync for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl Sync for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl Sync for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]]], +"karyon_jsonrpc":[["impl Sync for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl Sync for Client",1,["karyon_jsonrpc::client::Client"]],["impl Sync for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl Sync for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl Sync for Error",1,["karyon_jsonrpc::error::Error"]],["impl Sync for Request",1,["karyon_jsonrpc::message::Request"]],["impl Sync for Response",1,["karyon_jsonrpc::message::Response"]],["impl Sync for Error",1,["karyon_jsonrpc::message::Error"]],["impl Sync for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl Sync for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> Sync for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl Sync for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl Sync for Addr",1,["karyon_net::endpoint::Addr"]],["impl Sync for Error",1,["karyon_net::error::Error"]],["impl Sync for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl Sync for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl Sync for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl Sync for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl Sync for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl Sync for Backend",1,["karyon_p2p::backend::Backend"]],["impl Sync for Codec",1,["karyon_p2p::codec::Codec"]],["impl Sync for Config",1,["karyon_p2p::config::Config"]],["impl Sync for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl Sync for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl Sync for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl Sync for Connector",1,["karyon_p2p::connector::Connector"]],["impl Sync for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl Sync for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl Sync for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl Sync for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl Sync for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl Sync for Error",1,["karyon_p2p::error::Error"]],["impl Sync for Listener",1,["karyon_p2p::listener::Listener"]],["impl Sync for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl Sync for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl Sync for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl Sync for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl Sync for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl Sync for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl Sync for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl Sync for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl Sync for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl Sync for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl Sync for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl Sync for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl Sync for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl Sync for Peer",1,["karyon_p2p::peer::Peer"]],["impl Sync for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl Sync for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl Sync for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl Sync for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl Sync for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl Sync for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl Sync for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl Sync for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl Sync for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl Sync for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl Sync for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl Sync for Version",1,["karyon_p2p::version::Version"]],["impl Sync for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl Sync for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl Sync for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl Sync for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl Sync for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl Sync for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl Sync for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/marker/trait.Unpin.js b/trait.impl/core/marker/trait.Unpin.js new file mode 100644 index 00000000..995be437 --- /dev/null +++ b/trait.impl/core/marker/trait.Unpin.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl Unpin for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl Unpin for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> Unpin for CondVarAwait<'a, T>",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl Unpin for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl Unpin for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<T1, T2> Unpin for Either<T1, T2>
where\n T1: Unpin,\n T2: Unpin,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> Unpin for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> Unpin for TaskResult<T>
where\n T: Unpin,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl Unpin for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl Unpin for Error",1,["karyon_core::error::Error"]],["impl<T> Unpin for EventSys<T>
where\n T: Unpin,
",1,["karyon_core::event::EventSys"]],["impl<T, E> !Unpin for EventListener<T, E>",1,["karyon_core::event::EventListener"]],["impl Unpin for Event",1,["karyon_core::event::Event"]],["impl<T> Unpin for Publisher<T>",1,["karyon_core::pubsub::Publisher"]],["impl<T> !Unpin for Subscription<T>",1,["karyon_core::pubsub::Subscription"]],["impl Unpin for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl Unpin for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl Unpin for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl Unpin for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl Unpin for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl Unpin for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]],["impl<'__pin, F1, F2> Unpin for Select<F1, F2>
where\n __Origin<'__pin, F1, F2>: Unpin,
"]], +"karyon_jsonrpc":[["impl Unpin for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl Unpin for Client",1,["karyon_jsonrpc::client::Client"]],["impl Unpin for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl Unpin for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl Unpin for Error",1,["karyon_jsonrpc::error::Error"]],["impl Unpin for Request",1,["karyon_jsonrpc::message::Request"]],["impl Unpin for Response",1,["karyon_jsonrpc::message::Response"]],["impl Unpin for Error",1,["karyon_jsonrpc::message::Error"]],["impl Unpin for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl Unpin for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> Unpin for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl Unpin for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl Unpin for Addr",1,["karyon_net::endpoint::Addr"]],["impl Unpin for Error",1,["karyon_net::error::Error"]],["impl Unpin for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl Unpin for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl Unpin for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl Unpin for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl Unpin for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl Unpin for Backend",1,["karyon_p2p::backend::Backend"]],["impl Unpin for Codec",1,["karyon_p2p::codec::Codec"]],["impl Unpin for Config",1,["karyon_p2p::config::Config"]],["impl Unpin for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl Unpin for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl Unpin for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl Unpin for Connector",1,["karyon_p2p::connector::Connector"]],["impl Unpin for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl Unpin for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl Unpin for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl Unpin for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl Unpin for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl Unpin for Error",1,["karyon_p2p::error::Error"]],["impl Unpin for Listener",1,["karyon_p2p::listener::Listener"]],["impl Unpin for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl Unpin for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl Unpin for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl Unpin for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl Unpin for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl Unpin for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl Unpin for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl Unpin for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl Unpin for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl Unpin for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl Unpin for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl Unpin for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl Unpin for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl !Unpin for Peer",1,["karyon_p2p::peer::Peer"]],["impl Unpin for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl Unpin for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl Unpin for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl Unpin for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl Unpin for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl Unpin for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl Unpin for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl Unpin for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl Unpin for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl Unpin for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl Unpin for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl Unpin for Version",1,["karyon_p2p::version::Version"]],["impl Unpin for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl Unpin for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl Unpin for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl Unpin for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl Unpin for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl Unpin for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl Unpin for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/ops/drop/trait.Drop.js b/trait.impl/core/ops/drop/trait.Drop.js new file mode 100644 index 00000000..84e7d56a --- /dev/null +++ b/trait.impl/core/ops/drop/trait.Drop.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_core":[["impl<'a, T> Drop for CondVarAwait<'a, T>"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js new file mode 100644 index 00000000..1556a0c1 --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl RefUnwindSafe for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl RefUnwindSafe for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> !RefUnwindSafe for CondVarAwait<'a, T>",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl RefUnwindSafe for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl !RefUnwindSafe for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<F1, F2> RefUnwindSafe for Select<F1, F2>
where\n F1: RefUnwindSafe,\n F2: RefUnwindSafe,
",1,["karyon_core::async_util::select::Select"]],["impl<T1, T2> RefUnwindSafe for Either<T1, T2>
where\n T1: RefUnwindSafe,\n T2: RefUnwindSafe,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> !RefUnwindSafe for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> RefUnwindSafe for TaskResult<T>
where\n T: RefUnwindSafe,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl !RefUnwindSafe for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl !RefUnwindSafe for Error",1,["karyon_core::error::Error"]],["impl<T> !RefUnwindSafe for EventSys<T>",1,["karyon_core::event::EventSys"]],["impl<T, E> !RefUnwindSafe for EventListener<T, E>",1,["karyon_core::event::EventListener"]],["impl !RefUnwindSafe for Event",1,["karyon_core::event::Event"]],["impl<T> !RefUnwindSafe for Publisher<T>",1,["karyon_core::pubsub::Publisher"]],["impl<T> !RefUnwindSafe for Subscription<T>",1,["karyon_core::pubsub::Subscription"]],["impl RefUnwindSafe for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl RefUnwindSafe for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl RefUnwindSafe for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl RefUnwindSafe for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl RefUnwindSafe for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl RefUnwindSafe for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]]], +"karyon_jsonrpc":[["impl RefUnwindSafe for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl !RefUnwindSafe for Client",1,["karyon_jsonrpc::client::Client"]],["impl RefUnwindSafe for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl !RefUnwindSafe for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl !RefUnwindSafe for Error",1,["karyon_jsonrpc::error::Error"]],["impl RefUnwindSafe for Request",1,["karyon_jsonrpc::message::Request"]],["impl RefUnwindSafe for Response",1,["karyon_jsonrpc::message::Response"]],["impl RefUnwindSafe for Error",1,["karyon_jsonrpc::message::Error"]],["impl RefUnwindSafe for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl RefUnwindSafe for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> !RefUnwindSafe for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl RefUnwindSafe for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl RefUnwindSafe for Addr",1,["karyon_net::endpoint::Addr"]],["impl !RefUnwindSafe for Error",1,["karyon_net::error::Error"]],["impl !RefUnwindSafe for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl !RefUnwindSafe for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl !RefUnwindSafe for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl RefUnwindSafe for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl !RefUnwindSafe for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl !RefUnwindSafe for Backend",1,["karyon_p2p::backend::Backend"]],["impl !RefUnwindSafe for Codec",1,["karyon_p2p::codec::Codec"]],["impl RefUnwindSafe for Config",1,["karyon_p2p::config::Config"]],["impl RefUnwindSafe for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl !RefUnwindSafe for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl !RefUnwindSafe for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl !RefUnwindSafe for Connector",1,["karyon_p2p::connector::Connector"]],["impl !RefUnwindSafe for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl RefUnwindSafe for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl RefUnwindSafe for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl !RefUnwindSafe for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl !RefUnwindSafe for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl !RefUnwindSafe for Error",1,["karyon_p2p::error::Error"]],["impl !RefUnwindSafe for Listener",1,["karyon_p2p::listener::Listener"]],["impl RefUnwindSafe for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl RefUnwindSafe for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl RefUnwindSafe for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl RefUnwindSafe for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl RefUnwindSafe for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl RefUnwindSafe for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl RefUnwindSafe for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl RefUnwindSafe for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl RefUnwindSafe for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl RefUnwindSafe for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl RefUnwindSafe for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl RefUnwindSafe for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl RefUnwindSafe for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl !RefUnwindSafe for Peer",1,["karyon_p2p::peer::Peer"]],["impl !RefUnwindSafe for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl RefUnwindSafe for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl !RefUnwindSafe for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl RefUnwindSafe for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl RefUnwindSafe for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl RefUnwindSafe for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl RefUnwindSafe for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl RefUnwindSafe for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl !RefUnwindSafe for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl RefUnwindSafe for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl RefUnwindSafe for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl RefUnwindSafe for Version",1,["karyon_p2p::version::Version"]],["impl RefUnwindSafe for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl !RefUnwindSafe for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl RefUnwindSafe for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl RefUnwindSafe for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl RefUnwindSafe for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl RefUnwindSafe for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl RefUnwindSafe for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js new file mode 100644 index 00000000..647ceb7f --- /dev/null +++ b/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js @@ -0,0 +1,6 @@ +(function() {var implementors = { +"karyon_core":[["impl UnwindSafe for Backoff",1,["karyon_core::async_util::backoff::Backoff"]],["impl UnwindSafe for CondVar",1,["karyon_core::async_util::condvar::CondVar"]],["impl<'a, T> !UnwindSafe for CondVarAwait<'a, T>",1,["karyon_core::async_util::condvar::CondVarAwait"]],["impl UnwindSafe for Wakers",1,["karyon_core::async_util::condvar::Wakers"]],["impl UnwindSafe for CondWait",1,["karyon_core::async_util::condwait::CondWait"]],["impl<F1, F2> UnwindSafe for Select<F1, F2>
where\n F1: UnwindSafe,\n F2: UnwindSafe,
",1,["karyon_core::async_util::select::Select"]],["impl<T1, T2> UnwindSafe for Either<T1, T2>
where\n T1: UnwindSafe,\n T2: UnwindSafe,
",1,["karyon_core::async_util::select::Either"]],["impl<'a> !UnwindSafe for TaskGroup<'a>",1,["karyon_core::async_util::task_group::TaskGroup"]],["impl<T> UnwindSafe for TaskResult<T>
where\n T: UnwindSafe,
",1,["karyon_core::async_util::task_group::TaskResult"]],["impl !UnwindSafe for TaskHandler",1,["karyon_core::async_util::task_group::TaskHandler"]],["impl !UnwindSafe for Error",1,["karyon_core::error::Error"]],["impl<T> UnwindSafe for EventSys<T>
where\n T: UnwindSafe,
",1,["karyon_core::event::EventSys"]],["impl<T, E> !UnwindSafe for EventListener<T, E>",1,["karyon_core::event::EventListener"]],["impl !UnwindSafe for Event",1,["karyon_core::event::Event"]],["impl<T> UnwindSafe for Publisher<T>",1,["karyon_core::pubsub::Publisher"]],["impl<T> !UnwindSafe for Subscription<T>",1,["karyon_core::pubsub::Subscription"]],["impl UnwindSafe for KeyPairType",1,["karyon_core::crypto::key_pair::KeyPairType"]],["impl UnwindSafe for SecretKey",1,["karyon_core::crypto::key_pair::SecretKey"]],["impl UnwindSafe for KeyPair",1,["karyon_core::crypto::key_pair::KeyPair"]],["impl UnwindSafe for Ed25519KeyPair",1,["karyon_core::crypto::key_pair::Ed25519KeyPair"]],["impl UnwindSafe for PublicKey",1,["karyon_core::crypto::key_pair::PublicKey"]],["impl UnwindSafe for Ed25519PublicKey",1,["karyon_core::crypto::key_pair::Ed25519PublicKey"]]], +"karyon_jsonrpc":[["impl UnwindSafe for ClientConfig",1,["karyon_jsonrpc::client::ClientConfig"]],["impl !UnwindSafe for Client",1,["karyon_jsonrpc::client::Client"]],["impl UnwindSafe for CodecConfig",1,["karyon_jsonrpc::codec::CodecConfig"]],["impl !UnwindSafe for Codec",1,["karyon_jsonrpc::codec::Codec"]],["impl !UnwindSafe for Error",1,["karyon_jsonrpc::error::Error"]],["impl UnwindSafe for Request",1,["karyon_jsonrpc::message::Request"]],["impl UnwindSafe for Response",1,["karyon_jsonrpc::message::Response"]],["impl UnwindSafe for Error",1,["karyon_jsonrpc::message::Error"]],["impl UnwindSafe for Notification",1,["karyon_jsonrpc::message::Notification"]],["impl UnwindSafe for ServerConfig",1,["karyon_jsonrpc::server::ServerConfig"]],["impl<'a> !UnwindSafe for Server<'a>",1,["karyon_jsonrpc::server::Server"]]], +"karyon_net":[["impl UnwindSafe for Endpoint",1,["karyon_net::endpoint::Endpoint"]],["impl UnwindSafe for Addr",1,["karyon_net::endpoint::Addr"]],["impl !UnwindSafe for Error",1,["karyon_net::error::Error"]],["impl UnwindSafe for TcpConn",1,["karyon_net::transports::tcp::TcpConn"]],["impl UnwindSafe for TlsConn",1,["karyon_net::transports::tls::TlsConn"]],["impl !UnwindSafe for TlsListener",1,["karyon_net::transports::tls::TlsListener"]],["impl UnwindSafe for UdpConn",1,["karyon_net::transports::udp::UdpConn"]],["impl UnwindSafe for UnixConn",1,["karyon_net::transports::unix::UnixConn"]]], +"karyon_p2p":[["impl !UnwindSafe for Backend",1,["karyon_p2p::backend::Backend"]],["impl !UnwindSafe for Codec",1,["karyon_p2p::codec::Codec"]],["impl UnwindSafe for Config",1,["karyon_p2p::config::Config"]],["impl UnwindSafe for ConnDirection",1,["karyon_p2p::connection::ConnDirection"]],["impl !UnwindSafe for NewConn",1,["karyon_p2p::connection::NewConn"]],["impl !UnwindSafe for ConnQueue",1,["karyon_p2p::connection::ConnQueue"]],["impl !UnwindSafe for Connector",1,["karyon_p2p::connector::Connector"]],["impl !UnwindSafe for LookupService",1,["karyon_p2p::discovery::lookup::LookupService"]],["impl UnwindSafe for PingMsg",1,["karyon_p2p::discovery::refresh::PingMsg"]],["impl UnwindSafe for PongMsg",1,["karyon_p2p::discovery::refresh::PongMsg"]],["impl !UnwindSafe for RefreshService",1,["karyon_p2p::discovery::refresh::RefreshService"]],["impl !UnwindSafe for Discovery",1,["karyon_p2p::discovery::Discovery"]],["impl !UnwindSafe for Error",1,["karyon_p2p::error::Error"]],["impl !UnwindSafe for Listener",1,["karyon_p2p::listener::Listener"]],["impl UnwindSafe for NetMsg",1,["karyon_p2p::message::NetMsg"]],["impl UnwindSafe for NetMsgHeader",1,["karyon_p2p::message::NetMsgHeader"]],["impl UnwindSafe for NetMsgCmd",1,["karyon_p2p::message::NetMsgCmd"]],["impl UnwindSafe for ProtocolMsg",1,["karyon_p2p::message::ProtocolMsg"]],["impl UnwindSafe for VerMsg",1,["karyon_p2p::message::VerMsg"]],["impl UnwindSafe for VerAckMsg",1,["karyon_p2p::message::VerAckMsg"]],["impl UnwindSafe for ShutdownMsg",1,["karyon_p2p::message::ShutdownMsg"]],["impl UnwindSafe for PingMsg",1,["karyon_p2p::message::PingMsg"]],["impl UnwindSafe for PongMsg",1,["karyon_p2p::message::PongMsg"]],["impl UnwindSafe for FindPeerMsg",1,["karyon_p2p::message::FindPeerMsg"]],["impl UnwindSafe for PeerMsg",1,["karyon_p2p::message::PeerMsg"]],["impl UnwindSafe for PeersMsg",1,["karyon_p2p::message::PeersMsg"]],["impl UnwindSafe for PeerID",1,["karyon_p2p::peer::peer_id::PeerID"]],["impl !UnwindSafe for Peer",1,["karyon_p2p::peer::Peer"]],["impl !UnwindSafe for PeerPool",1,["karyon_p2p::peer_pool::PeerPool"]],["impl UnwindSafe for PingProtocolMsg",1,["karyon_p2p::protocols::ping::PingProtocolMsg"]],["impl !UnwindSafe for PingProtocol",1,["karyon_p2p::protocols::ping::PingProtocol"]],["impl UnwindSafe for BucketEntry",1,["karyon_p2p::routing_table::bucket::BucketEntry"]],["impl UnwindSafe for Bucket",1,["karyon_p2p::routing_table::bucket::Bucket"]],["impl UnwindSafe for Entry",1,["karyon_p2p::routing_table::entry::Entry"]],["impl UnwindSafe for AddEntryResult",1,["karyon_p2p::routing_table::AddEntryResult"]],["impl UnwindSafe for RoutingTable",1,["karyon_p2p::routing_table::RoutingTable"]],["impl UnwindSafe for ConnectionSlots",1,["karyon_p2p::slots::ConnectionSlots"]],["impl UnwindSafe for SrvrCertVerifier",1,["karyon_p2p::tls_config::SrvrCertVerifier"]],["impl UnwindSafe for CliCertVerifier",1,["karyon_p2p::tls_config::CliCertVerifier"]],["impl UnwindSafe for Version",1,["karyon_p2p::version::Version"]],["impl UnwindSafe for VersionInt",1,["karyon_p2p::version::VersionInt"]],["impl !UnwindSafe for Monitor",1,["karyon_p2p::monitor::Monitor"]],["impl UnwindSafe for MonitorEvent",1,["karyon_p2p::monitor::MonitorEvent"]],["impl UnwindSafe for ConnEvent",1,["karyon_p2p::monitor::ConnEvent"]],["impl UnwindSafe for PeerPoolEvent",1,["karyon_p2p::monitor::PeerPoolEvent"]],["impl UnwindSafe for DiscoveryEvent",1,["karyon_p2p::monitor::DiscoveryEvent"]],["impl UnwindSafe for ProtocolEvent",1,["karyon_p2p::protocol::ProtocolEvent"]]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/core/str/traits/trait.FromStr.js b/trait.impl/core/str/traits/trait.FromStr.js new file mode 100644 index 00000000..3f03a26c --- /dev/null +++ b/trait.impl/core/str/traits/trait.FromStr.js @@ -0,0 +1,4 @@ +(function() {var implementors = { +"karyon_net":[["impl FromStr for Endpoint"]], +"karyon_p2p":[["impl FromStr for Version"],["impl FromStr for VersionInt"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_core/crypto/key_pair/trait.KeyPairExt.js b/trait.impl/karyon_core/crypto/key_pair/trait.KeyPairExt.js new file mode 100644 index 00000000..41e80b6d --- /dev/null +++ b/trait.impl/karyon_core/crypto/key_pair/trait.KeyPairExt.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_core":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_core/crypto/key_pair/trait.PublicKeyExt.js b/trait.impl/karyon_core/crypto/key_pair/trait.PublicKeyExt.js new file mode 100644 index 00000000..41e80b6d --- /dev/null +++ b/trait.impl/karyon_core/crypto/key_pair/trait.PublicKeyExt.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_core":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_core/event/trait.EventValue.js b/trait.impl/karyon_core/event/trait.EventValue.js new file mode 100644 index 00000000..eb6ab2b3 --- /dev/null +++ b/trait.impl/karyon_core/event/trait.EventValue.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_p2p":[["impl EventValue for ProtocolEvent"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_core/event/trait.EventValueAny.js b/trait.impl/karyon_core/event/trait.EventValueAny.js new file mode 100644 index 00000000..41e80b6d --- /dev/null +++ b/trait.impl/karyon_core/event/trait.EventValueAny.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_core":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_net/connection/trait.Connection.js b/trait.impl/karyon_net/connection/trait.Connection.js new file mode 100644 index 00000000..69227586 --- /dev/null +++ b/trait.impl/karyon_net/connection/trait.Connection.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_net":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_net/connection/trait.ToConn.js b/trait.impl/karyon_net/connection/trait.ToConn.js new file mode 100644 index 00000000..69227586 --- /dev/null +++ b/trait.impl/karyon_net/connection/trait.ToConn.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_net":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_net/listener/trait.ConnListener.js b/trait.impl/karyon_net/listener/trait.ConnListener.js new file mode 100644 index 00000000..69227586 --- /dev/null +++ b/trait.impl/karyon_net/listener/trait.ConnListener.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_net":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_net/listener/trait.ToListener.js b/trait.impl/karyon_net/listener/trait.ToListener.js new file mode 100644 index 00000000..69227586 --- /dev/null +++ b/trait.impl/karyon_net/listener/trait.ToListener.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_net":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_p2p/codec/trait.CodecMsg.js b/trait.impl/karyon_p2p/codec/trait.CodecMsg.js new file mode 100644 index 00000000..7b3698ac --- /dev/null +++ b/trait.impl/karyon_p2p/codec/trait.CodecMsg.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_p2p":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/karyon_p2p/protocol/trait.Protocol.js b/trait.impl/karyon_p2p/protocol/trait.Protocol.js new file mode 100644 index 00000000..7b3698ac --- /dev/null +++ b/trait.impl/karyon_p2p/protocol/trait.Protocol.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_p2p":[] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/rustls/verify/trait.ClientCertVerifier.js b/trait.impl/rustls/verify/trait.ClientCertVerifier.js new file mode 100644 index 00000000..a0e65414 --- /dev/null +++ b/trait.impl/rustls/verify/trait.ClientCertVerifier.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_p2p":[["impl ClientCertVerifier for CliCertVerifier"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/rustls/verify/trait.ServerCertVerifier.js b/trait.impl/rustls/verify/trait.ServerCertVerifier.js new file mode 100644 index 00000000..f9da1ab0 --- /dev/null +++ b/trait.impl/rustls/verify/trait.ServerCertVerifier.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_p2p":[["impl ServerCertVerifier for SrvrCertVerifier"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/serde/de/trait.Deserialize.js b/trait.impl/serde/de/trait.Deserialize.js new file mode 100644 index 00000000..b195a844 --- /dev/null +++ b/trait.impl/serde/de/trait.Deserialize.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_jsonrpc":[["impl<'de> Deserialize<'de> for Request"],["impl<'de> Deserialize<'de> for Response"],["impl<'de> Deserialize<'de> for Error"],["impl<'de> Deserialize<'de> for Notification"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/trait.impl/serde/ser/trait.Serialize.js b/trait.impl/serde/ser/trait.Serialize.js new file mode 100644 index 00000000..c12f75e7 --- /dev/null +++ b/trait.impl/serde/ser/trait.Serialize.js @@ -0,0 +1,3 @@ +(function() {var implementors = { +"karyon_jsonrpc":[["impl Serialize for Error"],["impl Serialize for Notification"],["impl Serialize for Request"],["impl Serialize for Response"]] +};if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() \ No newline at end of file diff --git a/type.impl/alloc/boxed/struct.Box.js b/type.impl/alloc/boxed/struct.Box.js new file mode 100644 index 00000000..99a178be --- /dev/null +++ b/type.impl/alloc/boxed/struct.Box.js @@ -0,0 +1,4 @@ +(function() {var type_impls = { +"karyon_jsonrpc":[["
source§

impl<T> Box<T>

1.0.0 · source

pub fn new(x: T) -> Box<T>

Allocates memory on the heap and then places x into it.

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
let five = Box::new(5);
\n
source

pub fn new_uninit() -> Box<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new box with uninitialized contents.

\n
Examples
\n
#![feature(new_uninit)]\n\nlet mut five = Box::<u32>::new_uninit();\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Box<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n\nlet zero = Box::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
1.33.0 · source

pub fn pin(x: T) -> Pin<Box<T>>

Constructs a new Pin<Box<T>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin(x)\ndoes the same as Box::into_pin(Box::new(x)). Consider using\ninto_pin if you already have a Box<T>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new.

\n
source

pub fn try_new(x: T) -> Result<Box<T>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory on the heap then places x into it,\nreturning an error if the allocation fails

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nlet five = Box::try_new(5)?;
\n
source

pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents on the heap,\nreturning an error if the allocation fails

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nlet mut five = Box::<u32>::try_new_uninit()?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes on the heap

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nlet zero = Box::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
",0,"karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T, A> Box<T, A>
where\n A: Allocator,

source

pub fn new_in(x: T, alloc: A) -> Box<T, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it.

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::new_in(5, System);
\n
source

pub fn try_new_in(x: T, alloc: A) -> Result<Box<T, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it,\nreturning an error if the allocation fails

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::try_new_in(5, System)?;
\n
source

pub fn new_uninit_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator,\nreturning an error if the allocation fails

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn new_zeroed_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator,\nreturning an error if the allocation fails,

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
source

pub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>
where\n A: 'static + Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Box<T, A>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin_in(x, alloc)\ndoes the same as Box::into_pin(Box::new_in(x, alloc)). Consider using\ninto_pin if you already have a Box<T, A>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new_in.

\n
source

pub fn into_boxed_slice(boxed: Box<T, A>) -> Box<[T], A>

🔬This is a nightly-only experimental API. (box_into_boxed_slice)

Converts a Box<T> into a Box<[T]>

\n

This conversion does not allocate on the heap and happens in place.

\n
source

pub fn into_inner(boxed: Box<T, A>) -> T

🔬This is a nightly-only experimental API. (box_into_inner)

Consumes the Box, returning the wrapped value.

\n
Examples
\n
#![feature(box_into_inner)]\n\nlet c = Box::new(5);\n\nassert_eq!(Box::into_inner(c), 5);
\n
",0,"karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T> Box<T>
where\n T: ?Sized,

1.4.0 · source

pub unsafe fn from_raw(raw: *mut T) -> Box<T>

Constructs a box from a raw pointer.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
Safety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n

The safety conditions are described in the memory layout section.

\n
Examples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw:

\n\n
let x = Box::new(5);\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manually create a Box from scratch by using the global allocator:

\n\n
use std::alloc::{alloc, Layout};\n\nunsafe {\n    let ptr = alloc(Layout::new::<i32>()) as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw(ptr);\n}
\n
",0,"karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T, A> Box<T, A>
where\n A: Allocator,\n T: ?Sized,

const: unstable · source

pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a box from a raw pointer in the given allocator.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
Safety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n
Examples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw_with_allocator:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(5, System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manually create a Box from scratch by using the system allocator:

\n\n
#![feature(allocator_api, slice_ptr_get)]\n\nuse std::alloc::{Allocator, Layout, System};\n\nunsafe {\n    let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw_in(ptr, System);\n}
\n
1.4.0 · source

pub fn into_raw(b: Box<T, A>) -> *mut T

Consumes the Box, returning a wrapped raw pointer.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw(b) instead of b.into_raw(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Converting the raw pointer back into a Box with Box::from_raw\nfor automatic cleanup:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
use std::alloc::{dealloc, Layout};\nuse std::ptr;\n\nlet x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    dealloc(ptr as *mut u8, Layout::new::<String>());\n}
\n

Note: This is equivalent to the following:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    drop(Box::from_raw(ptr));\n}
\n
source

pub fn into_raw_with_allocator(b: Box<T, A>) -> (*mut T, A)

🔬This is a nightly-only experimental API. (allocator_api)

Consumes the Box, returning a wrapped raw pointer and the allocator.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw_in function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw_with_allocator(b) instead of b.into_raw_with_allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Converting the raw pointer back into a Box with Box::from_raw_in\nfor automatic cleanup:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::{Allocator, Layout, System};\nuse std::ptr::{self, NonNull};\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    let non_null = NonNull::new_unchecked(ptr);\n    alloc.deallocate(non_null.cast(), Layout::new::<String>());\n}
\n
const: unstable · source

pub fn allocator(b: &Box<T, A>) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Box::allocator(&b) instead of b.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
1.26.0 · source

pub fn leak<'a>(b: Box<T, A>) -> &'a mut T
where\n A: 'a,

Consumes and leaks the Box, returning a mutable reference,\n&'a mut T. Note that the type T must outlive the chosen lifetime\n'a. If the type has only static references, or none at all, then this\nmay be chosen to be 'static.

\n

This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak. If this is not acceptable, the reference should first be wrapped\nwith the Box::from_raw function producing a Box. This Box can\nthen be dropped which will properly destroy T and release the\nallocated memory.

\n

Note: this is an associated function, which means that you have\nto call it as Box::leak(b) instead of b.leak(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Simple usage:

\n\n
let x = Box::new(41);\nlet static_ref: &'static mut usize = Box::leak(x);\n*static_ref += 1;\nassert_eq!(*static_ref, 42);
\n

Unsized data:

\n\n
let x = vec![1, 2, 3].into_boxed_slice();\nlet static_ref = Box::leak(x);\nstatic_ref[0] = 4;\nassert_eq!(*static_ref, [4, 2, 3]);
\n
1.63.0 (const: unstable) · source

pub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>
where\n A: 'static,

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then\n*boxed will be pinned in memory and unable to be moved.

\n

This conversion does not allocate on the heap and happens in place.

\n

This is also available via From.

\n

Constructing and pinning a Box with Box::into_pin(Box::new(x))\ncan also be written more concisely using Box::pin(x).\nThis into_pin method is useful if you already have a Box<T>, or you are\nconstructing a (pinned) Box in a different way than with Box::new.

\n
Notes
\n

It’s not recommended that crates add an impl like From<Box<T>> for Pin<T>,\nas it’ll introduce an ambiguity when calling Pin::from.\nA demonstration of such a poor impl is shown below.

\n\n
struct Foo; // A type defined in this crate.\nimpl From<Box<()>> for Pin<Foo> {\n    fn from(_: Box<()>) -> Pin<Foo> {\n        Pin::new(Foo)\n    }\n}\n\nlet foo = Box::new(());\nlet bar = Pin::from(foo);
\n
",0,"karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<S> Seek for Box<S>
where\n S: Seek + ?Sized,

source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>

Seek to an offset, in bytes, in a stream. Read more
source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.55.0 · source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

🔬This is a nightly-only experimental API. (seek_seek_relative)
Seeks relative to the current position. Read more
","Seek","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<W> Write for Box<W>
where\n W: Write + ?Sized,

source§

fn write(&mut self, buf: &[u8]) -> Result<usize, Error>

Write a buffer into this writer, returning how many bytes were written. Read more
source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored\nimplementation. Read more
source§

fn flush(&mut self) -> Result<(), Error>

Flush this output stream, ensuring that all intermediately buffered\ncontents reach their destination. Read more
source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error\nencountered. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
","Write","karyon_jsonrpc::service::RPCMethod"],["
1.63.0 · source§

impl<T> AsRawFd for Box<T>
where\n T: AsRawFd,

source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<B> BufRead for Box<B>
where\n B: BufRead + ?Sized,

source§

fn fill_buf(&mut self) -> Result<&[u8], Error>

Returns the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
source§

fn consume(&mut self, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to read. Read more
source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes into buf until the delimiter byte or EOF is reached. Read more
source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until a newline (the 0xA byte) is reached, and append\nthem to the provided String buffer. Read more
source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Check if the underlying Read has any data left to be read. Read more
source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

🔬This is a nightly-only experimental API. (bufread_skip_until)
Skip all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · source§

fn split(self, byte: u8) -> Split<Self>
where\n Self: Sized,

Returns an iterator over the contents of this reader split on the byte\nbyte. Read more
1.0.0 · source§

fn lines(self) -> Lines<Self>
where\n Self: Sized,

Returns an iterator over the lines of this reader. Read more
","BufRead","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<R> Read for Box<R>
where\n R: Read + ?Sized,

source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>

Pull some bytes from this source into the specified buffer, returning\nhow many bytes were read. Read more
source§

fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored\nimplementation. Read more
source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes until EOF in this source, placing them into buf. Read more
source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until EOF in this source, appending them to buf. Read more
source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Read the exact number of bytes required to fill buf. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Read the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where\n Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where\n R: Read,\n Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where\n Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
","Read","karyon_jsonrpc::service::RPCMethod"],["
1.64.0 · source§

impl<T> AsFd for Box<T>
where\n T: AsFd,

source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","karyon_jsonrpc::service::RPCMethod"],["
1.33.0 · source§

impl<T, A> Unpin for Box<T, A>
where\n A: Allocator + 'static,\n T: ?Sized,

","Unpin","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> DerefMut for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
","DerefMut","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T, U> DispatchFromDyn<Box<U>> for Box<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_jsonrpc::service::RPCMethod"],["
1.36.0 · source§

impl<F, A> Future for Box<F, A>
where\n F: Future + Unpin + ?Sized,\n A: Allocator + 'static,

§

type Output = <F as Future>::Output

The type of value produced on completion.
source§

fn poll(\n self: Pin<&mut Box<F, A>>,\n cx: &mut Context<'_>\n) -> Poll<<Box<F, A> as Future>::Output>

Attempt to resolve the future to a final value, registering\nthe current task for wakeup if the value is not yet available. Read more
","Future","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<I, A> ExactSizeIterator for Box<I, A>
where\n I: ExactSizeIterator + ?Sized,\n A: Allocator,

source§

fn len(&self) -> usize

Returns the exact remaining length of the iterator. Read more
source§

fn is_empty(&self) -> bool

🔬This is a nightly-only experimental API. (exact_size_is_empty)
Returns true if the iterator is empty. Read more
","ExactSizeIterator","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<I, A> Iterator for Box<I, A>
where\n I: Iterator + ?Sized,\n A: Allocator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<<I as Iterator>::Item>

Advances the iterator and returns the next value. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
source§

fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element of the iterator. Read more
source§

fn last(self) -> Option<<I as Iterator>::Item>

Consumes the iterator, returning the last element. Read more
source§

fn next_chunk<const N: usize>(\n &mut self\n) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>
where\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0 · source§

fn count(self) -> usize
where\n Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
source§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.28.0 · source§

fn step_by(self, step: usize) -> StepBy<Self>
where\n Self: Sized,

Creates an iterator starting at the same point, but stepping by\nthe given amount at each iteration. Read more
1.0.0 · source§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0 · source§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
source§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
where\n Self: Sized,\n G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator\nbetween adjacent items of the original iterator. Read more
1.0.0 · source§

fn map<B, F>(self, f: F) -> Map<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each\nelement. Read more
1.21.0 · source§

fn for_each<F>(self, f: F)
where\n Self: Sized,\n F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0 · source§

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element\nshould be yielded. Read more
1.0.0 · source§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0 · source§

fn enumerate(self) -> Enumerate<Self>
where\n Self: Sized,

Creates an iterator which gives the current iteration count as well as\nthe next value. Read more
1.0.0 · source§

fn peekable(self) -> Peekable<Self>
where\n Self: Sized,

Creates an iterator which can use the peek and peek_mut methods\nto look at the next element of the iterator without consuming it. See\ntheir documentation for more information. Read more
1.0.0 · source§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0 · source§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0 · source§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
where\n Self: Sized,\n P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0 · source§

fn skip(self, n: usize) -> Skip<Self>
where\n Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0 · source§

fn take(self, n: usize) -> Take<Self>
where\n Self: Sized,

Creates an iterator that yields the first n elements, or fewer\nif the underlying iterator ends sooner. Read more
1.0.0 · source§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where\n Self: Sized,\n F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but\nunlike fold, produces a new iterator. Read more
1.0.0 · source§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where\n Self: Sized,\n U: IntoIterator,\n F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
source§

fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
where\n Self: Sized,\n F: FnMut(&[Self::Item; N]) -> R,

🔬This is a nightly-only experimental API. (iter_map_windows)
Calls the given function f for each contiguous window of size N over\nself and returns an iterator over the outputs of f. Like slice::windows(),\nthe windows during mapping overlap as well. Read more
1.0.0 · source§

fn fuse(self) -> Fuse<Self>
where\n Self: Sized,

Creates an iterator which ends after the first None. Read more
1.0.0 · source§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where\n Self: Sized,\n F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0 · source§

fn collect<B>(self) -> B
where\n B: FromIterator<Self::Item>,\n Self: Sized,

Transforms an iterator into a collection. Read more
source§

fn collect_into<E>(self, collection: &mut E) -> &mut E
where\n E: Extend<Self::Item>,\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0 · source§

fn partition<B, F>(self, f: F) -> (B, B)
where\n Self: Sized,\n B: Default + Extend<Self::Item>,\n F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
source§

fn is_partitioned<P>(self, predicate: P) -> bool
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate,\nsuch that all those that return true precede all those that return false. Read more
1.27.0 · source§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

An iterator method that applies a function as long as it returns\nsuccessfully, producing a single, final value. Read more
1.27.0 · source§

fn try_for_each<F, R>(&mut self, f: F) -> R
where\n Self: Sized,\n F: FnMut(Self::Item) -> R,\n R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the\niterator, stopping at the first error and returning that error. Read more
1.0.0 · source§

fn fold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation,\nreturning the final result. Read more
1.51.0 · source§

fn reduce<F>(self, f: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing\noperation. Read more
source§

fn try_reduce<F, R>(\n &mut self,\n f: F\n) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
where\n Self: Sized,\n F: FnMut(Self::Item, Self::Item) -> R,\n R: Try<Output = Self::Item>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the\nclosure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0 · source§

fn all<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0 · source§

fn any<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0 · source§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0 · source§

fn find_map<B, F>(&mut self, f: F) -> Option<B>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns\nthe first non-none result. Read more
source§

fn try_find<F, R>(\n &mut self,\n f: F\n) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
where\n Self: Sized,\n F: FnMut(&Self::Item) -> R,\n R: Try<Output = bool>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns\nthe first true result or the first error. Read more
1.0.0 · source§

fn position<P>(&mut self, predicate: P) -> Option<usize>
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0 · source§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the\nspecified function. Read more
1.15.0 · source§

fn max_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the\nspecified comparison function. Read more
1.6.0 · source§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the\nspecified function. Read more
1.15.0 · source§

fn min_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the\nspecified comparison function. Read more
1.0.0 · source§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
where\n FromA: Default + Extend<A>,\n FromB: Default + Extend<B>,\n Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0 · source§

fn copied<'a, T>(self) -> Copied<Self>
where\n T: 'a + Copy,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0 · source§

fn cloned<'a, T>(self) -> Cloned<Self>
where\n T: 'a + Clone,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
source§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
where\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0 · source§

fn sum<S>(self) -> S
where\n Self: Sized,\n S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0 · source§

fn product<P>(self) -> P
where\n Self: Sized,\n P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
source§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.5.0 · source§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Lexicographically compares the PartialOrd elements of\nthis Iterator with those of another. The comparison works like short-circuit\nevaluation, returning a result without comparing the remaining elements.\nAs soon as an order can be determined, the evaluation stops and a result is returned. Read more
source§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.5.0 · source§

fn eq<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are equal to those of\nanother. Read more
source§

fn eq_by<I, F>(self, other: I, eq: F) -> bool
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this Iterator are equal to those of\nanother with respect to the specified equality function. Read more
1.5.0 · source§

fn ne<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are not equal to those of\nanother. Read more
1.5.0 · source§

fn lt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless than those of another. Read more
1.5.0 · source§

fn le<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless or equal to those of another. Read more
1.5.0 · source§

fn gt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than those of another. Read more
1.5.0 · source§

fn ge<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than or equal to those of another. Read more
source§

fn is_sorted_by<F>(self, compare: F) -> bool
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
source§

fn is_sorted_by_key<F, K>(self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> K,\n K: PartialOrd,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction\nfunction. Read more
","Iterator","karyon_jsonrpc::service::RPCMethod"],["
1.22.0 · source§

impl<T, A> Hasher for Box<T, A>
where\n T: Hasher + ?Sized,\n A: Allocator,

source§

fn finish(&self) -> u64

Returns the hash value for the values written so far. Read more
source§

fn write(&mut self, bytes: &[u8])

Writes some data into this Hasher. Read more
source§

fn write_u8(&mut self, i: u8)

Writes a single u8 into this hasher.
source§

fn write_u16(&mut self, i: u16)

Writes a single u16 into this hasher.
source§

fn write_u32(&mut self, i: u32)

Writes a single u32 into this hasher.
source§

fn write_u64(&mut self, i: u64)

Writes a single u64 into this hasher.
source§

fn write_u128(&mut self, i: u128)

Writes a single u128 into this hasher.
source§

fn write_usize(&mut self, i: usize)

Writes a single usize into this hasher.
source§

fn write_i8(&mut self, i: i8)

Writes a single i8 into this hasher.
source§

fn write_i16(&mut self, i: i16)

Writes a single i16 into this hasher.
source§

fn write_i32(&mut self, i: i32)

Writes a single i32 into this hasher.
source§

fn write_i64(&mut self, i: i64)

Writes a single i64 into this hasher.
source§

fn write_i128(&mut self, i: i128)

Writes a single i128 into this hasher.
source§

fn write_isize(&mut self, i: isize)

Writes a single isize into this hasher.
source§

fn write_length_prefix(&mut self, len: usize)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a length prefix into this hasher, as part of being prefix-free. Read more
source§

fn write_str(&mut self, s: &str)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a single str into this hasher. Read more
","Hasher","karyon_jsonrpc::service::RPCMethod"],["
1.8.0 · source§

impl<T> Error for Box<T>
where\n T: Error,

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
source§

fn provide<'b>(&'b self, request: &mut Request<'b>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
","Error","karyon_jsonrpc::service::RPCMethod"],["
1.35.0 · source§

impl<Args, F, A> FnMut<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnMut<Args> + ?Sized,\n A: Allocator,

source§

extern "rust-call" fn call_mut(\n &mut self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnMut","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<S> AsyncIterator for Box<S>
where\n S: AsyncIterator + Unpin + ?Sized,

§

type Item = <S as AsyncIterator>::Item

🔬This is a nightly-only experimental API. (async_iterator)
The type of items yielded by the async iterator.
source§

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Box<S> as AsyncIterator>::Item>>

🔬This is a nightly-only experimental API. (async_iterator)
Attempt to pull out the next value of this async iterator, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the async iterator is exhausted. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (async_iterator)
Returns the bounds on the remaining length of the async iterator. Read more
","AsyncIterator","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Pointer for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
","Pointer","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> PartialOrd for Box<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

source§

fn partial_cmp(&self, other: &Box<T, A>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
source§

fn lt(&self, other: &Box<T, A>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
source§

fn le(&self, other: &Box<T, A>) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
source§

fn ge(&self, other: &Box<T, A>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
source§

fn gt(&self, other: &Box<T, A>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
","PartialOrd","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Deref for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
","Deref","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Ord for Box<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

source§

fn cmp(&self, other: &Box<T, A>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_jsonrpc::service::RPCMethod"],["
1.6.0 · source§

impl<T> From<T> for Box<T>

source§

fn from(t: T) -> Box<T>

Converts a T into a Box<T>

\n

The conversion allocates on the heap and moves t\nfrom the stack into it.

\n
Examples
\n
let x = 5;\nlet boxed = Box::new(5);\n\nassert_eq!(Box::from(x), boxed);
\n
","From","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Drop for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
","Drop","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T, U, A> CoerceUnsized<Box<U, A>> for Box<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_jsonrpc::service::RPCMethod"],["
1.35.0 · source§

impl<Args, F, A> Fn<Args> for Box<F, A>
where\n Args: Tuple,\n F: Fn<Args> + ?Sized,\n A: Allocator,

source§

extern "rust-call" fn call(\n &self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","Fn","karyon_jsonrpc::service::RPCMethod"],["
1.26.0 · source§

impl<I, A> FusedIterator for Box<I, A>
where\n I: FusedIterator + ?Sized,\n A: Allocator,

","FusedIterator","karyon_jsonrpc::service::RPCMethod"],["
1.5.0 · source§

impl<T, A> AsRef<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_jsonrpc::service::RPCMethod"],["
1.1.0 · source§

impl<T, A> Borrow<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Hash for Box<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

source§

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_jsonrpc::service::RPCMethod"],["
1.5.0 · source§

impl<T, A> AsMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
","AsMut","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Clone for Box<T, A>
where\n T: Clone,\n A: Allocator + Clone,

source§

fn clone(&self) -> Box<T, A>

Returns a new box with a clone() of this box’s contents.

\n
Examples
\n
let x = Box::new(5);\nlet y = x.clone();\n\n// The value is the same\nassert_eq!(x, y);\n\n// But they are unique objects\nassert_ne!(&*x as *const i32, &*y as *const i32);
\n
source§

fn clone_from(&mut self, source: &Box<T, A>)

Copies source’s contents into self without creating a new allocation.

\n
Examples
\n
let x = Box::new(5);\nlet mut y = Box::new(10);\nlet yp: *const i32 = &*y;\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no allocation occurred\nassert_eq!(yp, &*y);
\n
","Clone","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Display for Box<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<I, A> DoubleEndedIterator for Box<I, A>
where\n I: DoubleEndedIterator + ?Sized,\n A: Allocator,

source§

fn next_back(&mut self) -> Option<<I as Iterator>::Item>

Removes and returns an element from the end of the iterator. Read more
source§

fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element from the end of the iterator. Read more
source§

fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator from the back by n elements. Read more
1.27.0 · source§

fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

This is the reverse version of Iterator::try_fold(): it takes\nelements starting from the back of the iterator. Read more
1.27.0 · source§

fn rfold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

An iterator method that reduces the iterator’s elements to a single,\nfinal value, starting from the back. Read more
1.27.0 · source§

fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator from the back that satisfies a predicate. Read more
","DoubleEndedIterator","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<G, R, A> Coroutine<R> for Box<G, A>
where\n G: Coroutine<R> + Unpin + ?Sized,\n A: Allocator + 'static,

§

type Yield = <G as Coroutine<R>>::Yield

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine yields. Read more
§

type Return = <G as Coroutine<R>>::Return

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine returns. Read more
source§

fn resume(\n self: Pin<&mut Box<G, A>>,\n arg: R\n) -> CoroutineState<<Box<G, A> as Coroutine<R>>::Yield, <Box<G, A> as Coroutine<R>>::Return>

🔬This is a nightly-only experimental API. (coroutine_trait)
Resumes the execution of this coroutine. Read more
","Coroutine","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Eq for Box<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","karyon_jsonrpc::service::RPCMethod"],["
1.1.0 · source§

impl<T, A> BorrowMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
","BorrowMut","karyon_jsonrpc::service::RPCMethod"],["
1.35.0 · source§

impl<Args, F, A> FnOnce<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnOnce<Args> + ?Sized,\n A: Allocator,

§

type Output = <F as FnOnce<Args>>::Output

The returned type after the call operator is used.
source§

extern "rust-call" fn call_once(\n self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnOnce","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T> Default for Box<T>
where\n T: Default,

source§

fn default() -> Box<T>

Creates a Box<T>, with the Default value for T.

\n
","Default","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> Debug for Box<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_jsonrpc::service::RPCMethod"],["
1.0.0 · source§

impl<T, A> PartialEq for Box<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

source§

fn eq(&self, other: &Box<T, A>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &Box<T, A>) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<'de, T> Deserialize<'de> for Box<T>
where\n T: Deserialize<'de>,

source§

fn deserialize<D>(\n deserializer: D\n) -> Result<Box<T>, <D as Deserializer<'de>>::Error>
where\n D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
","Deserialize<'de>","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T> Serialize for Box<T>
where\n T: Serialize + ?Sized,

source§

fn serialize<S>(\n &self,\n serializer: S\n) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where\n S: Serializer,

Serialize this value into the given Serde serializer. Read more
","Serialize","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T> Encode for Box<T>
where\n T: Encode + ?Sized,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<'de, T> BorrowDecode<'de> for Box<T>
where\n T: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Box<T>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<T> Decode for Box<T>
where\n T: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Box<T>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<R> CryptoRng for Box<R>
where\n R: CryptoRng + ?Sized,

","CryptoRng","karyon_jsonrpc::service::RPCMethod"],["
source§

impl<R> RngCore for Box<R>
where\n R: RngCore + ?Sized,

source§

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
source§

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data. Read more
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill dest entirely with random data. Read more
","RngCore","karyon_jsonrpc::service::RPCMethod"],["
§

impl<S> Stream for Box<S>
where\n S: Stream + Unpin + ?Sized,

§

type Item = <S as Stream>::Item

Values yielded by the stream.
§

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Box<S> as Stream>::Item>>

Attempt to pull out the next value of this stream, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the stream is exhausted. Read more
§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
","Stream","karyon_jsonrpc::service::RPCMethod"],["
§

impl<F> FusedFuture for Box<F>
where\n F: FusedFuture + Unpin + ?Sized,

§

fn is_terminated(&self) -> bool

Returns true if the underlying future should no longer be polled.
","FusedFuture","karyon_jsonrpc::service::RPCMethod"],["
§

impl<S> FusedStream for Box<S>
where\n S: FusedStream + Unpin + ?Sized,

§

fn is_terminated(&self) -> bool

Returns true if the stream should no longer be polled.
","FusedStream","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> AsyncWrite for Box<T>
where\n T: AsyncWrite + Unpin + ?Sized,

§

fn poll_write(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n buf: &[u8]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
§

fn poll_write_vectored(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n bufs: &[IoSlice<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from bufs into the object using vectored\nIO operations. Read more
§

fn poll_flush(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to flush the object, ensuring that any buffered data reach\ntheir destination. Read more
§

fn poll_close(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to close the object. Read more
","AsyncWrite","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> AsyncRead for Box<T>
where\n T: AsyncRead + Unpin + ?Sized,

§

fn poll_read(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n buf: &mut [u8]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into buf. Read more
§

fn poll_read_vectored(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n bufs: &mut [IoSliceMut<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into bufs using vectored\nIO operations. Read more
","AsyncRead","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> AsyncSeek for Box<T>
where\n T: AsyncSeek + Unpin + ?Sized,

§

fn poll_seek(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n pos: SeekFrom\n) -> Poll<Result<u64, Error>>

Attempt to seek to an offset, in bytes, in a stream. Read more
","AsyncSeek","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> AsyncBufRead for Box<T>
where\n T: AsyncBufRead + Unpin + ?Sized,

§

fn poll_fill_buf(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<&[u8], Error>>

Attempt to return the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
§

fn consume(self: Pin<&mut Box<T>>, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to poll_read. Read more
","AsyncBufRead","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> IoSafe for Box<T>
where\n T: IoSafe + ?Sized,

","IoSafe","karyon_jsonrpc::service::RPCMethod"],["
§

impl<S> Subscriber for Box<S>
where\n S: Subscriber + ?Sized,

§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this subscriber, returning whether or not\nthe subscriber is interested in being notified about the callsite. Read more
§

fn enabled(&self, metadata: &Metadata<'_>) -> bool

Returns true if a span or event with the specified metadata would be\nrecorded. Read more
§

fn max_level_hint(&self) -> Option<LevelFilter>

Returns the highest verbosity level that this Subscriber will\nenable, or None, if the subscriber does not implement level-based\nfiltering or chooses not to implement this method. Read more
§

fn new_span(&self, span: &Attributes<'_>) -> Id

Visit the construction of a new span, returning a new span ID for the\nspan being constructed. Read more
§

fn record(&self, span: &Id, values: &Record<'_>)

Record a set of values on a span. Read more
§

fn record_follows_from(&self, span: &Id, follows: &Id)

Adds an indication that span follows from the span with the id\nfollows. Read more
§

fn event_enabled(&self, event: &Event<'_>) -> bool

Determine if an [Event] should be recorded. Read more
§

fn event(&self, event: &Event<'_>)

Records that an Event has occurred. Read more
§

fn enter(&self, span: &Id)

Records that a span has been entered. Read more
§

fn exit(&self, span: &Id)

Records that a span has been exited. Read more
§

fn clone_span(&self, id: &Id) -> Id

Notifies the subscriber that a span ID has been cloned. Read more
§

fn try_close(&self, id: Id) -> bool

Notifies the subscriber that a span ID has been dropped, and returns\ntrue if there are now 0 IDs that refer to that span. Read more
§

fn drop_span(&self, id: Id)

👎Deprecated since 0.1.2: use Subscriber::try_close instead
This method is deprecated. Read more
§

fn current_span(&self) -> Current

Returns a type representing this subscriber’s view of the current span. Read more
§

unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()>

If self is the same type as the provided TypeId, returns an untyped\n*const pointer to that type. Otherwise, returns None. Read more
§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Invoked when this subscriber becomes a [Dispatch]. Read more
","Subscriber","karyon_jsonrpc::service::RPCMethod"],["
§

impl<T> Value for Box<T>
where\n T: Value + ?Sized,

§

fn record(&self, key: &Field, visitor: &mut dyn Visit)

Visits this value with the given Visitor.
","Value","karyon_jsonrpc::service::RPCMethod"]], +"karyon_net":[["
source§

impl<T> Box<T>

1.0.0 · source

pub fn new(x: T) -> Box<T>

Allocates memory on the heap and then places x into it.

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
let five = Box::new(5);
\n
source

pub fn new_uninit() -> Box<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new box with uninitialized contents.

\n
Examples
\n
#![feature(new_uninit)]\n\nlet mut five = Box::<u32>::new_uninit();\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Box<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n\nlet zero = Box::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
1.33.0 · source

pub fn pin(x: T) -> Pin<Box<T>>

Constructs a new Pin<Box<T>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin(x)\ndoes the same as Box::into_pin(Box::new(x)). Consider using\ninto_pin if you already have a Box<T>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new.

\n
source

pub fn try_new(x: T) -> Result<Box<T>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory on the heap then places x into it,\nreturning an error if the allocation fails

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nlet five = Box::try_new(5)?;
\n
source

pub fn try_new_uninit() -> Result<Box<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents on the heap,\nreturning an error if the allocation fails

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nlet mut five = Box::<u32>::try_new_uninit()?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Box<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes on the heap

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nlet zero = Box::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
",0,"karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T, A> Box<T, A>
where\n A: Allocator,

source

pub fn new_in(x: T, alloc: A) -> Box<T, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it.

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::new_in(5, System);
\n
source

pub fn try_new_in(x: T, alloc: A) -> Result<Box<T, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Allocates memory in the given allocator then places x into it,\nreturning an error if the allocation fails

\n

This doesn’t actually allocate if T is zero-sized.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet five = Box::try_new_in(5, System)?;
\n
source

pub fn new_uninit_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new box with uninitialized contents in the provided allocator,\nreturning an error if the allocation fails

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet mut five = Box::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    five.as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn new_zeroed_in(alloc: A) -> Box<MaybeUninit<T>, A>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Box<MaybeUninit<T>, A>, AllocError>
where\n A: Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Box with uninitialized contents, with the memory\nbeing filled with 0 bytes in the provided allocator,\nreturning an error if the allocation fails,

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(allocator_api, new_uninit)]\n\nuse std::alloc::System;\n\nlet zero = Box::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
source

pub fn pin_in(x: T, alloc: A) -> Pin<Box<T, A>>
where\n A: 'static + Allocator,

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Box<T, A>>. If T does not implement Unpin, then\nx will be pinned in memory and unable to be moved.

\n

Constructing and pinning of the Box can also be done in two steps: Box::pin_in(x, alloc)\ndoes the same as Box::into_pin(Box::new_in(x, alloc)). Consider using\ninto_pin if you already have a Box<T, A>, or if you want to\nconstruct a (pinned) Box in a different way than with Box::new_in.

\n
source

pub fn into_boxed_slice(boxed: Box<T, A>) -> Box<[T], A>

🔬This is a nightly-only experimental API. (box_into_boxed_slice)

Converts a Box<T> into a Box<[T]>

\n

This conversion does not allocate on the heap and happens in place.

\n
source

pub fn into_inner(boxed: Box<T, A>) -> T

🔬This is a nightly-only experimental API. (box_into_inner)

Consumes the Box, returning the wrapped value.

\n
Examples
\n
#![feature(box_into_inner)]\n\nlet c = Box::new(5);\n\nassert_eq!(Box::into_inner(c), 5);
\n
",0,"karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T> Box<T>
where\n T: ?Sized,

1.4.0 · source

pub unsafe fn from_raw(raw: *mut T) -> Box<T>

Constructs a box from a raw pointer.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
Safety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n

The safety conditions are described in the memory layout section.

\n
Examples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw:

\n\n
let x = Box::new(5);\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manually create a Box from scratch by using the global allocator:

\n\n
use std::alloc::{alloc, Layout};\n\nunsafe {\n    let ptr = alloc(Layout::new::<i32>()) as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw(ptr);\n}
\n
",0,"karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T, A> Box<T, A>
where\n A: Allocator,\n T: ?Sized,

const: unstable · source

pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Box<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a box from a raw pointer in the given allocator.

\n

After calling this function, the raw pointer is owned by the\nresulting Box. Specifically, the Box destructor will call\nthe destructor of T and free the allocated memory. For this\nto be safe, the memory must have been allocated in accordance\nwith the memory layout used by Box .

\n
Safety
\n

This function is unsafe because improper use may lead to\nmemory problems. For example, a double-free may occur if the\nfunction is called twice on the same raw pointer.

\n
Examples
\n

Recreate a Box which was previously converted to a raw pointer\nusing Box::into_raw_with_allocator:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(5, System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manually create a Box from scratch by using the system allocator:

\n\n
#![feature(allocator_api, slice_ptr_get)]\n\nuse std::alloc::{Allocator, Layout, System};\n\nunsafe {\n    let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;\n    // In general .write is required to avoid attempting to destruct\n    // the (uninitialized) previous contents of `ptr`, though for this\n    // simple example `*ptr = 5` would have worked as well.\n    ptr.write(5);\n    let x = Box::from_raw_in(ptr, System);\n}
\n
1.4.0 · source

pub fn into_raw(b: Box<T, A>) -> *mut T

Consumes the Box, returning a wrapped raw pointer.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw(b) instead of b.into_raw(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Converting the raw pointer back into a Box with Box::from_raw\nfor automatic cleanup:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nlet x = unsafe { Box::from_raw(ptr) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
use std::alloc::{dealloc, Layout};\nuse std::ptr;\n\nlet x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    dealloc(ptr as *mut u8, Layout::new::<String>());\n}
\n

Note: This is equivalent to the following:

\n\n
let x = Box::new(String::from(\"Hello\"));\nlet ptr = Box::into_raw(x);\nunsafe {\n    drop(Box::from_raw(ptr));\n}
\n
source

pub fn into_raw_with_allocator(b: Box<T, A>) -> (*mut T, A)

🔬This is a nightly-only experimental API. (allocator_api)

Consumes the Box, returning a wrapped raw pointer and the allocator.

\n

The pointer will be properly aligned and non-null.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the Box. In particular, the\ncaller should properly destroy T and release the memory, taking\ninto account the memory layout used by Box. The easiest way to\ndo this is to convert the raw pointer back into a Box with the\nBox::from_raw_in function, allowing the Box destructor to perform\nthe cleanup.

\n

Note: this is an associated function, which means that you have\nto call it as Box::into_raw_with_allocator(b) instead of b.into_raw_with_allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Converting the raw pointer back into a Box with Box::from_raw_in\nfor automatic cleanup:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::System;\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nlet x = unsafe { Box::from_raw_in(ptr, alloc) };
\n

Manual cleanup by explicitly running the destructor and deallocating\nthe memory:

\n\n
#![feature(allocator_api)]\n\nuse std::alloc::{Allocator, Layout, System};\nuse std::ptr::{self, NonNull};\n\nlet x = Box::new_in(String::from(\"Hello\"), System);\nlet (ptr, alloc) = Box::into_raw_with_allocator(x);\nunsafe {\n    ptr::drop_in_place(ptr);\n    let non_null = NonNull::new_unchecked(ptr);\n    alloc.deallocate(non_null.cast(), Layout::new::<String>());\n}
\n
const: unstable · source

pub fn allocator(b: &Box<T, A>) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Box::allocator(&b) instead of b.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
1.26.0 · source

pub fn leak<'a>(b: Box<T, A>) -> &'a mut T
where\n A: 'a,

Consumes and leaks the Box, returning a mutable reference,\n&'a mut T. Note that the type T must outlive the chosen lifetime\n'a. If the type has only static references, or none at all, then this\nmay be chosen to be 'static.

\n

This function is mainly useful for data that lives for the remainder of\nthe program’s life. Dropping the returned reference will cause a memory\nleak. If this is not acceptable, the reference should first be wrapped\nwith the Box::from_raw function producing a Box. This Box can\nthen be dropped which will properly destroy T and release the\nallocated memory.

\n

Note: this is an associated function, which means that you have\nto call it as Box::leak(b) instead of b.leak(). This\nis so that there is no conflict with a method on the inner type.

\n
Examples
\n

Simple usage:

\n\n
let x = Box::new(41);\nlet static_ref: &'static mut usize = Box::leak(x);\n*static_ref += 1;\nassert_eq!(*static_ref, 42);
\n

Unsized data:

\n\n
let x = vec![1, 2, 3].into_boxed_slice();\nlet static_ref = Box::leak(x);\nstatic_ref[0] = 4;\nassert_eq!(*static_ref, [4, 2, 3]);
\n
1.63.0 (const: unstable) · source

pub fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>>
where\n A: 'static,

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then\n*boxed will be pinned in memory and unable to be moved.

\n

This conversion does not allocate on the heap and happens in place.

\n

This is also available via From.

\n

Constructing and pinning a Box with Box::into_pin(Box::new(x))\ncan also be written more concisely using Box::pin(x).\nThis into_pin method is useful if you already have a Box<T>, or you are\nconstructing a (pinned) Box in a different way than with Box::new.

\n
Notes
\n

It’s not recommended that crates add an impl like From<Box<T>> for Pin<T>,\nas it’ll introduce an ambiguity when calling Pin::from.\nA demonstration of such a poor impl is shown below.

\n\n
struct Foo; // A type defined in this crate.\nimpl From<Box<()>> for Pin<Foo> {\n    fn from(_: Box<()>) -> Pin<Foo> {\n        Pin::new(Foo)\n    }\n}\n\nlet foo = Box::new(());\nlet bar = Pin::from(foo);
\n
",0,"karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<S> Seek for Box<S>
where\n S: Seek + ?Sized,

source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error>

Seek to an offset, in bytes, in a stream. Read more
source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.55.0 · source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

🔬This is a nightly-only experimental API. (seek_seek_relative)
Seeks relative to the current position. Read more
","Seek","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<W> Write for Box<W>
where\n W: Write + ?Sized,

source§

fn write(&mut self, buf: &[u8]) -> Result<usize, Error>

Write a buffer into this writer, returning how many bytes were written. Read more
source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored\nimplementation. Read more
source§

fn flush(&mut self) -> Result<(), Error>

Flush this output stream, ensuring that all intermediately buffered\ncontents reach their destination. Read more
source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error\nencountered. Read more
source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
","Write","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.63.0 · source§

impl<T> AsRawFd for Box<T>
where\n T: AsRawFd,

source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<B> BufRead for Box<B>
where\n B: BufRead + ?Sized,

source§

fn fill_buf(&mut self) -> Result<&[u8], Error>

Returns the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
source§

fn consume(&mut self, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to read. Read more
source§

fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes into buf until the delimiter byte or EOF is reached. Read more
source§

fn read_line(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until a newline (the 0xA byte) is reached, and append\nthem to the provided String buffer. Read more
source§

fn has_data_left(&mut self) -> Result<bool, Error>

🔬This is a nightly-only experimental API. (buf_read_has_data_left)
Check if the underlying Read has any data left to be read. Read more
source§

fn skip_until(&mut self, byte: u8) -> Result<usize, Error>

🔬This is a nightly-only experimental API. (bufread_skip_until)
Skip all bytes until the delimiter byte or EOF is reached. Read more
1.0.0 · source§

fn split(self, byte: u8) -> Split<Self>
where\n Self: Sized,

Returns an iterator over the contents of this reader split on the byte\nbyte. Read more
1.0.0 · source§

fn lines(self) -> Lines<Self>
where\n Self: Sized,

Returns an iterator over the lines of this reader. Read more
","BufRead","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<R> Read for Box<R>
where\n R: Read + ?Sized,

source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>

Pull some bytes from this source into the specified buffer, returning\nhow many bytes were read. Read more
source§

fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored\nimplementation. Read more
source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, Error>

Read all bytes until EOF in this source, placing them into buf. Read more
source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>

Read all bytes until EOF in this source, appending them to buf. Read more
source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>

Read the exact number of bytes required to fill buf. Read more
source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Read the exact number of bytes required to fill cursor. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · source§

fn bytes(self) -> Bytes<Self>
where\n Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where\n R: Read,\n Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · source§

fn take(self, limit: u64) -> Take<Self>
where\n Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
","Read","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.64.0 · source§

impl<T> AsFd for Box<T>
where\n T: AsFd,

source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.33.0 · source§

impl<T, A> Unpin for Box<T, A>
where\n A: Allocator + 'static,\n T: ?Sized,

","Unpin","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> DerefMut for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
","DerefMut","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T, U> DispatchFromDyn<Box<U>> for Box<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.36.0 · source§

impl<F, A> Future for Box<F, A>
where\n F: Future + Unpin + ?Sized,\n A: Allocator + 'static,

§

type Output = <F as Future>::Output

The type of value produced on completion.
source§

fn poll(\n self: Pin<&mut Box<F, A>>,\n cx: &mut Context<'_>\n) -> Poll<<Box<F, A> as Future>::Output>

Attempt to resolve the future to a final value, registering\nthe current task for wakeup if the value is not yet available. Read more
","Future","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<I, A> ExactSizeIterator for Box<I, A>
where\n I: ExactSizeIterator + ?Sized,\n A: Allocator,

source§

fn len(&self) -> usize

Returns the exact remaining length of the iterator. Read more
source§

fn is_empty(&self) -> bool

🔬This is a nightly-only experimental API. (exact_size_is_empty)
Returns true if the iterator is empty. Read more
","ExactSizeIterator","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<I, A> Iterator for Box<I, A>
where\n I: Iterator + ?Sized,\n A: Allocator,

§

type Item = <I as Iterator>::Item

The type of the elements being iterated over.
source§

fn next(&mut self) -> Option<<I as Iterator>::Item>

Advances the iterator and returns the next value. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator. Read more
source§

fn nth(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element of the iterator. Read more
source§

fn last(self) -> Option<<I as Iterator>::Item>

Consumes the iterator, returning the last element. Read more
source§

fn next_chunk<const N: usize>(\n &mut self\n) -> Result<[Self::Item; N], IntoIter<Self::Item, N>>
where\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
1.0.0 · source§

fn count(self) -> usize
where\n Self: Sized,

Consumes the iterator, counting the number of iterations and returning it. Read more
source§

fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
1.28.0 · source§

fn step_by(self, step: usize) -> StepBy<Self>
where\n Self: Sized,

Creates an iterator starting at the same point, but stepping by\nthe given amount at each iteration. Read more
1.0.0 · source§

fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator<Item = Self::Item>,

Takes two iterators and creates a new iterator over both in sequence. Read more
1.0.0 · source§

fn zip<U>(self, other: U) -> Zip<Self, <U as IntoIterator>::IntoIter>
where\n Self: Sized,\n U: IntoIterator,

‘Zips up’ two iterators into a single iterator of pairs. Read more
source§

fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
where\n Self: Sized,\n G: FnMut() -> Self::Item,

🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator\nbetween adjacent items of the original iterator. Read more
1.0.0 · source§

fn map<B, F>(self, f: F) -> Map<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each\nelement. Read more
1.21.0 · source§

fn for_each<F>(self, f: F)
where\n Self: Sized,\n F: FnMut(Self::Item),

Calls a closure on each element of an iterator. Read more
1.0.0 · source§

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator which uses a closure to determine if an element\nshould be yielded. Read more
1.0.0 · source§

fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both filters and maps. Read more
1.0.0 · source§

fn enumerate(self) -> Enumerate<Self>
where\n Self: Sized,

Creates an iterator which gives the current iteration count as well as\nthe next value. Read more
1.0.0 · source§

fn peekable(self) -> Peekable<Self>
where\n Self: Sized,

Creates an iterator which can use the peek and peek_mut methods\nto look at the next element of the iterator without consuming it. See\ntheir documentation for more information. Read more
1.0.0 · source§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that skips elements based on a predicate. Read more
1.0.0 · source§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Creates an iterator that yields elements based on a predicate. Read more
1.57.0 · source§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
where\n Self: Sized,\n P: FnMut(Self::Item) -> Option<B>,

Creates an iterator that both yields elements based on a predicate and maps. Read more
1.0.0 · source§

fn skip(self, n: usize) -> Skip<Self>
where\n Self: Sized,

Creates an iterator that skips the first n elements. Read more
1.0.0 · source§

fn take(self, n: usize) -> Take<Self>
where\n Self: Sized,

Creates an iterator that yields the first n elements, or fewer\nif the underlying iterator ends sooner. Read more
1.0.0 · source§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where\n Self: Sized,\n F: FnMut(&mut St, Self::Item) -> Option<B>,

An iterator adapter which, like fold, holds internal state, but\nunlike fold, produces a new iterator. Read more
1.0.0 · source§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where\n Self: Sized,\n U: IntoIterator,\n F: FnMut(Self::Item) -> U,

Creates an iterator that works like map, but flattens nested structure. Read more
source§

fn map_windows<F, R, const N: usize>(self, f: F) -> MapWindows<Self, F, N>
where\n Self: Sized,\n F: FnMut(&[Self::Item; N]) -> R,

🔬This is a nightly-only experimental API. (iter_map_windows)
Calls the given function f for each contiguous window of size N over\nself and returns an iterator over the outputs of f. Like slice::windows(),\nthe windows during mapping overlap as well. Read more
1.0.0 · source§

fn fuse(self) -> Fuse<Self>
where\n Self: Sized,

Creates an iterator which ends after the first None. Read more
1.0.0 · source§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where\n Self: Sized,\n F: FnMut(&Self::Item),

Does something with each element of an iterator, passing the value on. Read more
1.0.0 · source§

fn by_ref(&mut self) -> &mut Self
where\n Self: Sized,

Borrows an iterator, rather than consuming it. Read more
1.0.0 · source§

fn collect<B>(self) -> B
where\n B: FromIterator<Self::Item>,\n Self: Sized,

Transforms an iterator into a collection. Read more
source§

fn collect_into<E>(self, collection: &mut E) -> &mut E
where\n E: Extend<Self::Item>,\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
1.0.0 · source§

fn partition<B, F>(self, f: F) -> (B, B)
where\n Self: Sized,\n B: Default + Extend<Self::Item>,\n F: FnMut(&Self::Item) -> bool,

Consumes an iterator, creating two collections from it. Read more
source§

fn is_partitioned<P>(self, predicate: P) -> bool
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate,\nsuch that all those that return true precede all those that return false. Read more
1.27.0 · source§

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

An iterator method that applies a function as long as it returns\nsuccessfully, producing a single, final value. Read more
1.27.0 · source§

fn try_for_each<F, R>(&mut self, f: F) -> R
where\n Self: Sized,\n F: FnMut(Self::Item) -> R,\n R: Try<Output = ()>,

An iterator method that applies a fallible function to each item in the\niterator, stopping at the first error and returning that error. Read more
1.0.0 · source§

fn fold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

Folds every element into an accumulator by applying an operation,\nreturning the final result. Read more
1.51.0 · source§

fn reduce<F>(self, f: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(Self::Item, Self::Item) -> Self::Item,

Reduces the elements to a single one, by repeatedly applying a reducing\noperation. Read more
source§

fn try_reduce<F, R>(\n &mut self,\n f: F\n) -> <<R as Try>::Residual as Residual<Option<<R as Try>::Output>>>::TryType
where\n Self: Sized,\n F: FnMut(Self::Item, Self::Item) -> R,\n R: Try<Output = Self::Item>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the\nclosure returns a failure, the failure is propagated back to the caller immediately. Read more
1.0.0 · source§

fn all<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if every element of the iterator matches a predicate. Read more
1.0.0 · source§

fn any<F>(&mut self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> bool,

Tests if any element of the iterator matches a predicate. Read more
1.0.0 · source§

fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator that satisfies a predicate. Read more
1.30.0 · source§

fn find_map<B, F>(&mut self, f: F) -> Option<B>
where\n Self: Sized,\n F: FnMut(Self::Item) -> Option<B>,

Applies function to the elements of iterator and returns\nthe first non-none result. Read more
source§

fn try_find<F, R>(\n &mut self,\n f: F\n) -> <<R as Try>::Residual as Residual<Option<Self::Item>>>::TryType
where\n Self: Sized,\n F: FnMut(&Self::Item) -> R,\n R: Try<Output = bool>,\n <R as Try>::Residual: Residual<Option<Self::Item>>,

🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns\nthe first true result or the first error. Read more
1.0.0 · source§

fn position<P>(&mut self, predicate: P) -> Option<usize>
where\n Self: Sized,\n P: FnMut(Self::Item) -> bool,

Searches for an element in an iterator, returning its index. Read more
1.6.0 · source§

fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the maximum value from the\nspecified function. Read more
1.15.0 · source§

fn max_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the maximum value with respect to the\nspecified comparison function. Read more
1.6.0 · source§

fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
where\n B: Ord,\n Self: Sized,\n F: FnMut(&Self::Item) -> B,

Returns the element that gives the minimum value from the\nspecified function. Read more
1.15.0 · source§

fn min_by<F>(self, compare: F) -> Option<Self::Item>
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Ordering,

Returns the element that gives the minimum value with respect to the\nspecified comparison function. Read more
1.0.0 · source§

fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
where\n FromA: Default + Extend<A>,\n FromB: Default + Extend<B>,\n Self: Sized + Iterator<Item = (A, B)>,

Converts an iterator of pairs into a pair of containers. Read more
1.36.0 · source§

fn copied<'a, T>(self) -> Copied<Self>
where\n T: 'a + Copy,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which copies all of its elements. Read more
1.0.0 · source§

fn cloned<'a, T>(self) -> Cloned<Self>
where\n T: 'a + Clone,\n Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements. Read more
source§

fn array_chunks<const N: usize>(self) -> ArrayChunks<Self, N>
where\n Self: Sized,

🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
1.11.0 · source§

fn sum<S>(self) -> S
where\n Self: Sized,\n S: Sum<Self::Item>,

Sums the elements of an iterator. Read more
1.11.0 · source§

fn product<P>(self) -> P
where\n Self: Sized,\n P: Product<Self::Item>,

Iterates over the entire iterator, multiplying all the elements Read more
source§

fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.5.0 · source§

fn partial_cmp<I>(self, other: I) -> Option<Ordering>
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Lexicographically compares the PartialOrd elements of\nthis Iterator with those of another. The comparison works like short-circuit\nevaluation, returning a result without comparing the remaining elements.\nAs soon as an order can be determined, the evaluation stops and a result is returned. Read more
source§

fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those\nof another with respect to the specified comparison function. Read more
1.5.0 · source§

fn eq<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are equal to those of\nanother. Read more
source§

fn eq_by<I, F>(self, other: I, eq: F) -> bool
where\n Self: Sized,\n I: IntoIterator,\n F: FnMut(Self::Item, <I as IntoIterator>::Item) -> bool,

🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this Iterator are equal to those of\nanother with respect to the specified equality function. Read more
1.5.0 · source§

fn ne<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialEq<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are not equal to those of\nanother. Read more
1.5.0 · source§

fn lt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless than those of another. Read more
1.5.0 · source§

fn le<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\nless or equal to those of another. Read more
1.5.0 · source§

fn gt<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than those of another. Read more
1.5.0 · source§

fn ge<I>(self, other: I) -> bool
where\n I: IntoIterator,\n Self::Item: PartialOrd<<I as IntoIterator>::Item>,\n Self: Sized,

Determines if the elements of this Iterator are lexicographically\ngreater than or equal to those of another. Read more
source§

fn is_sorted_by<F>(self, compare: F) -> bool
where\n Self: Sized,\n F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
source§

fn is_sorted_by_key<F, K>(self, f: F) -> bool
where\n Self: Sized,\n F: FnMut(Self::Item) -> K,\n K: PartialOrd,

🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction\nfunction. Read more
","Iterator","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.22.0 · source§

impl<T, A> Hasher for Box<T, A>
where\n T: Hasher + ?Sized,\n A: Allocator,

source§

fn finish(&self) -> u64

Returns the hash value for the values written so far. Read more
source§

fn write(&mut self, bytes: &[u8])

Writes some data into this Hasher. Read more
source§

fn write_u8(&mut self, i: u8)

Writes a single u8 into this hasher.
source§

fn write_u16(&mut self, i: u16)

Writes a single u16 into this hasher.
source§

fn write_u32(&mut self, i: u32)

Writes a single u32 into this hasher.
source§

fn write_u64(&mut self, i: u64)

Writes a single u64 into this hasher.
source§

fn write_u128(&mut self, i: u128)

Writes a single u128 into this hasher.
source§

fn write_usize(&mut self, i: usize)

Writes a single usize into this hasher.
source§

fn write_i8(&mut self, i: i8)

Writes a single i8 into this hasher.
source§

fn write_i16(&mut self, i: i16)

Writes a single i16 into this hasher.
source§

fn write_i32(&mut self, i: i32)

Writes a single i32 into this hasher.
source§

fn write_i64(&mut self, i: i64)

Writes a single i64 into this hasher.
source§

fn write_i128(&mut self, i: i128)

Writes a single i128 into this hasher.
source§

fn write_isize(&mut self, i: isize)

Writes a single isize into this hasher.
source§

fn write_length_prefix(&mut self, len: usize)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a length prefix into this hasher, as part of being prefix-free. Read more
source§

fn write_str(&mut self, s: &str)

🔬This is a nightly-only experimental API. (hasher_prefixfree_extras)
Writes a single str into this hasher. Read more
","Hasher","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.8.0 · source§

impl<T> Error for Box<T>
where\n T: Error,

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
source§

fn provide<'b>(&'b self, request: &mut Request<'b>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
","Error","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.35.0 · source§

impl<Args, F, A> FnMut<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnMut<Args> + ?Sized,\n A: Allocator,

source§

extern "rust-call" fn call_mut(\n &mut self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnMut","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<S> AsyncIterator for Box<S>
where\n S: AsyncIterator + Unpin + ?Sized,

§

type Item = <S as AsyncIterator>::Item

🔬This is a nightly-only experimental API. (async_iterator)
The type of items yielded by the async iterator.
source§

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Box<S> as AsyncIterator>::Item>>

🔬This is a nightly-only experimental API. (async_iterator)
Attempt to pull out the next value of this async iterator, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the async iterator is exhausted. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (async_iterator)
Returns the bounds on the remaining length of the async iterator. Read more
","AsyncIterator","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Pointer for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
","Pointer","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> PartialOrd for Box<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

source§

fn partial_cmp(&self, other: &Box<T, A>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
source§

fn lt(&self, other: &Box<T, A>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
source§

fn le(&self, other: &Box<T, A>) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
source§

fn ge(&self, other: &Box<T, A>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
source§

fn gt(&self, other: &Box<T, A>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
","PartialOrd","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Deref for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
","Deref","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Ord for Box<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

source§

fn cmp(&self, other: &Box<T, A>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.6.0 · source§

impl<T> From<T> for Box<T>

source§

fn from(t: T) -> Box<T>

Converts a T into a Box<T>

\n

The conversion allocates on the heap and moves t\nfrom the stack into it.

\n
Examples
\n
let x = 5;\nlet boxed = Box::new(5);\n\nassert_eq!(Box::from(x), boxed);
\n
","From","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Drop for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
","Drop","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T, U, A> CoerceUnsized<Box<U, A>> for Box<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.35.0 · source§

impl<Args, F, A> Fn<Args> for Box<F, A>
where\n Args: Tuple,\n F: Fn<Args> + ?Sized,\n A: Allocator,

source§

extern "rust-call" fn call(\n &self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","Fn","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.26.0 · source§

impl<I, A> FusedIterator for Box<I, A>
where\n I: FusedIterator + ?Sized,\n A: Allocator,

","FusedIterator","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.5.0 · source§

impl<T, A> AsRef<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.1.0 · source§

impl<T, A> Borrow<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Hash for Box<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

source§

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.5.0 · source§

impl<T, A> AsMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
","AsMut","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Clone for Box<T, A>
where\n T: Clone,\n A: Allocator + Clone,

source§

fn clone(&self) -> Box<T, A>

Returns a new box with a clone() of this box’s contents.

\n
Examples
\n
let x = Box::new(5);\nlet y = x.clone();\n\n// The value is the same\nassert_eq!(x, y);\n\n// But they are unique objects\nassert_ne!(&*x as *const i32, &*y as *const i32);
\n
source§

fn clone_from(&mut self, source: &Box<T, A>)

Copies source’s contents into self without creating a new allocation.

\n
Examples
\n
let x = Box::new(5);\nlet mut y = Box::new(10);\nlet yp: *const i32 = &*y;\n\ny.clone_from(&x);\n\n// The value is the same\nassert_eq!(x, y);\n\n// And no allocation occurred\nassert_eq!(yp, &*y);
\n
","Clone","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Display for Box<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<I, A> DoubleEndedIterator for Box<I, A>
where\n I: DoubleEndedIterator + ?Sized,\n A: Allocator,

source§

fn next_back(&mut self) -> Option<<I as Iterator>::Item>

Removes and returns an element from the end of the iterator. Read more
source§

fn nth_back(&mut self, n: usize) -> Option<<I as Iterator>::Item>

Returns the nth element from the end of the iterator. Read more
source§

fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize>

🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator from the back by n elements. Read more
1.27.0 · source§

fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> R,\n R: Try<Output = B>,

This is the reverse version of Iterator::try_fold(): it takes\nelements starting from the back of the iterator. Read more
1.27.0 · source§

fn rfold<B, F>(self, init: B, f: F) -> B
where\n Self: Sized,\n F: FnMut(B, Self::Item) -> B,

An iterator method that reduces the iterator’s elements to a single,\nfinal value, starting from the back. Read more
1.27.0 · source§

fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item>
where\n Self: Sized,\n P: FnMut(&Self::Item) -> bool,

Searches for an element of an iterator from the back that satisfies a predicate. Read more
","DoubleEndedIterator","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<G, R, A> Coroutine<R> for Box<G, A>
where\n G: Coroutine<R> + Unpin + ?Sized,\n A: Allocator + 'static,

§

type Yield = <G as Coroutine<R>>::Yield

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine yields. Read more
§

type Return = <G as Coroutine<R>>::Return

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine returns. Read more
source§

fn resume(\n self: Pin<&mut Box<G, A>>,\n arg: R\n) -> CoroutineState<<Box<G, A> as Coroutine<R>>::Yield, <Box<G, A> as Coroutine<R>>::Return>

🔬This is a nightly-only experimental API. (coroutine_trait)
Resumes the execution of this coroutine. Read more
","Coroutine","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Eq for Box<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.1.0 · source§

impl<T, A> BorrowMut<T> for Box<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
","BorrowMut","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.35.0 · source§

impl<Args, F, A> FnOnce<Args> for Box<F, A>
where\n Args: Tuple,\n F: FnOnce<Args> + ?Sized,\n A: Allocator,

§

type Output = <F as FnOnce<Args>>::Output

The returned type after the call operator is used.
source§

extern "rust-call" fn call_once(\n self,\n args: Args\n) -> <Box<F, A> as FnOnce<Args>>::Output

🔬This is a nightly-only experimental API. (fn_traits)
Performs the call operation.
","FnOnce","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T> Default for Box<T>
where\n T: Default,

source§

fn default() -> Box<T>

Creates a Box<T>, with the Default value for T.

\n
","Default","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> Debug for Box<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
1.0.0 · source§

impl<T, A> PartialEq for Box<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

source§

fn eq(&self, other: &Box<T, A>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &Box<T, A>) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T> Encode for Box<T>
where\n T: Encode + ?Sized,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<'de, T> BorrowDecode<'de> for Box<T>
where\n T: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Box<T>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<T> Decode for Box<T>
where\n T: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Box<T>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<S> Stream for Box<S>
where\n S: Stream + Unpin + ?Sized,

§

type Item = <S as Stream>::Item

Values yielded by the stream.
§

fn poll_next(\n self: Pin<&mut Box<S>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Box<S> as Stream>::Item>>

Attempt to pull out the next value of this stream, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the stream is exhausted. Read more
§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
","Stream","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<F> FusedFuture for Box<F>
where\n F: FusedFuture + Unpin + ?Sized,

§

fn is_terminated(&self) -> bool

Returns true if the underlying future should no longer be polled.
","FusedFuture","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<S> FusedStream for Box<S>
where\n S: FusedStream + Unpin + ?Sized,

§

fn is_terminated(&self) -> bool

Returns true if the stream should no longer be polled.
","FusedStream","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> AsyncWrite for Box<T>
where\n T: AsyncWrite + Unpin + ?Sized,

§

fn poll_write(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n buf: &[u8]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
§

fn poll_write_vectored(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n bufs: &[IoSlice<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from bufs into the object using vectored\nIO operations. Read more
§

fn poll_flush(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to flush the object, ensuring that any buffered data reach\ntheir destination. Read more
§

fn poll_close(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to close the object. Read more
","AsyncWrite","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> AsyncRead for Box<T>
where\n T: AsyncRead + Unpin + ?Sized,

§

fn poll_read(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n buf: &mut [u8]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into buf. Read more
§

fn poll_read_vectored(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n bufs: &mut [IoSliceMut<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into bufs using vectored\nIO operations. Read more
","AsyncRead","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> AsyncSeek for Box<T>
where\n T: AsyncSeek + Unpin + ?Sized,

§

fn poll_seek(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>,\n pos: SeekFrom\n) -> Poll<Result<u64, Error>>

Attempt to seek to an offset, in bytes, in a stream. Read more
","AsyncSeek","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> AsyncBufRead for Box<T>
where\n T: AsyncBufRead + Unpin + ?Sized,

§

fn poll_fill_buf(\n self: Pin<&mut Box<T>>,\n cx: &mut Context<'_>\n) -> Poll<Result<&[u8], Error>>

Attempt to return the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
§

fn consume(self: Pin<&mut Box<T>>, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to poll_read. Read more
","AsyncBufRead","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> IoSafe for Box<T>
where\n T: IoSafe + ?Sized,

","IoSafe","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<S> Subscriber for Box<S>
where\n S: Subscriber + ?Sized,

§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this subscriber, returning whether or not\nthe subscriber is interested in being notified about the callsite. Read more
§

fn enabled(&self, metadata: &Metadata<'_>) -> bool

Returns true if a span or event with the specified metadata would be\nrecorded. Read more
§

fn max_level_hint(&self) -> Option<LevelFilter>

Returns the highest verbosity level that this Subscriber will\nenable, or None, if the subscriber does not implement level-based\nfiltering or chooses not to implement this method. Read more
§

fn new_span(&self, span: &Attributes<'_>) -> Id

Visit the construction of a new span, returning a new span ID for the\nspan being constructed. Read more
§

fn record(&self, span: &Id, values: &Record<'_>)

Record a set of values on a span. Read more
§

fn record_follows_from(&self, span: &Id, follows: &Id)

Adds an indication that span follows from the span with the id\nfollows. Read more
§

fn event_enabled(&self, event: &Event<'_>) -> bool

Determine if an [Event] should be recorded. Read more
§

fn event(&self, event: &Event<'_>)

Records that an Event has occurred. Read more
§

fn enter(&self, span: &Id)

Records that a span has been entered. Read more
§

fn exit(&self, span: &Id)

Records that a span has been exited. Read more
§

fn clone_span(&self, id: &Id) -> Id

Notifies the subscriber that a span ID has been cloned. Read more
§

fn try_close(&self, id: Id) -> bool

Notifies the subscriber that a span ID has been dropped, and returns\ntrue if there are now 0 IDs that refer to that span. Read more
§

fn drop_span(&self, id: Id)

👎Deprecated since 0.1.2: use Subscriber::try_close instead
This method is deprecated. Read more
§

fn current_span(&self) -> Current

Returns a type representing this subscriber’s view of the current span. Read more
§

unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()>

If self is the same type as the provided TypeId, returns an untyped\n*const pointer to that type. Otherwise, returns None. Read more
§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Invoked when this subscriber becomes a [Dispatch]. Read more
","Subscriber","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
§

impl<T> Value for Box<T>
where\n T: Value + ?Sized,

§

fn record(&self, key: &Field, visitor: &mut dyn Visit)

Visits this value with the given Visitor.
","Value","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<R> CryptoRng for Box<R>
where\n R: CryptoRng + ?Sized,

","CryptoRng","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl<R> RngCore for Box<R>
where\n R: RngCore + ?Sized,

source§

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
source§

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data. Read more
source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>

Fill dest entirely with random data. Read more
","RngCore","karyon_net::connection::Conn","karyon_net::listener::Listener"],["
source§

impl From<UnixListener> for Box<dyn ConnListener>

source§

fn from(listener: UnixListener) -> Self

Converts to this type from the input type.
","From","karyon_net::listener::Listener"],["
source§

impl From<TcpStream> for Box<dyn Connection>

source§

fn from(conn: TcpStream) -> Self

Converts to this type from the input type.
","From","karyon_net::connection::Conn"],["
source§

impl From<TlsListener> for Box<dyn ConnListener>

source§

fn from(listener: TlsListener) -> Self

Converts to this type from the input type.
","From","karyon_net::listener::Listener"],["
source§

impl From<UdpSocket> for Box<dyn Connection>

source§

fn from(conn: UdpSocket) -> Self

Converts to this type from the input type.
","From","karyon_net::connection::Conn"],["
source§

impl From<UnixStream> for Box<dyn Connection>

source§

fn from(conn: UnixStream) -> Self

Converts to this type from the input type.
","From","karyon_net::connection::Conn"],["
source§

impl From<TlsStream<TcpStream>> for Box<dyn Connection>

source§

fn from(conn: TlsStream<TcpStream>) -> Self

Converts to this type from the input type.
","From>","karyon_net::connection::Conn"],["
source§

impl From<TcpListener> for Box<dyn ConnListener>

source§

fn from(listener: TcpListener) -> Self

Converts to this type from the input type.
","From","karyon_net::listener::Listener"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/alloc/string/struct.String.js b/type.impl/alloc/string/struct.String.js new file mode 100644 index 00000000..b66919fe --- /dev/null +++ b/type.impl/alloc/string/struct.String.js @@ -0,0 +1,3 @@ +(function() {var type_impls = { +"karyon_p2p":[["
source§

impl String

1.0.0 (const: 1.39.0) · source

pub const fn new() -> String

Creates a new empty String.

\n

Given that the String is empty, this will not allocate any initial\nbuffer. While that means that this initial operation is very\ninexpensive, it may cause excessive allocation later when you add\ndata. If you have an idea of how much data the String will hold,\nconsider the with_capacity method to prevent excessive\nre-allocation.

\n
Examples
\n
let s = String::new();
\n
1.0.0 · source

pub fn with_capacity(capacity: usize) -> String

Creates a new empty String with at least the specified capacity.

\n

Strings have an internal buffer to hold their data. The capacity is\nthe length of that buffer, and can be queried with the capacity\nmethod. This method creates an empty String, but one with an initial\nbuffer that can hold at least capacity bytes. This is useful when you\nmay be appending a bunch of data to the String, reducing the number of\nreallocations it needs to do.

\n

If the given capacity is 0, no allocation will occur, and this method\nis identical to the new method.

\n
Examples
\n
let mut s = String::with_capacity(10);\n\n// The String contains no chars, even though it has capacity for more\nassert_eq!(s.len(), 0);\n\n// These are all done without reallocating...\nlet cap = s.capacity();\nfor _ in 0..10 {\n    s.push('a');\n}\n\nassert_eq!(s.capacity(), cap);\n\n// ...but this may make the string reallocate\ns.push('a');
\n
1.0.0 · source

pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>

Converts a vector of bytes to a String.

\n

A string (String) is made of bytes (u8), and a vector of bytes\n(Vec<u8>) is made of bytes, so this function converts between the\ntwo. Not all byte slices are valid Strings, however: String\nrequires that it is valid UTF-8. from_utf8() checks to ensure that\nthe bytes are valid UTF-8, and then does the conversion.

\n

If you are sure that the byte slice is valid UTF-8, and you don’t want\nto incur the overhead of the validity check, there is an unsafe version\nof this function, from_utf8_unchecked, which has the same behavior\nbut skips the check.

\n

This method will take care to not copy the vector, for efficiency’s\nsake.

\n

If you need a &str instead of a String, consider\nstr::from_utf8.

\n

The inverse of this method is into_bytes.

\n
Errors
\n

Returns Err if the slice is not UTF-8 with a description as to why the\nprovided bytes are not UTF-8. The vector you moved in is also included.

\n
Examples
\n

Basic usage:

\n\n
// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\n// We know these bytes are valid, so we'll use `unwrap()`.\nlet sparkle_heart = String::from_utf8(sparkle_heart).unwrap();\n\nassert_eq!(\"💖\", sparkle_heart);
\n

Incorrect bytes:

\n\n
// some invalid bytes, in a vector\nlet sparkle_heart = vec![0, 159, 146, 150];\n\nassert!(String::from_utf8(sparkle_heart).is_err());
\n

See the docs for FromUtf8Error for more details on what you can do\nwith this error.

\n
1.0.0 · source

pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>

Converts a slice of bytes to a string, including invalid characters.

\n

Strings are made of bytes (u8), and a slice of bytes\n(&[u8]) is made of bytes, so this function converts\nbetween the two. Not all byte slices are valid strings, however: strings\nare required to be valid UTF-8. During this conversion,\nfrom_utf8_lossy() will replace any invalid UTF-8 sequences with\nU+FFFD REPLACEMENT CHARACTER, which looks like this: �

\n

If you are sure that the byte slice is valid UTF-8, and you don’t want\nto incur the overhead of the conversion, there is an unsafe version\nof this function, from_utf8_unchecked, which has the same behavior\nbut skips the checks.

\n

This function returns a Cow<'a, str>. If our byte slice is invalid\nUTF-8, then we need to insert the replacement characters, which will\nchange the size of the string, and hence, require a String. But if\nit’s already valid UTF-8, we don’t need a new allocation. This return\ntype allows us to handle both cases.

\n
Examples
\n

Basic usage:

\n\n
// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\nlet sparkle_heart = String::from_utf8_lossy(&sparkle_heart);\n\nassert_eq!(\"💖\", sparkle_heart);
\n

Incorrect bytes:

\n\n
// some invalid bytes\nlet input = b\"Hello \\xF0\\x90\\x80World\";\nlet output = String::from_utf8_lossy(input);\n\nassert_eq!(\"Hello �World\", output);
\n
1.0.0 · source

pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>

Decode a UTF-16–encoded vector v into a String, returning Err\nif v contains any invalid data.

\n
Examples
\n
// 𝄞music\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n          0x0073, 0x0069, 0x0063];\nassert_eq!(String::from(\"𝄞music\"),\n           String::from_utf16(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n          0xD800, 0x0069, 0x0063];\nassert!(String::from_utf16(v).is_err());
\n
1.0.0 · source

pub fn from_utf16_lossy(v: &[u16]) -> String

Decode a UTF-16–encoded slice v into a String, replacing\ninvalid data with the replacement character (U+FFFD).

\n

Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.

\n
Examples
\n
// 𝄞mus<invalid>ic<invalid>\nlet v = &[0xD834, 0xDD1E, 0x006d, 0x0075,\n          0x0073, 0xDD1E, 0x0069, 0x0063,\n          0xD834];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n           String::from_utf16_lossy(v));
\n
source

pub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error>

🔬This is a nightly-only experimental API. (str_from_utf16_endian)

Decode a UTF-16LE–encoded vector v into a String, returning Err\nif v contains any invalid data.

\n
Examples
\n

Basic usage:

\n\n
#![feature(str_from_utf16_endian)]\n// 𝄞music\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n          0x73, 0x00, 0x69, 0x00, 0x63, 0x00];\nassert_eq!(String::from(\"𝄞music\"),\n           String::from_utf16le(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n          0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];\nassert!(String::from_utf16le(v).is_err());
\n
source

pub fn from_utf16le_lossy(v: &[u8]) -> String

🔬This is a nightly-only experimental API. (str_from_utf16_endian)

Decode a UTF-16LE–encoded slice v into a String, replacing\ninvalid data with the replacement character (U+FFFD).

\n

Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16le_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.

\n
Examples
\n

Basic usage:

\n\n
#![feature(str_from_utf16_endian)]\n// 𝄞mus<invalid>ic<invalid>\nlet v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,\n          0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,\n          0x34, 0xD8];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n           String::from_utf16le_lossy(v));
\n
source

pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>

🔬This is a nightly-only experimental API. (str_from_utf16_endian)

Decode a UTF-16BE–encoded vector v into a String, returning Err\nif v contains any invalid data.

\n
Examples
\n

Basic usage:

\n\n
#![feature(str_from_utf16_endian)]\n// 𝄞music\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n          0x00, 0x73, 0x00, 0x69, 0x00, 0x63];\nassert_eq!(String::from(\"𝄞music\"),\n           String::from_utf16be(v).unwrap());\n\n// 𝄞mu<invalid>ic\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n          0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];\nassert!(String::from_utf16be(v).is_err());
\n
source

pub fn from_utf16be_lossy(v: &[u8]) -> String

🔬This is a nightly-only experimental API. (str_from_utf16_endian)

Decode a UTF-16BE–encoded slice v into a String, replacing\ninvalid data with the replacement character (U+FFFD).

\n

Unlike from_utf8_lossy which returns a Cow<'a, str>,\nfrom_utf16le_lossy returns a String since the UTF-16 to UTF-8\nconversion requires a memory allocation.

\n
Examples
\n

Basic usage:

\n\n
#![feature(str_from_utf16_endian)]\n// 𝄞mus<invalid>ic<invalid>\nlet v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,\n          0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,\n          0xD8, 0x34];\n\nassert_eq!(String::from(\"𝄞mus\\u{FFFD}ic\\u{FFFD}\"),\n           String::from_utf16be_lossy(v));
\n
source

pub fn into_raw_parts(self) -> (*mut u8, usize, usize)

🔬This is a nightly-only experimental API. (vec_into_raw_parts)

Decomposes a String into its raw components.

\n

Returns the raw pointer to the underlying data, the length of\nthe string (in bytes), and the allocated capacity of the data\n(in bytes). These are the same arguments in the same order as\nthe arguments to from_raw_parts.

\n

After calling this function, the caller is responsible for the\nmemory previously managed by the String. The only way to do\nthis is to convert the raw pointer, length, and capacity back\ninto a String with the from_raw_parts function, allowing\nthe destructor to perform the cleanup.

\n
Examples
\n
#![feature(vec_into_raw_parts)]\nlet s = String::from(\"hello\");\n\nlet (ptr, len, cap) = s.into_raw_parts();\n\nlet rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };\nassert_eq!(rebuilt, \"hello\");
\n
1.0.0 · source

pub unsafe fn from_raw_parts(\n buf: *mut u8,\n length: usize,\n capacity: usize\n) -> String

Creates a new String from a length, capacity, and pointer.

\n
Safety
\n

This is highly unsafe, due to the number of invariants that aren’t\nchecked:

\n
    \n
  • The memory at buf needs to have been previously allocated by the\nsame allocator the standard library uses, with a required alignment of exactly 1.
  • \n
  • length needs to be less than or equal to capacity.
  • \n
  • capacity needs to be the correct value.
  • \n
  • The first length bytes at buf need to be valid UTF-8.
  • \n
\n

Violating these may cause problems like corrupting the allocator’s\ninternal data structures. For example, it is normally not safe to\nbuild a String from a pointer to a C char array containing UTF-8\nunless you are certain that array was originally allocated by the\nRust standard library’s allocator.

\n

The ownership of buf is effectively transferred to the\nString which may then deallocate, reallocate or change the\ncontents of memory pointed to by the pointer at will. Ensure\nthat nothing else uses the pointer after calling this\nfunction.

\n
Examples
\n
use std::mem;\n\nunsafe {\n    let s = String::from(\"hello\");\n\n    // Prevent automatically dropping the String's data\n    let mut s = mem::ManuallyDrop::new(s);\n\n    let ptr = s.as_mut_ptr();\n    let len = s.len();\n    let capacity = s.capacity();\n\n    let s = String::from_raw_parts(ptr, len, capacity);\n\n    assert_eq!(String::from(\"hello\"), s);\n}
\n
1.0.0 · source

pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String

Converts a vector of bytes to a String without checking that the\nstring contains valid UTF-8.

\n

See the safe version, from_utf8, for more details.

\n
Safety
\n

This function is unsafe because it does not check that the bytes passed\nto it are valid UTF-8. If this constraint is violated, it may cause\nmemory unsafety issues with future users of the String, as the rest of\nthe standard library assumes that Strings are valid UTF-8.

\n
Examples
\n
// some bytes, in a vector\nlet sparkle_heart = vec![240, 159, 146, 150];\n\nlet sparkle_heart = unsafe {\n    String::from_utf8_unchecked(sparkle_heart)\n};\n\nassert_eq!(\"💖\", sparkle_heart);
\n
1.0.0 · source

pub fn into_bytes(self) -> Vec<u8>

Converts a String into a byte vector.

\n

This consumes the String, so we do not need to copy its contents.

\n
Examples
\n
let s = String::from(\"hello\");\nlet bytes = s.into_bytes();\n\nassert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
\n
1.7.0 · source

pub fn as_str(&self) -> &str

Extracts a string slice containing the entire String.

\n
Examples
\n
let s = String::from(\"foo\");\n\nassert_eq!(\"foo\", s.as_str());
\n
1.7.0 · source

pub fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

\n
Examples
\n
let mut s = String::from(\"foobar\");\nlet s_mut_str = s.as_mut_str();\n\ns_mut_str.make_ascii_uppercase();\n\nassert_eq!(\"FOOBAR\", s_mut_str);
\n
1.0.0 · source

pub fn push_str(&mut self, string: &str)

Appends a given string slice onto the end of this String.

\n
Examples
\n
let mut s = String::from(\"foo\");\n\ns.push_str(\"bar\");\n\nassert_eq!(\"foobar\", s);
\n
source

pub fn extend_from_within<R>(&mut self, src: R)
where\n R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (string_extend_from_within)

Copies elements from src range to the end of the string.

\n
Panics
\n

Panics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.

\n
Examples
\n
#![feature(string_extend_from_within)]\nlet mut string = String::from(\"abcde\");\n\nstring.extend_from_within(2..);\nassert_eq!(string, \"abcdecde\");\n\nstring.extend_from_within(..2);\nassert_eq!(string, \"abcdecdeab\");\n\nstring.extend_from_within(4..8);\nassert_eq!(string, \"abcdecdeabecde\");
\n
1.0.0 · source

pub fn capacity(&self) -> usize

Returns this String’s capacity, in bytes.

\n
Examples
\n
let s = String::with_capacity(10);\n\nassert!(s.capacity() >= 10);
\n
1.0.0 · source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional bytes more than the\ncurrent length. The allocator may reserve more space to speculatively\navoid frequent allocations. After calling reserve,\ncapacity will be greater than or equal to self.len() + additional.\nDoes nothing if capacity is already sufficient.

\n
Panics
\n

Panics if the new capacity overflows usize.

\n
Examples
\n

Basic usage:

\n\n
let mut s = String::new();\n\ns.reserve(10);\n\nassert!(s.capacity() >= 10);
\n

This might not actually increase the capacity:

\n\n
let mut s = String::with_capacity(10);\ns.push('a');\ns.push('b');\n\n// s now has a length of 2 and a capacity of at least 10\nlet capacity = s.capacity();\nassert_eq!(2, s.len());\nassert!(capacity >= 10);\n\n// Since we already have at least an extra 8 capacity, calling this...\ns.reserve(8);\n\n// ... doesn't actually increase.\nassert_eq!(capacity, s.capacity());
\n
1.0.0 · source

pub fn reserve_exact(&mut self, additional: usize)

Reserves the minimum capacity for at least additional bytes more than\nthe current length. Unlike reserve, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling reserve_exact, capacity will be greater than or equal to\nself.len() + additional. Does nothing if the capacity is already\nsufficient.

\n
Panics
\n

Panics if the new capacity overflows usize.

\n
Examples
\n

Basic usage:

\n\n
let mut s = String::new();\n\ns.reserve_exact(10);\n\nassert!(s.capacity() >= 10);
\n

This might not actually increase the capacity:

\n\n
let mut s = String::with_capacity(10);\ns.push('a');\ns.push('b');\n\n// s now has a length of 2 and a capacity of at least 10\nlet capacity = s.capacity();\nassert_eq!(2, s.len());\nassert!(capacity >= 10);\n\n// Since we already have at least an extra 8 capacity, calling this...\ns.reserve_exact(8);\n\n// ... doesn't actually increase.\nassert_eq!(capacity, s.capacity());
\n
1.57.0 · source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional bytes more than the\ncurrent length. The allocator may reserve more space to speculatively\navoid frequent allocations. After calling try_reserve, capacity will be\ngreater than or equal to self.len() + additional if it returns\nOk(()). Does nothing if capacity is already sufficient. This method\npreserves the contents even if an error occurs.

\n
Errors
\n

If the capacity overflows, or the allocator reports a failure, then an error\nis returned.

\n
Examples
\n
use std::collections::TryReserveError;\n\nfn process_data(data: &str) -> Result<String, TryReserveError> {\n    let mut output = String::new();\n\n    // Pre-reserve the memory, exiting if we can't\n    output.try_reserve(data.len())?;\n\n    // Now we know this can't OOM in the middle of our complex work\n    output.push_str(data);\n\n    Ok(output)\n}
\n
1.57.0 · source

pub fn try_reserve_exact(\n &mut self,\n additional: usize\n) -> Result<(), TryReserveError>

Tries to reserve the minimum capacity for at least additional bytes\nmore than the current length. Unlike try_reserve, this will not\ndeliberately over-allocate to speculatively avoid frequent allocations.\nAfter calling try_reserve_exact, capacity will be greater than or\nequal to self.len() + additional if it returns Ok(()).\nDoes nothing if the capacity is already sufficient.

\n

Note that the allocator may give the collection more space than it\nrequests. Therefore, capacity can not be relied upon to be precisely\nminimal. Prefer try_reserve if future insertions are expected.

\n
Errors
\n

If the capacity overflows, or the allocator reports a failure, then an error\nis returned.

\n
Examples
\n
use std::collections::TryReserveError;\n\nfn process_data(data: &str) -> Result<String, TryReserveError> {\n    let mut output = String::new();\n\n    // Pre-reserve the memory, exiting if we can't\n    output.try_reserve_exact(data.len())?;\n\n    // Now we know this can't OOM in the middle of our complex work\n    output.push_str(data);\n\n    Ok(output)\n}
\n
1.0.0 · source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of this String to match its length.

\n
Examples
\n
let mut s = String::from(\"foo\");\n\ns.reserve(100);\nassert!(s.capacity() >= 100);\n\ns.shrink_to_fit();\nassert_eq!(3, s.capacity());
\n
1.56.0 · source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of this String with a lower bound.

\n

The capacity will remain at least as large as both the length\nand the supplied value.

\n

If the current capacity is less than the lower limit, this is a no-op.

\n
Examples
\n
let mut s = String::from(\"foo\");\n\ns.reserve(100);\nassert!(s.capacity() >= 100);\n\ns.shrink_to(10);\nassert!(s.capacity() >= 10);\ns.shrink_to(0);\nassert!(s.capacity() >= 3);
\n
1.0.0 · source

pub fn push(&mut self, ch: char)

Appends the given char to the end of this String.

\n
Examples
\n
let mut s = String::from(\"abc\");\n\ns.push('1');\ns.push('2');\ns.push('3');\n\nassert_eq!(\"abc123\", s);
\n
1.0.0 · source

pub fn as_bytes(&self) -> &[u8]

Returns a byte slice of this String’s contents.

\n

The inverse of this method is from_utf8.

\n
Examples
\n
let s = String::from(\"hello\");\n\nassert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
\n
1.0.0 · source

pub fn truncate(&mut self, new_len: usize)

Shortens this String to the specified length.

\n

If new_len is greater than the string’s current length, this has no\neffect.

\n

Note that this method has no effect on the allocated capacity\nof the string

\n
Panics
\n

Panics if new_len does not lie on a char boundary.

\n
Examples
\n
let mut s = String::from(\"hello\");\n\ns.truncate(2);\n\nassert_eq!(\"he\", s);
\n
1.0.0 · source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

\n

Returns None if this String is empty.

\n
Examples
\n
let mut s = String::from(\"abč\");\n\nassert_eq!(s.pop(), Some('č'));\nassert_eq!(s.pop(), Some('b'));\nassert_eq!(s.pop(), Some('a'));\n\nassert_eq!(s.pop(), None);
\n
1.0.0 · source

pub fn remove(&mut self, idx: usize) -> char

Removes a char from this String at a byte position and returns it.

\n

This is an O(n) operation, as it requires copying every element in the\nbuffer.

\n
Panics
\n

Panics if idx is larger than or equal to the String’s length,\nor if it does not lie on a char boundary.

\n
Examples
\n
let mut s = String::from(\"abç\");\n\nassert_eq!(s.remove(0), 'a');\nassert_eq!(s.remove(1), 'ç');\nassert_eq!(s.remove(0), 'b');
\n
source

pub fn remove_matches<P, 'a>(&'a mut self, pat: P)
where\n P: for<'x> Pattern<'x>,

🔬This is a nightly-only experimental API. (string_remove_matches)

Remove all matches of pattern pat in the String.

\n
Examples
\n
#![feature(string_remove_matches)]\nlet mut s = String::from(\"Trees are not green, the sky is not blue.\");\ns.remove_matches(\"not \");\nassert_eq!(\"Trees are green, the sky is blue.\", s);
\n

Matches will be detected and removed iteratively, so in cases where\npatterns overlap, only the first pattern will be removed:

\n\n
#![feature(string_remove_matches)]\nlet mut s = String::from(\"banana\");\ns.remove_matches(\"ana\");\nassert_eq!(\"bna\", s);
\n
1.26.0 · source

pub fn retain<F>(&mut self, f: F)
where\n F: FnMut(char) -> bool,

Retains only the characters specified by the predicate.

\n

In other words, remove all characters c such that f(c) returns false.\nThis method operates in place, visiting each character exactly once in the\noriginal order, and preserves the order of the retained characters.

\n
Examples
\n
let mut s = String::from(\"f_o_ob_ar\");\n\ns.retain(|c| c != '_');\n\nassert_eq!(s, \"foobar\");
\n

Because the elements are visited exactly once in the original order,\nexternal state may be used to decide which elements to keep.

\n\n
let mut s = String::from(\"abcde\");\nlet keep = [false, true, true, false, true];\nlet mut iter = keep.iter();\ns.retain(|_| *iter.next().unwrap());\nassert_eq!(s, \"bce\");
\n
1.0.0 · source

pub fn insert(&mut self, idx: usize, ch: char)

Inserts a character into this String at a byte position.

\n

This is an O(n) operation as it requires copying every element in the\nbuffer.

\n
Panics
\n

Panics if idx is larger than the String’s length, or if it does not\nlie on a char boundary.

\n
Examples
\n
let mut s = String::with_capacity(3);\n\ns.insert(0, 'f');\ns.insert(1, 'o');\ns.insert(2, 'o');\n\nassert_eq!(\"foo\", s);
\n
1.16.0 · source

pub fn insert_str(&mut self, idx: usize, string: &str)

Inserts a string slice into this String at a byte position.

\n

This is an O(n) operation as it requires copying every element in the\nbuffer.

\n
Panics
\n

Panics if idx is larger than the String’s length, or if it does not\nlie on a char boundary.

\n
Examples
\n
let mut s = String::from(\"bar\");\n\ns.insert_str(0, \"foo\");\n\nassert_eq!(\"foobar\", s);
\n
1.0.0 · source

pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8>

Returns a mutable reference to the contents of this String.

\n
Safety
\n

This function is unsafe because the returned &mut Vec allows writing\nbytes which are not valid UTF-8. If this constraint is violated, using\nthe original String after dropping the &mut Vec may violate memory\nsafety, as the rest of the standard library assumes that Strings are\nvalid UTF-8.

\n
Examples
\n
let mut s = String::from(\"hello\");\n\nunsafe {\n    let vec = s.as_mut_vec();\n    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);\n\n    vec.reverse();\n}\nassert_eq!(s, \"olleh\");
\n
1.0.0 · source

pub fn len(&self) -> usize

Returns the length of this String, in bytes, not chars or\ngraphemes. In other words, it might not be what a human considers the\nlength of the string.

\n
Examples
\n
let a = String::from(\"foo\");\nassert_eq!(a.len(), 3);\n\nlet fancy_f = String::from(\"ƒoo\");\nassert_eq!(fancy_f.len(), 4);\nassert_eq!(fancy_f.chars().count(), 3);
\n
1.0.0 · source

pub fn is_empty(&self) -> bool

Returns true if this String has a length of zero, and false otherwise.

\n
Examples
\n
let mut v = String::new();\nassert!(v.is_empty());\n\nv.push('a');\nassert!(!v.is_empty());
\n
1.16.0 · source

pub fn split_off(&mut self, at: usize) -> String

Splits the string into two at the given byte index.

\n

Returns a newly allocated String. self contains bytes [0, at), and\nthe returned String contains bytes [at, len). at must be on the\nboundary of a UTF-8 code point.

\n

Note that the capacity of self does not change.

\n
Panics
\n

Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last\ncode point of the string.

\n
Examples
\n
let mut hello = String::from(\"Hello, World!\");\nlet world = hello.split_off(7);\nassert_eq!(hello, \"Hello, \");\nassert_eq!(world, \"World!\");
\n
1.0.0 · source

pub fn clear(&mut self)

Truncates this String, removing all contents.

\n

While this means the String will have a length of zero, it does not\ntouch its capacity.

\n
Examples
\n
let mut s = String::from(\"foo\");\n\ns.clear();\n\nassert!(s.is_empty());\nassert_eq!(0, s.len());\nassert_eq!(3, s.capacity());
\n
1.6.0 · source

pub fn drain<R>(&mut self, range: R) -> Drain<'_>
where\n R: RangeBounds<usize>,

Removes the specified range from the string in bulk, returning all\nremoved characters as an iterator.

\n

The returned iterator keeps a mutable borrow on the string to optimize\nits implementation.

\n
Panics
\n

Panics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.

\n
Leaking
\n

If the returned iterator goes out of scope without being dropped (due to\ncore::mem::forget, for example), the string may still contain a copy\nof any drained characters, or may have lost characters arbitrarily,\nincluding characters outside the range.

\n
Examples
\n
let mut s = String::from(\"α is alpha, β is beta\");\nlet beta_offset = s.find('β').unwrap_or(s.len());\n\n// Remove the range up until the β from the string\nlet t: String = s.drain(..beta_offset).collect();\nassert_eq!(t, \"α is alpha, \");\nassert_eq!(s, \"β is beta\");\n\n// A full range clears the string, like `clear()` does\ns.drain(..);\nassert_eq!(s, \"\");
\n
1.27.0 · source

pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
where\n R: RangeBounds<usize>,

Removes the specified range in the string,\nand replaces it with the given string.\nThe given string doesn’t need to be the same length as the range.

\n
Panics
\n

Panics if the starting point or end point do not lie on a char\nboundary, or if they’re out of bounds.

\n
Examples
\n
let mut s = String::from(\"α is alpha, β is beta\");\nlet beta_offset = s.find('β').unwrap_or(s.len());\n\n// Replace the range up until the β from the string\ns.replace_range(..beta_offset, \"Α is capital alpha; \");\nassert_eq!(s, \"Α is capital alpha; β is beta\");
\n
1.4.0 · source

pub fn into_boxed_str(self) -> Box<str>

Converts this String into a Box<str>.

\n

This will drop any excess capacity.

\n
Examples
\n
let s = String::from(\"hello\");\n\nlet b = s.into_boxed_str();
\n
1.72.0 · source

pub fn leak<'a>(self) -> &'a mut str

Consumes and leaks the String, returning a mutable reference to the contents,\n&'a mut str.

\n

The caller has free choice over the returned lifetime, including 'static. Indeed,\nthis function is ideally used for data that lives for the remainder of the program’s life,\nas dropping the returned reference will cause a memory leak.

\n

It does not reallocate or shrink the String,\nso the leaked allocation may include unused capacity that is not part\nof the returned slice. If you don’t want that, call into_boxed_str,\nand then Box::leak.

\n
Examples
\n
let x = String::from(\"bucket\");\nlet static_ref: &'static mut str = x.leak();\nassert_eq!(static_ref, \"bucket\");
\n
",0,"karyon_p2p::protocol::ProtocolID"],["
1.16.0 · source§

impl ToSocketAddrs for String

§

type Iter = IntoIter<SocketAddr>

Returned iterator over socket addresses which this type may correspond\nto.
source§

fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>, Error>

Converts this object to an iterator of resolved SocketAddrs. Read more
","ToSocketAddrs","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl AsRef<OsStr> for String

source§

fn as_ref(&self) -> &OsStr

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl AsRef<Path> for String

source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_p2p::protocol::ProtocolID"],["
1.3.0 · source§

impl DerefMut for String

source§

fn deref_mut(&mut self) -> &mut str

Mutably dereferences the value.
","DerefMut","karyon_p2p::protocol::ProtocolID"],["
1.26.0 · source§

impl Index<RangeInclusive<usize>> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, index: RangeInclusive<usize>) -> &str

Performs the indexing (container[index]) operation. Read more
","Index>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Index<Range<usize>> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, index: Range<usize>) -> &str

Performs the indexing (container[index]) operation. Read more
","Index>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Index<RangeTo<usize>> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, index: RangeTo<usize>) -> &str

Performs the indexing (container[index]) operation. Read more
","Index>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Index<RangeFull> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, _index: RangeFull) -> &str

Performs the indexing (container[index]) operation. Read more
","Index","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Index<RangeFrom<usize>> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, index: RangeFrom<usize>) -> &str

Performs the indexing (container[index]) operation. Read more
","Index>","karyon_p2p::protocol::ProtocolID"],["
1.26.0 · source§

impl Index<RangeToInclusive<usize>> for String

§

type Output = str

The returned type after indexing.
source§

fn index(&self, index: RangeToInclusive<usize>) -> &str

Performs the indexing (container[index]) operation. Read more
","Index>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl StructuralPartialEq for String

","StructuralPartialEq","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl FromStr for String

§

type Err = Infallible

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<String, <String as FromStr>::Err>

Parses a string s to return a value of this type. Read more
","FromStr","karyon_p2p::protocol::ProtocolID"],["
1.45.0 · source§

impl FromIterator<Box<str>> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = Box<str>>,

Creates a value from an iterator. Read more
","FromIterator>","karyon_p2p::protocol::ProtocolID"],["
1.4.0 · source§

impl FromIterator<String> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = String>,

Creates a value from an iterator. Read more
","FromIterator","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl<'a> FromIterator<&'a str> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = &'a str>,

Creates a value from an iterator. Read more
","FromIterator<&'a str>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl FromIterator<char> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = char>,

Creates a value from an iterator. Read more
","FromIterator","karyon_p2p::protocol::ProtocolID"],["
1.19.0 · source§

impl<'a> FromIterator<Cow<'a, str>> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = Cow<'a, str>>,

Creates a value from an iterator. Read more
","FromIterator>","karyon_p2p::protocol::ProtocolID"],["
1.17.0 · source§

impl<'a> FromIterator<&'a char> for String

source§

fn from_iter<I>(iter: I) -> String
where\n I: IntoIterator<Item = &'a char>,

Creates a value from an iterator. Read more
","FromIterator<&'a char>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl PartialOrd for String

source§

fn partial_cmp(&self, other: &String) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Deref for String

§

type Target = str

The resulting type after dereferencing.
source§

fn deref(&self) -> &str

Dereferences the value.
","Deref","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Ord for String

source§

fn cmp(&self, other: &String) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl From<&str> for String

source§

fn from(s: &str) -> String

Converts a &str into a String.

\n

The result is allocated on the heap.

\n
","From<&str>","karyon_p2p::protocol::ProtocolID"],["
1.44.0 · source§

impl From<&mut str> for String

source§

fn from(s: &mut str) -> String

Converts a &mut str into a String.

\n

The result is allocated on the heap.

\n
","From<&mut str>","karyon_p2p::protocol::ProtocolID"],["
1.18.0 · source§

impl From<Box<str>> for String

source§

fn from(s: Box<str>) -> String

Converts the given boxed str slice to a String.\nIt is notable that the str slice is owned.

\n
Examples
\n
let s1: String = String::from(\"hello world\");\nlet s2: Box<str> = s1.into_boxed_str();\nlet s3: String = String::from(s2);\n\nassert_eq!(\"hello world\", s3)
\n
","From>","karyon_p2p::protocol::ProtocolID"],["
1.46.0 · source§

impl From<char> for String

source§

fn from(c: char) -> String

Allocates an owned String from a single character.

\n
Example
\n
let c: char = 'a';\nlet s: String = String::from(c);\nassert_eq!(\"a\", &s[..]);
\n
","From","karyon_p2p::protocol::ProtocolID"],["
1.14.0 · source§

impl<'a> From<Cow<'a, str>> for String

source§

fn from(s: Cow<'a, str>) -> String

Converts a clone-on-write string to an owned\ninstance of String.

\n

This extracts the owned string,\nclones the string if it is not already owned.

\n
Example
\n
// If the string is not owned...\nlet cow: Cow<'_, str> = Cow::Borrowed(\"eggplant\");\n// It will allocate on the heap and copy the string.\nlet owned: String = String::from(cow);\nassert_eq!(&owned[..], \"eggplant\");
\n
","From>","karyon_p2p::protocol::ProtocolID"],["
1.35.0 · source§

impl From<&String> for String

source§

fn from(s: &String) -> String

Converts a &String into a String.

\n

This clones s and returns the clone.

\n
","From<&String>","karyon_p2p::protocol::ProtocolID"],["
1.12.0 · source§

impl AddAssign<&str> for String

Implements the += operator for appending to a String.

\n

This has the same behavior as the push_str method.

\n
source§

fn add_assign(&mut self, other: &str)

Performs the += operation. Read more
","AddAssign<&str>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl AsRef<str> for String

source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl AsRef<[u8]> for String

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef<[u8]>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Borrow<str> for String

source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
","Borrow","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Hash for String

source§

fn hash<H>(&self, hasher: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_p2p::protocol::ProtocolID"],["
1.3.0 · source§

impl IndexMut<RangeFrom<usize>> for String

source§

fn index_mut(&mut self, index: RangeFrom<usize>) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut>","karyon_p2p::protocol::ProtocolID"],["
1.3.0 · source§

impl IndexMut<Range<usize>> for String

source§

fn index_mut(&mut self, index: Range<usize>) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut>","karyon_p2p::protocol::ProtocolID"],["
1.3.0 · source§

impl IndexMut<RangeTo<usize>> for String

source§

fn index_mut(&mut self, index: RangeTo<usize>) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut>","karyon_p2p::protocol::ProtocolID"],["
1.3.0 · source§

impl IndexMut<RangeFull> for String

source§

fn index_mut(&mut self, _index: RangeFull) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut","karyon_p2p::protocol::ProtocolID"],["
1.26.0 · source§

impl IndexMut<RangeToInclusive<usize>> for String

source§

fn index_mut(&mut self, index: RangeToInclusive<usize>) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut>","karyon_p2p::protocol::ProtocolID"],["
1.26.0 · source§

impl IndexMut<RangeInclusive<usize>> for String

source§

fn index_mut(&mut self, index: RangeInclusive<usize>) -> &mut str

Performs the mutable indexing (container[index]) operation. Read more
","IndexMut>","karyon_p2p::protocol::ProtocolID"],["
1.43.0 · source§

impl AsMut<str> for String

source§

fn as_mut(&mut self) -> &mut str

Converts this type into a mutable reference of the (usually inferred) input type.
","AsMut","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Clone for String

source§

fn clone(&self) -> String

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &String)

Performs copy-assignment from source. Read more
","Clone","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Display for String

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Eq for String

","Eq","karyon_p2p::protocol::ProtocolID"],["
1.36.0 · source§

impl BorrowMut<str> for String

source§

fn borrow_mut(&mut self) -> &mut str

Mutably borrows from an owned value. Read more
","BorrowMut","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl StructuralEq for String

","StructuralEq","karyon_p2p::protocol::ProtocolID"],["
1.45.0 · source§

impl Extend<Box<str>> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = Box<str>>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend>","karyon_p2p::protocol::ProtocolID"],["
1.2.0 · source§

impl<'a> Extend<&'a char> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = &'a char>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, _: &'a char)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend<&'a char>","karyon_p2p::protocol::ProtocolID"],["
1.4.0 · source§

impl Extend<String> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = String>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, s: String)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend","karyon_p2p::protocol::ProtocolID"],["
1.19.0 · source§

impl<'a> Extend<Cow<'a, str>> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = Cow<'a, str>>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, s: Cow<'a, str>)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl<'a> Extend<&'a str> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = &'a str>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, s: &'a str)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend<&'a str>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Extend<char> for String

source§

fn extend<I>(&mut self, iter: I)
where\n I: IntoIterator<Item = char>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, c: char)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Default for String

source§

fn default() -> String

Creates an empty String.

\n
","Default","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Write for String

source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write\nsucceeded. Read more
source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a char into this writer, returning whether the write succeeded. Read more
1.0.0 · source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the write! macro with implementors of this trait. Read more
","Write","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Debug for String

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl<'a, 'b> PartialEq<Cow<'a, str>> for String

source§

fn eq(&self, other: &Cow<'a, str>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &Cow<'a, str>) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl PartialEq for String

source§

fn eq(&self, other: &String) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl<'a, 'b> PartialEq<str> for String

source§

fn eq(&self, other: &str) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &str) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl<'a, 'b> PartialEq<&'a str> for String

source§

fn eq(&self, other: &&'a str) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &&'a str) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq<&'a str>","karyon_p2p::protocol::ProtocolID"],["
1.0.0 · source§

impl Add<&str> for String

Implements the + operator for concatenating two strings.

\n

This consumes the String on the left-hand side and re-uses its buffer (growing it if\nnecessary). This is done to avoid allocating a new String and copying the entire contents on\nevery operation, which would lead to O(n^2) running time when building an n-byte string by\nrepeated concatenation.

\n

The string on the right-hand side is only borrowed; its contents are copied into the returned\nString.

\n

Examples

\n

Concatenating two Strings takes the first by value and borrows the second:

\n\n
let a = String::from(\"hello\");\nlet b = String::from(\" world\");\nlet c = a + &b;\n// `a` is moved and can no longer be used here.
\n

If you want to keep using the first String, you can clone it and append to the clone instead:

\n\n
let a = String::from(\"hello\");\nlet b = String::from(\" world\");\nlet c = a.clone() + &b;\n// `a` is still valid here.
\n

Concatenating &str slices can be done by converting the first to a String:

\n\n
let a = \"hello\";\nlet b = \" world\";\nlet c = a.to_string() + b;
\n
§

type Output = String

The resulting type after applying the + operator.
source§

fn add(self, other: &str) -> String

Performs the + operation. Read more
","Add<&str>","karyon_p2p::protocol::ProtocolID"],["
source§

impl Encode for String

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_p2p::protocol::ProtocolID"],["
source§

impl<'de> BorrowDecode<'de> for String

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<String, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_p2p::protocol::ProtocolID"],["
source§

impl Decode for String

source§

fn decode<D>(decoder: &mut D) -> Result<String, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_p2p::protocol::ProtocolID"],["
§

impl Arg for String

§

fn as_str(&self) -> Result<&str, Errno>

Returns a view of this string as a string slice.
§

fn to_string_lossy(&self) -> Cow<'_, str>

Returns a potentially-lossy rendering of this string as a\nCow<'_, str>.
§

fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>

Returns a view of this string as a maybe-owned CStr.
§

fn into_c_str<'b>(self) -> Result<Cow<'b, CStr>, Errno>
where\n String: 'b,

Consumes self and returns a view of this string as a maybe-owned\nCStr.
§

fn into_with_c_str<T, F>(self, f: F) -> Result<T, Errno>
where\n String: Sized,\n F: FnOnce(&CStr) -> Result<T, Errno>,

Runs a closure with self passed in as a &CStr.
","Arg","karyon_p2p::protocol::ProtocolID"],["
§

impl Value for String

§

fn record(&self, key: &Field, visitor: &mut dyn Visit)

Visits this value with the given Visitor.
","Value","karyon_p2p::protocol::ProtocolID"],["
§

impl AsyncToSocketAddrs for String

","AsyncToSocketAddrs","karyon_p2p::protocol::ProtocolID"],["
§

impl Zeroize for String

§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the\nzeroization operation is not “optimized away” by the compiler.
","Zeroize","karyon_p2p::protocol::ProtocolID"],["
source§

impl From<Url> for String

String conversion.

\n
source§

fn from(value: Url) -> String

Converts to this type from the input type.
","From","karyon_p2p::protocol::ProtocolID"],["
§

impl Target for String

§

fn as_mut_string(&mut self) -> &mut String

§

fn finish(self) -> String

§

type Finished = String

","Target","karyon_p2p::protocol::ProtocolID"],["
§

impl ToDer for String

§

fn to_der_len(&self) -> Result<usize, Error>

Get the length of the object (including the header), when encoded
§

fn write_der_header(\n &self,\n writer: &mut dyn Write\n) -> Result<usize, SerializeError>

Attempt to write the DER header to this writer.
§

fn write_der_content(\n &self,\n writer: &mut dyn Write\n) -> Result<usize, SerializeError>

Attempt to write the DER content (all except header) to this writer.
§

fn to_der_vec(&self) -> Result<Vec<u8>, SerializeError>

Write the DER encoded representation to a newly allocated Vec<u8>.
§

fn to_der_vec_raw(&self) -> Result<Vec<u8>, SerializeError>

Similar to using to_vec, but uses provided values without changes.\nThis can generate an invalid encoding for a DER object.
§

fn write_der(&self, writer: &mut dyn Write) -> Result<usize, SerializeError>

Attempt to write the DER encoded representation (header and content) into this writer. Read more
§

fn write_der_raw(&self, writer: &mut dyn Write) -> Result<usize, SerializeError>

Similar to using to_der, but uses provided values without changes.\nThis can generate an invalid encoding for a DER object.
","ToDer","karyon_p2p::protocol::ProtocolID"],["
§

impl DerAutoDerive for String

","DerAutoDerive","karyon_p2p::protocol::ProtocolID"],["
§

impl CheckDerConstraints for String

§

fn check_constraints(any: &Any<'_>) -> Result<(), Error>

","CheckDerConstraints","karyon_p2p::protocol::ProtocolID"],["
§

impl Tagged for String

§

const TAG: Tag = Tag::Utf8String

","Tagged","karyon_p2p::protocol::ProtocolID"],["
§

impl<'a, 'b> TryFrom<&'b Any<'a>> for String

§

type Error = Error

The type returned in the event of a conversion error.
§

fn try_from(any: &'b Any<'a>) -> Result<String, Error>

Performs the conversion.
","TryFrom<&'b Any<'a>>","karyon_p2p::protocol::ProtocolID"],["
§

impl<'a> TryFrom<Any<'a>> for String

§

type Error = Error

The type returned in the event of a conversion error.
§

fn try_from(any: Any<'a>) -> Result<String, Error>

Performs the conversion.
","TryFrom>","karyon_p2p::protocol::ProtocolID"],["
§

impl BERDecodable for String

§

fn decode_ber(reader: BERReader<'_, '_>) -> Result<String, ASN1Error>

Reads an ASN.1 value from BERReader and converts it to Self. Read more
","BERDecodable","karyon_p2p::protocol::ProtocolID"],["
§

impl DEREncodable for String

§

fn encode_der(&self, writer: DERWriter<'_>)

Writes the value as an DER-encoded ASN.1 value. Read more
","DEREncodable","karyon_p2p::protocol::ProtocolID"],["
§

impl StrConsumer for String

Pushes the str onto the end of the String

\n
§

fn consume(&mut self, buf: &str)

Consume the base64 encoded data in buf
","StrConsumer","karyon_p2p::protocol::ProtocolID"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/alloc/sync/struct.Arc.js b/type.impl/alloc/sync/struct.Arc.js new file mode 100644 index 00000000..a9bbb047 --- /dev/null +++ b/type.impl/alloc/sync/struct.Arc.js @@ -0,0 +1,4 @@ +(function() {var type_impls = { +"karyon_core":[["
source§

impl<T> Arc<T>

1.0.0 · source

pub fn new(data: T) -> Arc<T>

Constructs a new Arc<T>.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);
\n
1.60.0 · source

pub fn new_cyclic<F>(data_fn: F) -> Arc<T>
where\n F: FnOnce(&Weak<T>) -> T,

Constructs a new Arc<T> while giving you a Weak<T> to the allocation,\nto allow you to construct a T which holds a weak pointer to itself.

\n

Generally, a structure circularly referencing itself, either directly or\nindirectly, should not hold a strong reference to itself to prevent a memory leak.\nUsing this function, you get access to the weak pointer during the\ninitialization of T, before the Arc<T> is created, such that you can\nclone and store it inside the T.

\n

new_cyclic first allocates the managed allocation for the Arc<T>,\nthen calls your closure, giving it a Weak<T> to this allocation,\nand only afterwards completes the construction of the Arc<T> by placing\nthe T returned from your closure into the allocation.

\n

Since the new Arc<T> is not fully-constructed until Arc<T>::new_cyclic\nreturns, calling upgrade on the weak reference inside your closure will\nfail and result in a None value.

\n
Panics
\n

If data_fn panics, the panic is propagated to the caller, and the\ntemporary Weak<T> is dropped normally.

\n
Example
\n
use std::sync::{Arc, Weak};\n\nstruct Gadget {\n    me: Weak<Gadget>,\n}\n\nimpl Gadget {\n    /// Construct a reference counted Gadget.\n    fn new() -> Arc<Self> {\n        // `me` is a `Weak<Gadget>` pointing at the new allocation of the\n        // `Arc` we're constructing.\n        Arc::new_cyclic(|me| {\n            // Create the actual struct here.\n            Gadget { me: me.clone() }\n        })\n    }\n\n    /// Return a reference counted pointer to Self.\n    fn me(&self) -> Arc<Self> {\n        self.me.upgrade().unwrap()\n    }\n}
\n
source

pub fn new_uninit() -> Arc<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Arc with uninitialized contents.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut five = Arc::<u32>::new_uninit();\n\n// Deferred initialization:\nArc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Arc<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n\nuse std::sync::Arc;\n\nlet zero = Arc::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
1.33.0 · source

pub fn pin(data: T) -> Pin<Arc<T>>

Constructs a new Pin<Arc<T>>. If T does not implement Unpin, then\ndata will be pinned in memory and unable to be moved.

\n
source

pub fn try_pin(data: T) -> Result<Pin<Arc<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T>>, return an error if allocation fails.

\n
source

pub fn try_new(data: T) -> Result<Arc<T>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T>, returning an error if allocation fails.

\n
Examples
\n
#![feature(allocator_api)]\nuse std::sync::Arc;\n\nlet five = Arc::try_new(5)?;
\n
source

pub fn try_new_uninit() -> Result<Arc<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, returning an error\nif allocation fails.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut five = Arc::<u32>::try_new_uninit()?;\n\n// Deferred initialization:\nArc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Arc<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, returning an error if allocation fails.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n\nuse std::sync::Arc;\n\nlet zero = Arc::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,

source

pub fn allocator(this: &Arc<T, A>) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Arc::allocator(&a) instead of a.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
source

pub fn new_in(data: T, alloc: A) -> Arc<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T> in the provided allocator.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);
\n
source

pub fn new_uninit_in(alloc: A) -> Arc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents in the provided allocator.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(get_mut_unchecked)]\n#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet mut five = Arc::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed_in(alloc: A) -> Arc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet zero = Arc::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn pin_in(data: T, alloc: A) -> Pin<Arc<T, A>>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T, A>> in the provided allocator. If T does not implement Unpin,\nthen data will be pinned in memory and unable to be moved.

\n
source

pub fn try_pin_in(data: T, alloc: A) -> Result<Pin<Arc<T, A>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T, A>> in the provided allocator, return an error if allocation\nfails.

\n
source

pub fn try_new_in(data: T, alloc: A) -> Result<Arc<T, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T, A> in the provided allocator, returning an error if allocation fails.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::try_new_in(5, System)?;
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Arc<MaybeUninit<T>, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, in the provided allocator, returning an\nerror if allocation fails.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet mut five = Arc::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Arc<MaybeUninit<T>, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator, returning an error if allocation\nfails.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet zero = Arc::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
1.4.0 · source

pub fn try_unwrap(this: Arc<T, A>) -> Result<T, Arc<T, A>>

Returns the inner value, if the Arc has exactly one strong reference.

\n

Otherwise, an Err is returned with the same Arc that was\npassed in.

\n

This will succeed even if there are outstanding weak references.

\n

It is strongly recommended to use Arc::into_inner instead if you don’t\nwant to keep the Arc in the Err case.\nImmediately dropping the Err payload, like in the expression\nArc::try_unwrap(this).ok(), can still cause the strong count to\ndrop to zero and the inner value of the Arc to be dropped:\nFor instance if two threads each execute this expression in parallel, then\nthere is a race condition. The threads could first both check whether they\nhave the last clone of their Arc via Arc::try_unwrap, and then\nboth drop their Arc in the call to ok,\ntaking the strong count from two down to zero.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(3);\nassert_eq!(Arc::try_unwrap(x), Ok(3));\n\nlet x = Arc::new(4);\nlet _y = Arc::clone(&x);\nassert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
\n
1.70.0 · source

pub fn into_inner(this: Arc<T, A>) -> Option<T>

Returns the inner value, if the Arc has exactly one strong reference.

\n

Otherwise, None is returned and the Arc is dropped.

\n

This will succeed even if there are outstanding weak references.

\n

If Arc::into_inner is called on every clone of this Arc,\nit is guaranteed that exactly one of the calls returns the inner value.\nThis means in particular that the inner value is not dropped.

\n

The similar expression Arc::try_unwrap(this).ok() does not\noffer such a guarantee. See the last example below\nand the documentation of Arc::try_unwrap.

\n
Examples
\n

Minimal example demonstrating the guarantee that Arc::into_inner gives.

\n\n
use std::sync::Arc;\n\nlet x = Arc::new(3);\nlet y = Arc::clone(&x);\n\n// Two threads calling `Arc::into_inner` on both clones of an `Arc`:\nlet x_thread = std::thread::spawn(|| Arc::into_inner(x));\nlet y_thread = std::thread::spawn(|| Arc::into_inner(y));\n\nlet x_inner_value = x_thread.join().unwrap();\nlet y_inner_value = y_thread.join().unwrap();\n\n// One of the threads is guaranteed to receive the inner value:\nassert!(matches!(\n    (x_inner_value, y_inner_value),\n    (None, Some(3)) | (Some(3), None)\n));\n// The result could also be `(None, None)` if the threads called\n// `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead.
\n

A more practical example demonstrating the need for Arc::into_inner:

\n\n
use std::sync::Arc;\n\n// Definition of a simple singly linked list using `Arc`:\n#[derive(Clone)]\nstruct LinkedList<T>(Option<Arc<Node<T>>>);\nstruct Node<T>(T, Option<Arc<Node<T>>>);\n\n// Dropping a long `LinkedList<T>` relying on the destructor of `Arc`\n// can cause a stack overflow. To prevent this, we can provide a\n// manual `Drop` implementation that does the destruction in a loop:\nimpl<T> Drop for LinkedList<T> {\n    fn drop(&mut self) {\n        let mut link = self.0.take();\n        while let Some(arc_node) = link.take() {\n            if let Some(Node(_value, next)) = Arc::into_inner(arc_node) {\n                link = next;\n            }\n        }\n    }\n}\n\n// Implementation of `new` and `push` omitted\nimpl<T> LinkedList<T> {\n    /* ... */\n}\n\n// The following code could have still caused a stack overflow\n// despite the manual `Drop` impl if that `Drop` impl had used\n// `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`.\n\n// Create a long list and clone it\nlet mut x = LinkedList::new();\nfor i in 0..100000 {\n    x.push(i); // Adds i to the front of x\n}\nlet y = x.clone();\n\n// Drop the clones in parallel\nlet x_thread = std::thread::spawn(|| drop(x));\nlet y_thread = std::thread::spawn(|| drop(y));\nx_thread.join().unwrap();\ny_thread.join().unwrap();
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T> Arc<T>
where\n T: ?Sized,

1.17.0 · source

pub unsafe fn from_raw(ptr: *const T) -> Arc<T>

Constructs an Arc<T> from a raw pointer.

\n

The raw pointer must have been previously returned by a call to\nArc<U>::into_raw where U must have the same size and\nalignment as T. This is trivially true if U is T.\nNote that if U is not T but has the same size and alignment, this is\nbasically like transmuting references of different types. See\nmem::transmute for more information on what\nrestrictions apply in this case.

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Arc<T> is never accessed.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet x_ptr = Arc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Arc` to prevent leak.\n    let x = Arc::from_raw(x_ptr);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n
1.51.0 · source

pub unsafe fn increment_strong_count(ptr: *const T)

Increments the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count(ptr);\n\n    // This assertion is deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw(ptr);\n    assert_eq!(2, Arc::strong_count(&five));\n}
\n
1.51.0 · source

pub unsafe fn decrement_strong_count(ptr: *const T)

Decrements the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method. This method can be used to release the final\nArc and backing storage, but should not be called after the final Arc has been\nreleased.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count(ptr);\n\n    // Those assertions are deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw(ptr);\n    assert_eq!(2, Arc::strong_count(&five));\n    Arc::decrement_strong_count(ptr);\n    assert_eq!(1, Arc::strong_count(&five));\n}
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

1.17.0 · source

pub fn into_raw(this: Arc<T, A>) -> *const T

Consumes the Arc, returning the wrapped pointer.

\n

To avoid a memory leak the pointer must be converted back to an Arc using\nArc::from_raw.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet x_ptr = Arc::into_raw(x);\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
1.45.0 · source

pub fn as_ptr(this: &Arc<T, A>) -> *const T

Provides a raw pointer to the data.

\n

The counts are not affected in any way and the Arc is not consumed. The pointer is valid for\nas long as there are strong counts in the Arc.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet y = Arc::clone(&x);\nlet x_ptr = Arc::as_ptr(&x);\nassert_eq!(x_ptr, Arc::as_ptr(&y));\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Arc<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs an Arc<T, A> from a raw pointer.

\n

The raw pointer must have been previously returned by a call to\nArc<U, A>::into_raw where U must have the same size and\nalignment as T. This is trivially true if U is T.\nNote that if U is not T but has the same size and alignment, this is\nbasically like transmuting references of different types. See\nmem::transmute for more information on what\nrestrictions apply in this case.

\n

The raw pointer must point to a block of memory allocated by alloc

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Arc<T> is never accessed.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet x = Arc::new_in(\"hello\".to_owned(), System);\nlet x_ptr = Arc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Arc` to prevent leak.\n    let x = Arc::from_raw_in(x_ptr, System);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n
1.4.0 · source

pub fn downgrade(this: &Arc<T, A>) -> Weak<T, A>
where\n A: Clone,

Creates a new Weak pointer to this allocation.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet weak_five = Arc::downgrade(&five);
\n
1.15.0 · source

pub fn weak_count(this: &Arc<T, A>) -> usize

Gets the number of Weak pointers to this allocation.

\n
Safety
\n

This method by itself is safe, but using it correctly requires extra care.\nAnother thread can change the weak count at any time,\nincluding potentially between calling this method and acting on the result.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet _weak_five = Arc::downgrade(&five);\n\n// This assertion is deterministic because we haven't shared\n// the `Arc` or `Weak` between threads.\nassert_eq!(1, Arc::weak_count(&five));
\n
1.15.0 · source

pub fn strong_count(this: &Arc<T, A>) -> usize

Gets the number of strong (Arc) pointers to this allocation.

\n
Safety
\n

This method by itself is safe, but using it correctly requires extra care.\nAnother thread can change the strong count at any time,\nincluding potentially between calling this method and acting on the result.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet _also_five = Arc::clone(&five);\n\n// This assertion is deterministic because we haven't shared\n// the `Arc` between threads.\nassert_eq!(2, Arc::strong_count(&five));
\n
source

pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
where\n A: Clone,

🔬This is a nightly-only experimental API. (allocator_api)

Increments the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method,, and ptr must point to a block of memory\nallocated by alloc.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count_in(ptr, System);\n\n    // This assertion is deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw_in(ptr, System);\n    assert_eq!(2, Arc::strong_count(&five));\n}
\n
source

pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A)

🔬This is a nightly-only experimental API. (allocator_api)

Decrements the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method, and ptr must point to a block of memory\nallocated by alloc. This method can be used to release the final\nArc and backing storage, but should not be called after the final Arc has been\nreleased.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count_in(ptr, System);\n\n    // Those assertions are deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw_in(ptr, System);\n    assert_eq!(2, Arc::strong_count(&five));\n    Arc::decrement_strong_count_in(ptr, System);\n    assert_eq!(1, Arc::strong_count(&five));\n}
\n
1.17.0 · source

pub fn ptr_eq(this: &Arc<T, A>, other: &Arc<T, A>) -> bool

Returns true if the two Arcs point to the same allocation in a vein similar to\nptr::eq. This function ignores the metadata of dyn Trait pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet same_five = Arc::clone(&five);\nlet other_five = Arc::new(5);\n\nassert!(Arc::ptr_eq(&five, &same_five));\nassert!(!Arc::ptr_eq(&five, &other_five));
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, A> Arc<T, A>
where\n T: Clone,\n A: Allocator + Clone,

1.4.0 · source

pub fn make_mut(this: &mut Arc<T, A>) -> &mut T

Makes a mutable reference into the given Arc.

\n

If there are other Arc pointers to the same allocation, then make_mut will\nclone the inner value to a new allocation to ensure unique ownership. This is also\nreferred to as clone-on-write.

\n

However, if there are no other Arc pointers to this allocation, but some Weak\npointers, then the Weak pointers will be dissociated and the inner value will not\nbe cloned.

\n

See also get_mut, which will fail rather than cloning the inner value\nor dissociating Weak pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet mut data = Arc::new(5);\n\n*Arc::make_mut(&mut data) += 1;         // Won't clone anything\nlet mut other_data = Arc::clone(&data); // Won't clone inner data\n*Arc::make_mut(&mut data) += 1;         // Clones inner data\n*Arc::make_mut(&mut data) += 1;         // Won't clone anything\n*Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything\n\n// Now `data` and `other_data` point to different allocations.\nassert_eq!(*data, 8);\nassert_eq!(*other_data, 12);
\n

Weak pointers will be dissociated:

\n\n
use std::sync::Arc;\n\nlet mut data = Arc::new(75);\nlet weak = Arc::downgrade(&data);\n\nassert!(75 == *data);\nassert!(75 == *weak.upgrade().unwrap());\n\n*Arc::make_mut(&mut data) += 1;\n\nassert!(76 == *data);\nassert!(weak.upgrade().is_none());
\n
1.76.0 · source

pub fn unwrap_or_clone(this: Arc<T, A>) -> T

If we have the only reference to T then unwrap it. Otherwise, clone T and return the\nclone.

\n

Assuming arc_t is of type Arc<T>, this function is functionally equivalent to\n(*arc_t).clone(), but will avoid cloning the inner value where possible.

\n
Examples
\n
let inner = String::from(\"test\");\nlet ptr = inner.as_ptr();\n\nlet arc = Arc::new(inner);\nlet inner = Arc::unwrap_or_clone(arc);\n// The inner value was not cloned\nassert!(ptr::eq(ptr, inner.as_ptr()));\n\nlet arc = Arc::new(inner);\nlet arc2 = arc.clone();\nlet inner = Arc::unwrap_or_clone(arc);\n// Because there were 2 references, we had to clone the inner value.\nassert!(!ptr::eq(ptr, inner.as_ptr()));\n// `arc2` is the last reference, so when we unwrap it we get back\n// the original `String`.\nlet inner = Arc::unwrap_or_clone(arc2);\nassert!(ptr::eq(ptr, inner.as_ptr()));
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

1.4.0 · source

pub fn get_mut(this: &mut Arc<T, A>) -> Option<&mut T>

Returns a mutable reference into the given Arc, if there are\nno other Arc or Weak pointers to the same allocation.

\n

Returns None otherwise, because it is not safe to\nmutate a shared value.

\n

See also make_mut, which will clone\nthe inner value when there are other Arc pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet mut x = Arc::new(3);\n*Arc::get_mut(&mut x).unwrap() = 4;\nassert_eq!(*x, 4);\n\nlet _y = Arc::clone(&x);\nassert!(Arc::get_mut(&mut x).is_none());
\n
source

pub unsafe fn get_mut_unchecked(this: &mut Arc<T, A>) -> &mut T

🔬This is a nightly-only experimental API. (get_mut_unchecked)

Returns a mutable reference into the given Arc,\nwithout any check.

\n

See also get_mut, which is safe and does appropriate checks.

\n
Safety
\n

If any other Arc or Weak pointers to the same allocation exist, then\nthey must not be dereferenced or have active borrows for the duration\nof the returned borrow, and their inner type must be exactly the same as the\ninner type of this Rc (including lifetimes). This is trivially the case if no\nsuch pointers exist, for example immediately after Arc::new.

\n
Examples
\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut x = Arc::new(String::new());\nunsafe {\n    Arc::get_mut_unchecked(&mut x).push_str(\"foo\")\n}\nassert_eq!(*x, \"foo\");
\n

Other Arc pointers to the same allocation must be to the same type.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet x: Arc<str> = Arc::from(\"Hello, world!\");\nlet mut y: Arc<[u8]> = x.clone().into();\nunsafe {\n    // this is Undefined Behavior, because x's inner type is str, not [u8]\n    Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8\n}\nprintln!(\"{}\", &*x); // Invalid UTF-8 in a str
\n

Other Arc pointers to the same allocation must be to the exact same type, including lifetimes.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet x: Arc<&str> = Arc::new(\"Hello, world!\");\n{\n    let s = String::from(\"Oh, no!\");\n    let mut y: Arc<&str> = x.clone().into();\n    unsafe {\n        // this is Undefined Behavior, because x's inner type\n        // is &'long str, not &'short str\n        *Arc::get_mut_unchecked(&mut y) = &s;\n    }\n}\nprintln!(\"{}\", &*x); // Use-after-free
\n
",0,"karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.63.0 · source§

impl<T> AsRawFd for Arc<T>
where\n T: AsRawFd,

This impl allows implementing traits that require AsRawFd on Arc.

\n\n
use std::net::UdpSocket;\nuse std::sync::Arc;\ntrait MyTrait: AsRawFd {\n}\nimpl MyTrait for Arc<UdpSocket> {}\nimpl MyTrait for Box<UdpSocket> {}
\n
source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.64.0 · source§

impl<T> AsFd for Arc<T>
where\n T: AsFd,

This impl allows implementing traits that require AsFd on Arc.

\n\n
use std::net::UdpSocket;\nuse std::sync::Arc;\n\ntrait MyTrait: AsFd {}\nimpl MyTrait for Arc<UdpSocket> {}\nimpl MyTrait for Box<UdpSocket> {}
\n
source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.33.0 · source§

impl<T, A> Unpin for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

","Unpin","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, U> DispatchFromDyn<Arc<U>> for Arc<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.52.0 · source§

impl<T> Error for Arc<T>
where\n T: Error + ?Sized,

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
source§

fn provide<'a>(&'a self, req: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
","Error","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Pointer for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
","Pointer","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> PartialOrd for Arc<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

source§

fn partial_cmp(&self, other: &Arc<T, A>) -> Option<Ordering>

Partial comparison for two Arcs.

\n

The two are compared by calling partial_cmp() on their inner values.

\n
Examples
\n
use std::sync::Arc;\nuse std::cmp::Ordering;\n\nlet five = Arc::new(5);\n\nassert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
\n
source§

fn lt(&self, other: &Arc<T, A>) -> bool

Less-than comparison for two Arcs.

\n

The two are compared by calling < on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five < Arc::new(6));
\n
source§

fn le(&self, other: &Arc<T, A>) -> bool

‘Less than or equal to’ comparison for two Arcs.

\n

The two are compared by calling <= on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five <= Arc::new(5));
\n
source§

fn gt(&self, other: &Arc<T, A>) -> bool

Greater-than comparison for two Arcs.

\n

The two are compared by calling > on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five > Arc::new(4));
\n
source§

fn ge(&self, other: &Arc<T, A>) -> bool

‘Greater than or equal to’ comparison for two Arcs.

\n

The two are compared by calling >= on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five >= Arc::new(5));
\n
","PartialOrd","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Deref for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
","Deref","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Ord for Arc<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

source§

fn cmp(&self, other: &Arc<T, A>) -> Ordering

Comparison for two Arcs.

\n

The two are compared by calling cmp() on their inner values.

\n
Examples
\n
use std::sync::Arc;\nuse std::cmp::Ordering;\n\nlet five = Arc::new(5);\n\nassert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
\n
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.6.0 · source§

impl<T> From<T> for Arc<T>

source§

fn from(t: T) -> Arc<T>

Converts a T into an Arc<T>

\n

The conversion moves the value into a\nnewly allocated Arc. It is equivalent to\ncalling Arc::new(t).

\n
Example
\n
let x = 5;\nlet arc = Arc::new(5);\n\nassert_eq!(Arc::from(x), arc);
\n
","From","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.45.0 · source§

impl<'a, B> From<Cow<'a, B>> for Arc<B>
where\n B: ToOwned + ?Sized,\n Arc<B>: From<&'a B> + From<<B as ToOwned>::Owned>,

source§

fn from(cow: Cow<'a, B>) -> Arc<B>

Create an atomically reference-counted pointer from\na clone-on-write pointer by copying its content.

\n
Example
\n
let cow: Cow<'_, str> = Cow::Borrowed(\"eggplant\");\nlet shared: Arc<str> = Arc::from(cow);\nassert_eq!(\"eggplant\", &shared[..]);
\n
","From>","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.21.0 · source§

impl<T, A> From<Box<T, A>> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn from(v: Box<T, A>) -> Arc<T, A>

Move a boxed object to a new, reference-counted allocation.

\n
Example
\n
let unique: Box<str> = Box::from(\"eggplant\");\nlet shared: Arc<str> = Arc::from(unique);\nassert_eq!(\"eggplant\", &shared[..]);
\n
","From>","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Drop for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Drops the Arc.

\n

This will decrement the strong reference count. If the strong reference\ncount reaches zero then the only other references (if any) are\nWeak, so we drop the inner value.

\n
Examples
\n
use std::sync::Arc;\n\nstruct Foo;\n\nimpl Drop for Foo {\n    fn drop(&mut self) {\n        println!(\"dropped!\");\n    }\n}\n\nlet foo  = Arc::new(Foo);\nlet foo2 = Arc::clone(&foo);\n\ndrop(foo);    // Doesn't print anything\ndrop(foo2);   // Prints \"dropped!\"
\n
","Drop","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T, U, A> CoerceUnsized<Arc<U, A>> for Arc<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Sync for Arc<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Sync,

","Sync","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.5.0 · source§

impl<T, A> AsRef<T> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Send for Arc<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Send,

","Send","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Borrow<T> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.9.0 · source§

impl<T, A> UnwindSafe for Arc<T, A>
where\n T: RefUnwindSafe + ?Sized,\n A: Allocator + UnwindSafe,

","UnwindSafe","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Hash for Arc<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

source§

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Clone for Arc<T, A>
where\n A: Allocator + Clone,\n T: ?Sized,

source§

fn clone(&self) -> Arc<T, A>

Makes a clone of the Arc pointer.

\n

This creates another pointer to the same allocation, increasing the\nstrong reference count.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet _ = Arc::clone(&five);
\n
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Display for Arc<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Eq for Arc<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T> Default for Arc<T>
where\n T: Default,

source§

fn default() -> Arc<T>

Creates a new Arc<T>, with the Default value for T.

\n
Examples
\n
use std::sync::Arc;\n\nlet x: Arc<i32> = Default::default();\nassert_eq!(*x, 0);
\n
","Default","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> Debug for Arc<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
1.0.0 · source§

impl<T, A> PartialEq for Arc<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

source§

fn eq(&self, other: &Arc<T, A>) -> bool

Equality for two Arcs.

\n

Two Arcs are equal if their inner values are equal, even if they are\nstored in different allocation.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Arcs that point to the same allocation are always equal.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five == Arc::new(5));
\n
source§

fn ne(&self, other: &Arc<T, A>) -> bool

Inequality for two Arcs.

\n

Two Arcs are not equal if their inner values are not equal.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Arcs that point to the same value are always equal.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five != Arc::new(6));
\n
","PartialEq","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T> Encode for Arc<T>
where\n T: Encode + ?Sized,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<'de, T> BorrowDecode<'de> for Arc<T>
where\n T: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Arc<T>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
source§

impl<T> Decode for Arc<T>
where\n T: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Arc<T>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"],["
§

impl<S> Subscriber for Arc<S>
where\n S: Subscriber + ?Sized,

§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this subscriber, returning whether or not\nthe subscriber is interested in being notified about the callsite. Read more
§

fn enabled(&self, metadata: &Metadata<'_>) -> bool

Returns true if a span or event with the specified metadata would be\nrecorded. Read more
§

fn max_level_hint(&self) -> Option<LevelFilter>

Returns the highest verbosity level that this Subscriber will\nenable, or None, if the subscriber does not implement level-based\nfiltering or chooses not to implement this method. Read more
§

fn new_span(&self, span: &Attributes<'_>) -> Id

Visit the construction of a new span, returning a new span ID for the\nspan being constructed. Read more
§

fn record(&self, span: &Id, values: &Record<'_>)

Record a set of values on a span. Read more
§

fn record_follows_from(&self, span: &Id, follows: &Id)

Adds an indication that span follows from the span with the id\nfollows. Read more
§

fn event_enabled(&self, event: &Event<'_>) -> bool

Determine if an [Event] should be recorded. Read more
§

fn event(&self, event: &Event<'_>)

Records that an Event has occurred. Read more
§

fn enter(&self, span: &Id)

Records that a span has been entered. Read more
§

fn exit(&self, span: &Id)

Records that a span has been exited. Read more
§

fn clone_span(&self, id: &Id) -> Id

Notifies the subscriber that a span ID has been cloned. Read more
§

fn try_close(&self, id: Id) -> bool

Notifies the subscriber that a span ID has been dropped, and returns\ntrue if there are now 0 IDs that refer to that span. Read more
§

fn drop_span(&self, id: Id)

👎Deprecated since 0.1.2: use Subscriber::try_close instead
This method is deprecated. Read more
§

fn current_span(&self) -> Current

Returns a type representing this subscriber’s view of the current span. Read more
§

unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()>

If self is the same type as the provided TypeId, returns an untyped\n*const pointer to that type. Otherwise, returns None. Read more
§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Invoked when this subscriber becomes a [Dispatch]. Read more
","Subscriber","karyon_core::event::ArcEventSys","karyon_core::pubsub::ArcPublisher","karyon_core::Executor","karyon_core::GlobalExecutor"]], +"karyon_p2p":[["
source§

impl<T> Arc<T>

1.0.0 · source

pub fn new(data: T) -> Arc<T>

Constructs a new Arc<T>.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);
\n
1.60.0 · source

pub fn new_cyclic<F>(data_fn: F) -> Arc<T>
where\n F: FnOnce(&Weak<T>) -> T,

Constructs a new Arc<T> while giving you a Weak<T> to the allocation,\nto allow you to construct a T which holds a weak pointer to itself.

\n

Generally, a structure circularly referencing itself, either directly or\nindirectly, should not hold a strong reference to itself to prevent a memory leak.\nUsing this function, you get access to the weak pointer during the\ninitialization of T, before the Arc<T> is created, such that you can\nclone and store it inside the T.

\n

new_cyclic first allocates the managed allocation for the Arc<T>,\nthen calls your closure, giving it a Weak<T> to this allocation,\nand only afterwards completes the construction of the Arc<T> by placing\nthe T returned from your closure into the allocation.

\n

Since the new Arc<T> is not fully-constructed until Arc<T>::new_cyclic\nreturns, calling upgrade on the weak reference inside your closure will\nfail and result in a None value.

\n
Panics
\n

If data_fn panics, the panic is propagated to the caller, and the\ntemporary Weak<T> is dropped normally.

\n
Example
\n
use std::sync::{Arc, Weak};\n\nstruct Gadget {\n    me: Weak<Gadget>,\n}\n\nimpl Gadget {\n    /// Construct a reference counted Gadget.\n    fn new() -> Arc<Self> {\n        // `me` is a `Weak<Gadget>` pointing at the new allocation of the\n        // `Arc` we're constructing.\n        Arc::new_cyclic(|me| {\n            // Create the actual struct here.\n            Gadget { me: me.clone() }\n        })\n    }\n\n    /// Return a reference counted pointer to Self.\n    fn me(&self) -> Arc<Self> {\n        self.me.upgrade().unwrap()\n    }\n}
\n
source

pub fn new_uninit() -> Arc<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Arc with uninitialized contents.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut five = Arc::<u32>::new_uninit();\n\n// Deferred initialization:\nArc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed() -> Arc<MaybeUninit<T>>

🔬This is a nightly-only experimental API. (new_uninit)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n\nuse std::sync::Arc;\n\nlet zero = Arc::<u32>::new_zeroed();\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
1.33.0 · source

pub fn pin(data: T) -> Pin<Arc<T>>

Constructs a new Pin<Arc<T>>. If T does not implement Unpin, then\ndata will be pinned in memory and unable to be moved.

\n
source

pub fn try_pin(data: T) -> Result<Pin<Arc<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T>>, return an error if allocation fails.

\n
source

pub fn try_new(data: T) -> Result<Arc<T>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T>, returning an error if allocation fails.

\n
Examples
\n
#![feature(allocator_api)]\nuse std::sync::Arc;\n\nlet five = Arc::try_new(5)?;
\n
source

pub fn try_new_uninit() -> Result<Arc<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, returning an error\nif allocation fails.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut five = Arc::<u32>::try_new_uninit()?;\n\n// Deferred initialization:\nArc::get_mut(&mut five).unwrap().write(5);\n\nlet five = unsafe { five.assume_init() };\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed() -> Result<Arc<MaybeUninit<T>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, returning an error if allocation fails.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n\nuse std::sync::Arc;\n\nlet zero = Arc::<u32>::try_new_zeroed()?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,

source

pub fn allocator(this: &Arc<T, A>) -> &A

🔬This is a nightly-only experimental API. (allocator_api)

Returns a reference to the underlying allocator.

\n

Note: this is an associated function, which means that you have\nto call it as Arc::allocator(&a) instead of a.allocator(). This\nis so that there is no conflict with a method on the inner type.

\n
source

pub fn new_in(data: T, alloc: A) -> Arc<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T> in the provided allocator.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);
\n
source

pub fn new_uninit_in(alloc: A) -> Arc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents in the provided allocator.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(get_mut_unchecked)]\n#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet mut five = Arc::<u32, _>::new_uninit_in(System);\n\nlet five = unsafe {\n    // Deferred initialization:\n    Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5)
\n
source

pub fn new_zeroed_in(alloc: A) -> Arc<MaybeUninit<T>, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit)]\n#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet zero = Arc::<u32, _>::new_zeroed_in(System);\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0)
\n
source

pub fn pin_in(data: T, alloc: A) -> Pin<Arc<T, A>>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T, A>> in the provided allocator. If T does not implement Unpin,\nthen data will be pinned in memory and unable to be moved.

\n
source

pub fn try_pin_in(data: T, alloc: A) -> Result<Pin<Arc<T, A>>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Pin<Arc<T, A>> in the provided allocator, return an error if allocation\nfails.

\n
source

pub fn try_new_in(data: T, alloc: A) -> Result<Arc<T, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc<T, A> in the provided allocator, returning an error if allocation fails.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::try_new_in(5, System)?;
\n
source

pub fn try_new_uninit_in(alloc: A) -> Result<Arc<MaybeUninit<T>, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, in the provided allocator, returning an\nerror if allocation fails.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet mut five = Arc::<u32, _>::try_new_uninit_in(System)?;\n\nlet five = unsafe {\n    // Deferred initialization:\n    Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);\n\n    five.assume_init()\n};\n\nassert_eq!(*five, 5);
\n
source

pub fn try_new_zeroed_in(alloc: A) -> Result<Arc<MaybeUninit<T>, A>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Arc with uninitialized contents, with the memory\nbeing filled with 0 bytes, in the provided allocator, returning an error if allocation\nfails.

\n

See MaybeUninit::zeroed for examples of correct and incorrect usage\nof this method.

\n
Examples
\n
#![feature(new_uninit, allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet zero = Arc::<u32, _>::try_new_zeroed_in(System)?;\nlet zero = unsafe { zero.assume_init() };\n\nassert_eq!(*zero, 0);
\n
1.4.0 · source

pub fn try_unwrap(this: Arc<T, A>) -> Result<T, Arc<T, A>>

Returns the inner value, if the Arc has exactly one strong reference.

\n

Otherwise, an Err is returned with the same Arc that was\npassed in.

\n

This will succeed even if there are outstanding weak references.

\n

It is strongly recommended to use Arc::into_inner instead if you don’t\nwant to keep the Arc in the Err case.\nImmediately dropping the Err payload, like in the expression\nArc::try_unwrap(this).ok(), can still cause the strong count to\ndrop to zero and the inner value of the Arc to be dropped:\nFor instance if two threads each execute this expression in parallel, then\nthere is a race condition. The threads could first both check whether they\nhave the last clone of their Arc via Arc::try_unwrap, and then\nboth drop their Arc in the call to ok,\ntaking the strong count from two down to zero.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(3);\nassert_eq!(Arc::try_unwrap(x), Ok(3));\n\nlet x = Arc::new(4);\nlet _y = Arc::clone(&x);\nassert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4);
\n
1.70.0 · source

pub fn into_inner(this: Arc<T, A>) -> Option<T>

Returns the inner value, if the Arc has exactly one strong reference.

\n

Otherwise, None is returned and the Arc is dropped.

\n

This will succeed even if there are outstanding weak references.

\n

If Arc::into_inner is called on every clone of this Arc,\nit is guaranteed that exactly one of the calls returns the inner value.\nThis means in particular that the inner value is not dropped.

\n

The similar expression Arc::try_unwrap(this).ok() does not\noffer such a guarantee. See the last example below\nand the documentation of Arc::try_unwrap.

\n
Examples
\n

Minimal example demonstrating the guarantee that Arc::into_inner gives.

\n\n
use std::sync::Arc;\n\nlet x = Arc::new(3);\nlet y = Arc::clone(&x);\n\n// Two threads calling `Arc::into_inner` on both clones of an `Arc`:\nlet x_thread = std::thread::spawn(|| Arc::into_inner(x));\nlet y_thread = std::thread::spawn(|| Arc::into_inner(y));\n\nlet x_inner_value = x_thread.join().unwrap();\nlet y_inner_value = y_thread.join().unwrap();\n\n// One of the threads is guaranteed to receive the inner value:\nassert!(matches!(\n    (x_inner_value, y_inner_value),\n    (None, Some(3)) | (Some(3), None)\n));\n// The result could also be `(None, None)` if the threads called\n// `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead.
\n

A more practical example demonstrating the need for Arc::into_inner:

\n\n
use std::sync::Arc;\n\n// Definition of a simple singly linked list using `Arc`:\n#[derive(Clone)]\nstruct LinkedList<T>(Option<Arc<Node<T>>>);\nstruct Node<T>(T, Option<Arc<Node<T>>>);\n\n// Dropping a long `LinkedList<T>` relying on the destructor of `Arc`\n// can cause a stack overflow. To prevent this, we can provide a\n// manual `Drop` implementation that does the destruction in a loop:\nimpl<T> Drop for LinkedList<T> {\n    fn drop(&mut self) {\n        let mut link = self.0.take();\n        while let Some(arc_node) = link.take() {\n            if let Some(Node(_value, next)) = Arc::into_inner(arc_node) {\n                link = next;\n            }\n        }\n    }\n}\n\n// Implementation of `new` and `push` omitted\nimpl<T> LinkedList<T> {\n    /* ... */\n}\n\n// The following code could have still caused a stack overflow\n// despite the manual `Drop` impl if that `Drop` impl had used\n// `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`.\n\n// Create a long list and clone it\nlet mut x = LinkedList::new();\nfor i in 0..100000 {\n    x.push(i); // Adds i to the front of x\n}\nlet y = x.clone();\n\n// Drop the clones in parallel\nlet x_thread = std::thread::spawn(|| drop(x));\nlet y_thread = std::thread::spawn(|| drop(y));\nx_thread.join().unwrap();\ny_thread.join().unwrap();
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T> Arc<T>
where\n T: ?Sized,

1.17.0 · source

pub unsafe fn from_raw(ptr: *const T) -> Arc<T>

Constructs an Arc<T> from a raw pointer.

\n

The raw pointer must have been previously returned by a call to\nArc<U>::into_raw where U must have the same size and\nalignment as T. This is trivially true if U is T.\nNote that if U is not T but has the same size and alignment, this is\nbasically like transmuting references of different types. See\nmem::transmute for more information on what\nrestrictions apply in this case.

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Arc<T> is never accessed.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet x_ptr = Arc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Arc` to prevent leak.\n    let x = Arc::from_raw(x_ptr);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n
1.51.0 · source

pub unsafe fn increment_strong_count(ptr: *const T)

Increments the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count(ptr);\n\n    // This assertion is deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw(ptr);\n    assert_eq!(2, Arc::strong_count(&five));\n}
\n
1.51.0 · source

pub unsafe fn decrement_strong_count(ptr: *const T)

Decrements the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method. This method can be used to release the final\nArc and backing storage, but should not be called after the final Arc has been\nreleased.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count(ptr);\n\n    // Those assertions are deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw(ptr);\n    assert_eq!(2, Arc::strong_count(&five));\n    Arc::decrement_strong_count(ptr);\n    assert_eq!(1, Arc::strong_count(&five));\n}
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

1.17.0 · source

pub fn into_raw(this: Arc<T, A>) -> *const T

Consumes the Arc, returning the wrapped pointer.

\n

To avoid a memory leak the pointer must be converted back to an Arc using\nArc::from_raw.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet x_ptr = Arc::into_raw(x);\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
1.45.0 · source

pub fn as_ptr(this: &Arc<T, A>) -> *const T

Provides a raw pointer to the data.

\n

The counts are not affected in any way and the Arc is not consumed. The pointer is valid for\nas long as there are strong counts in the Arc.

\n
Examples
\n
use std::sync::Arc;\n\nlet x = Arc::new(\"hello\".to_owned());\nlet y = Arc::clone(&x);\nlet x_ptr = Arc::as_ptr(&x);\nassert_eq!(x_ptr, Arc::as_ptr(&y));\nassert_eq!(unsafe { &*x_ptr }, \"hello\");
\n
source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Arc<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs an Arc<T, A> from a raw pointer.

\n

The raw pointer must have been previously returned by a call to\nArc<U, A>::into_raw where U must have the same size and\nalignment as T. This is trivially true if U is T.\nNote that if U is not T but has the same size and alignment, this is\nbasically like transmuting references of different types. See\nmem::transmute for more information on what\nrestrictions apply in this case.

\n

The raw pointer must point to a block of memory allocated by alloc

\n

The user of from_raw has to make sure a specific value of T is only\ndropped once.

\n

This function is unsafe because improper use may lead to memory unsafety,\neven if the returned Arc<T> is never accessed.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet x = Arc::new_in(\"hello\".to_owned(), System);\nlet x_ptr = Arc::into_raw(x);\n\nunsafe {\n    // Convert back to an `Arc` to prevent leak.\n    let x = Arc::from_raw_in(x_ptr, System);\n    assert_eq!(&*x, \"hello\");\n\n    // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe.\n}\n\n// The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
\n
1.4.0 · source

pub fn downgrade(this: &Arc<T, A>) -> Weak<T, A>
where\n A: Clone,

Creates a new Weak pointer to this allocation.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet weak_five = Arc::downgrade(&five);
\n
1.15.0 · source

pub fn weak_count(this: &Arc<T, A>) -> usize

Gets the number of Weak pointers to this allocation.

\n
Safety
\n

This method by itself is safe, but using it correctly requires extra care.\nAnother thread can change the weak count at any time,\nincluding potentially between calling this method and acting on the result.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet _weak_five = Arc::downgrade(&five);\n\n// This assertion is deterministic because we haven't shared\n// the `Arc` or `Weak` between threads.\nassert_eq!(1, Arc::weak_count(&five));
\n
1.15.0 · source

pub fn strong_count(this: &Arc<T, A>) -> usize

Gets the number of strong (Arc) pointers to this allocation.

\n
Safety
\n

This method by itself is safe, but using it correctly requires extra care.\nAnother thread can change the strong count at any time,\nincluding potentially between calling this method and acting on the result.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet _also_five = Arc::clone(&five);\n\n// This assertion is deterministic because we haven't shared\n// the `Arc` between threads.\nassert_eq!(2, Arc::strong_count(&five));
\n
source

pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
where\n A: Clone,

🔬This is a nightly-only experimental API. (allocator_api)

Increments the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, and the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) for the duration of this method,, and ptr must point to a block of memory\nallocated by alloc.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count_in(ptr, System);\n\n    // This assertion is deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw_in(ptr, System);\n    assert_eq!(2, Arc::strong_count(&five));\n}
\n
source

pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A)

🔬This is a nightly-only experimental API. (allocator_api)

Decrements the strong reference count on the Arc<T> associated with the\nprovided pointer by one.

\n
Safety
\n

The pointer must have been obtained through Arc::into_raw, the\nassociated Arc instance must be valid (i.e. the strong count must be at\nleast 1) when invoking this method, and ptr must point to a block of memory\nallocated by alloc. This method can be used to release the final\nArc and backing storage, but should not be called after the final Arc has been\nreleased.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Arc;\nuse std::alloc::System;\n\nlet five = Arc::new_in(5, System);\n\nunsafe {\n    let ptr = Arc::into_raw(five);\n    Arc::increment_strong_count_in(ptr, System);\n\n    // Those assertions are deterministic because we haven't shared\n    // the `Arc` between threads.\n    let five = Arc::from_raw_in(ptr, System);\n    assert_eq!(2, Arc::strong_count(&five));\n    Arc::decrement_strong_count_in(ptr, System);\n    assert_eq!(1, Arc::strong_count(&five));\n}
\n
1.17.0 · source

pub fn ptr_eq(this: &Arc<T, A>, other: &Arc<T, A>) -> bool

Returns true if the two Arcs point to the same allocation in a vein similar to\nptr::eq. This function ignores the metadata of dyn Trait pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\nlet same_five = Arc::clone(&five);\nlet other_five = Arc::new(5);\n\nassert!(Arc::ptr_eq(&five, &same_five));\nassert!(!Arc::ptr_eq(&five, &other_five));
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, A> Arc<T, A>
where\n T: Clone,\n A: Allocator + Clone,

1.4.0 · source

pub fn make_mut(this: &mut Arc<T, A>) -> &mut T

Makes a mutable reference into the given Arc.

\n

If there are other Arc pointers to the same allocation, then make_mut will\nclone the inner value to a new allocation to ensure unique ownership. This is also\nreferred to as clone-on-write.

\n

However, if there are no other Arc pointers to this allocation, but some Weak\npointers, then the Weak pointers will be dissociated and the inner value will not\nbe cloned.

\n

See also get_mut, which will fail rather than cloning the inner value\nor dissociating Weak pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet mut data = Arc::new(5);\n\n*Arc::make_mut(&mut data) += 1;         // Won't clone anything\nlet mut other_data = Arc::clone(&data); // Won't clone inner data\n*Arc::make_mut(&mut data) += 1;         // Clones inner data\n*Arc::make_mut(&mut data) += 1;         // Won't clone anything\n*Arc::make_mut(&mut other_data) *= 2;   // Won't clone anything\n\n// Now `data` and `other_data` point to different allocations.\nassert_eq!(*data, 8);\nassert_eq!(*other_data, 12);
\n

Weak pointers will be dissociated:

\n\n
use std::sync::Arc;\n\nlet mut data = Arc::new(75);\nlet weak = Arc::downgrade(&data);\n\nassert!(75 == *data);\nassert!(75 == *weak.upgrade().unwrap());\n\n*Arc::make_mut(&mut data) += 1;\n\nassert!(76 == *data);\nassert!(weak.upgrade().is_none());
\n
1.76.0 · source

pub fn unwrap_or_clone(this: Arc<T, A>) -> T

If we have the only reference to T then unwrap it. Otherwise, clone T and return the\nclone.

\n

Assuming arc_t is of type Arc<T>, this function is functionally equivalent to\n(*arc_t).clone(), but will avoid cloning the inner value where possible.

\n
Examples
\n
let inner = String::from(\"test\");\nlet ptr = inner.as_ptr();\n\nlet arc = Arc::new(inner);\nlet inner = Arc::unwrap_or_clone(arc);\n// The inner value was not cloned\nassert!(ptr::eq(ptr, inner.as_ptr()));\n\nlet arc = Arc::new(inner);\nlet arc2 = arc.clone();\nlet inner = Arc::unwrap_or_clone(arc);\n// Because there were 2 references, we had to clone the inner value.\nassert!(!ptr::eq(ptr, inner.as_ptr()));\n// `arc2` is the last reference, so when we unwrap it we get back\n// the original `String`.\nlet inner = Arc::unwrap_or_clone(arc2);\nassert!(ptr::eq(ptr, inner.as_ptr()));
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, A> Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

1.4.0 · source

pub fn get_mut(this: &mut Arc<T, A>) -> Option<&mut T>

Returns a mutable reference into the given Arc, if there are\nno other Arc or Weak pointers to the same allocation.

\n

Returns None otherwise, because it is not safe to\nmutate a shared value.

\n

See also make_mut, which will clone\nthe inner value when there are other Arc pointers.

\n
Examples
\n
use std::sync::Arc;\n\nlet mut x = Arc::new(3);\n*Arc::get_mut(&mut x).unwrap() = 4;\nassert_eq!(*x, 4);\n\nlet _y = Arc::clone(&x);\nassert!(Arc::get_mut(&mut x).is_none());
\n
source

pub unsafe fn get_mut_unchecked(this: &mut Arc<T, A>) -> &mut T

🔬This is a nightly-only experimental API. (get_mut_unchecked)

Returns a mutable reference into the given Arc,\nwithout any check.

\n

See also get_mut, which is safe and does appropriate checks.

\n
Safety
\n

If any other Arc or Weak pointers to the same allocation exist, then\nthey must not be dereferenced or have active borrows for the duration\nof the returned borrow, and their inner type must be exactly the same as the\ninner type of this Rc (including lifetimes). This is trivially the case if no\nsuch pointers exist, for example immediately after Arc::new.

\n
Examples
\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet mut x = Arc::new(String::new());\nunsafe {\n    Arc::get_mut_unchecked(&mut x).push_str(\"foo\")\n}\nassert_eq!(*x, \"foo\");
\n

Other Arc pointers to the same allocation must be to the same type.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet x: Arc<str> = Arc::from(\"Hello, world!\");\nlet mut y: Arc<[u8]> = x.clone().into();\nunsafe {\n    // this is Undefined Behavior, because x's inner type is str, not [u8]\n    Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8\n}\nprintln!(\"{}\", &*x); // Invalid UTF-8 in a str
\n

Other Arc pointers to the same allocation must be to the exact same type, including lifetimes.

\n\n
#![feature(get_mut_unchecked)]\n\nuse std::sync::Arc;\n\nlet x: Arc<&str> = Arc::new(\"Hello, world!\");\n{\n    let s = String::from(\"Oh, no!\");\n    let mut y: Arc<&str> = x.clone().into();\n    unsafe {\n        // this is Undefined Behavior, because x's inner type\n        // is &'long str, not &'short str\n        *Arc::get_mut_unchecked(&mut y) = &s;\n    }\n}\nprintln!(\"{}\", &*x); // Use-after-free
\n
",0,"karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.63.0 · source§

impl<T> AsRawFd for Arc<T>
where\n T: AsRawFd,

This impl allows implementing traits that require AsRawFd on Arc.

\n\n
use std::net::UdpSocket;\nuse std::sync::Arc;\ntrait MyTrait: AsRawFd {\n}\nimpl MyTrait for Arc<UdpSocket> {}\nimpl MyTrait for Box<UdpSocket> {}
\n
source§

fn as_raw_fd(&self) -> i32

Extracts the raw file descriptor. Read more
","AsRawFd","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.64.0 · source§

impl<T> AsFd for Arc<T>
where\n T: AsFd,

This impl allows implementing traits that require AsFd on Arc.

\n\n
use std::net::UdpSocket;\nuse std::sync::Arc;\n\ntrait MyTrait: AsFd {}\nimpl MyTrait for Arc<UdpSocket> {}\nimpl MyTrait for Box<UdpSocket> {}
\n
source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
","AsFd","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.33.0 · source§

impl<T, A> Unpin for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

","Unpin","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, U> DispatchFromDyn<Arc<U>> for Arc<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.52.0 · source§

impl<T> Error for Arc<T>
where\n T: Error + ?Sized,

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
source§

fn provide<'a>(&'a self, req: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
","Error","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Pointer for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
","Pointer","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> PartialOrd for Arc<T, A>
where\n T: PartialOrd + ?Sized,\n A: Allocator,

source§

fn partial_cmp(&self, other: &Arc<T, A>) -> Option<Ordering>

Partial comparison for two Arcs.

\n

The two are compared by calling partial_cmp() on their inner values.

\n
Examples
\n
use std::sync::Arc;\nuse std::cmp::Ordering;\n\nlet five = Arc::new(5);\n\nassert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6)));
\n
source§

fn lt(&self, other: &Arc<T, A>) -> bool

Less-than comparison for two Arcs.

\n

The two are compared by calling < on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five < Arc::new(6));
\n
source§

fn le(&self, other: &Arc<T, A>) -> bool

‘Less than or equal to’ comparison for two Arcs.

\n

The two are compared by calling <= on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five <= Arc::new(5));
\n
source§

fn gt(&self, other: &Arc<T, A>) -> bool

Greater-than comparison for two Arcs.

\n

The two are compared by calling > on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five > Arc::new(4));
\n
source§

fn ge(&self, other: &Arc<T, A>) -> bool

‘Greater than or equal to’ comparison for two Arcs.

\n

The two are compared by calling >= on their inner values.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five >= Arc::new(5));
\n
","PartialOrd","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Deref for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
","Deref","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Ord for Arc<T, A>
where\n T: Ord + ?Sized,\n A: Allocator,

source§

fn cmp(&self, other: &Arc<T, A>) -> Ordering

Comparison for two Arcs.

\n

The two are compared by calling cmp() on their inner values.

\n
Examples
\n
use std::sync::Arc;\nuse std::cmp::Ordering;\n\nlet five = Arc::new(5);\n\nassert_eq!(Ordering::Less, five.cmp(&Arc::new(6)));
\n
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.6.0 · source§

impl<T> From<T> for Arc<T>

source§

fn from(t: T) -> Arc<T>

Converts a T into an Arc<T>

\n

The conversion moves the value into a\nnewly allocated Arc. It is equivalent to\ncalling Arc::new(t).

\n
Example
\n
let x = 5;\nlet arc = Arc::new(5);\n\nassert_eq!(Arc::from(x), arc);
\n
","From","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.45.0 · source§

impl<'a, B> From<Cow<'a, B>> for Arc<B>
where\n B: ToOwned + ?Sized,\n Arc<B>: From<&'a B> + From<<B as ToOwned>::Owned>,

source§

fn from(cow: Cow<'a, B>) -> Arc<B>

Create an atomically reference-counted pointer from\na clone-on-write pointer by copying its content.

\n
Example
\n
let cow: Cow<'_, str> = Cow::Borrowed(\"eggplant\");\nlet shared: Arc<str> = Arc::from(cow);\nassert_eq!(\"eggplant\", &shared[..]);
\n
","From>","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.21.0 · source§

impl<T, A> From<Box<T, A>> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn from(v: Box<T, A>) -> Arc<T, A>

Move a boxed object to a new, reference-counted allocation.

\n
Example
\n
let unique: Box<str> = Box::from(\"eggplant\");\nlet shared: Arc<str> = Arc::from(unique);\nassert_eq!(\"eggplant\", &shared[..]);
\n
","From>","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Drop for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Drops the Arc.

\n

This will decrement the strong reference count. If the strong reference\ncount reaches zero then the only other references (if any) are\nWeak, so we drop the inner value.

\n
Examples
\n
use std::sync::Arc;\n\nstruct Foo;\n\nimpl Drop for Foo {\n    fn drop(&mut self) {\n        println!(\"dropped!\");\n    }\n}\n\nlet foo  = Arc::new(Foo);\nlet foo2 = Arc::clone(&foo);\n\ndrop(foo);    // Doesn't print anything\ndrop(foo2);   // Prints \"dropped!\"
\n
","Drop","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T, U, A> CoerceUnsized<Arc<U, A>> for Arc<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Sync for Arc<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Sync,

","Sync","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.5.0 · source§

impl<T, A> AsRef<T> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
","AsRef","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Send for Arc<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Send,

","Send","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Borrow<T> for Arc<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
","Borrow","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.9.0 · source§

impl<T, A> UnwindSafe for Arc<T, A>
where\n T: RefUnwindSafe + ?Sized,\n A: Allocator + UnwindSafe,

","UnwindSafe","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Hash for Arc<T, A>
where\n T: Hash + ?Sized,\n A: Allocator,

source§

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Clone for Arc<T, A>
where\n A: Allocator + Clone,\n T: ?Sized,

source§

fn clone(&self) -> Arc<T, A>

Makes a clone of the Arc pointer.

\n

This creates another pointer to the same allocation, increasing the\nstrong reference count.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet _ = Arc::clone(&five);
\n
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Display for Arc<T, A>
where\n T: Display + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Eq for Arc<T, A>
where\n T: Eq + ?Sized,\n A: Allocator,

","Eq","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T> Default for Arc<T>
where\n T: Default,

source§

fn default() -> Arc<T>

Creates a new Arc<T>, with the Default value for T.

\n
Examples
\n
use std::sync::Arc;\n\nlet x: Arc<i32> = Default::default();\nassert_eq!(*x, 0);
\n
","Default","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> Debug for Arc<T, A>
where\n T: Debug + ?Sized,\n A: Allocator,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
1.0.0 · source§

impl<T, A> PartialEq for Arc<T, A>
where\n T: PartialEq + ?Sized,\n A: Allocator,

source§

fn eq(&self, other: &Arc<T, A>) -> bool

Equality for two Arcs.

\n

Two Arcs are equal if their inner values are equal, even if they are\nstored in different allocation.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Arcs that point to the same allocation are always equal.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five == Arc::new(5));
\n
source§

fn ne(&self, other: &Arc<T, A>) -> bool

Inequality for two Arcs.

\n

Two Arcs are not equal if their inner values are not equal.

\n

If T also implements Eq (implying reflexivity of equality),\ntwo Arcs that point to the same value are always equal.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nassert!(five != Arc::new(6));
\n
","PartialEq","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T> Encode for Arc<T>
where\n T: Encode + ?Sized,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<'de, T> BorrowDecode<'de> for Arc<T>
where\n T: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Arc<T>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
source§

impl<T> Decode for Arc<T>
where\n T: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Arc<T>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
§

impl<S> Subscriber for Arc<S>
where\n S: Subscriber + ?Sized,

§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this subscriber, returning whether or not\nthe subscriber is interested in being notified about the callsite. Read more
§

fn enabled(&self, metadata: &Metadata<'_>) -> bool

Returns true if a span or event with the specified metadata would be\nrecorded. Read more
§

fn max_level_hint(&self) -> Option<LevelFilter>

Returns the highest verbosity level that this Subscriber will\nenable, or None, if the subscriber does not implement level-based\nfiltering or chooses not to implement this method. Read more
§

fn new_span(&self, span: &Attributes<'_>) -> Id

Visit the construction of a new span, returning a new span ID for the\nspan being constructed. Read more
§

fn record(&self, span: &Id, values: &Record<'_>)

Record a set of values on a span. Read more
§

fn record_follows_from(&self, span: &Id, follows: &Id)

Adds an indication that span follows from the span with the id\nfollows. Read more
§

fn event_enabled(&self, event: &Event<'_>) -> bool

Determine if an [Event] should be recorded. Read more
§

fn event(&self, event: &Event<'_>)

Records that an Event has occurred. Read more
§

fn enter(&self, span: &Id)

Records that a span has been entered. Read more
§

fn exit(&self, span: &Id)

Records that a span has been exited. Read more
§

fn clone_span(&self, id: &Id) -> Id

Notifies the subscriber that a span ID has been cloned. Read more
§

fn try_close(&self, id: Id) -> bool

Notifies the subscriber that a span ID has been dropped, and returns\ntrue if there are now 0 IDs that refer to that span. Read more
§

fn drop_span(&self, id: Id)

👎Deprecated since 0.1.2: use Subscriber::try_close instead
This method is deprecated. Read more
§

fn current_span(&self) -> Current

Returns a type representing this subscriber’s view of the current span. Read more
§

unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()>

If self is the same type as the provided TypeId, returns an untyped\n*const pointer to that type. Otherwise, returns None. Read more
§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Invoked when this subscriber becomes a [Dispatch]. Read more
","Subscriber","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
§

impl<Sp> LocalSpawn for Arc<Sp>
where\n Sp: LocalSpawn + ?Sized,

§

fn spawn_local_obj(\n &self,\n future: LocalFutureObj<'static, ()>\n) -> Result<(), SpawnError>

Spawns a future that will be run to completion. Read more
§

fn status_local(&self) -> Result<(), SpawnError>

Determines whether the executor is able to spawn new tasks. Read more
","LocalSpawn","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"],["
§

impl<Sp> Spawn for Arc<Sp>
where\n Sp: Spawn + ?Sized,

§

fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError>

Spawns a future that will be run to completion. Read more
§

fn status(&self) -> Result<(), SpawnError>

Determines whether the executor is able to spawn new tasks. Read more
","Spawn","karyon_p2p::backend::ArcBackend","karyon_p2p::discovery::ArcDiscovery","karyon_p2p::peer::ArcPeer","karyon_p2p::peer_pool::ArcPeerPool","karyon_p2p::protocol::ArcProtocol"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/alloc/sync/struct.Weak.js b/type.impl/alloc/sync/struct.Weak.js new file mode 100644 index 00000000..06eb5789 --- /dev/null +++ b/type.impl/alloc/sync/struct.Weak.js @@ -0,0 +1,4 @@ +(function() {var type_impls = { +"karyon_core":[["
source§

impl<T> Weak<T>

1.10.0 (const: 1.73.0) · source

pub const fn new() -> Weak<T>

Constructs a new Weak<T>, without allocating any memory.\nCalling upgrade on the return value always gives None.

\n
Examples
\n
use std::sync::Weak;\n\nlet empty: Weak<i64> = Weak::new();\nassert!(empty.upgrade().is_none());
\n
",0,"karyon_core::event::WeakEventSys"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,

source

pub fn new_in(alloc: A) -> Weak<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Weak<T, A>, without allocating any memory, technically in the provided\nallocator.\nCalling upgrade on the return value always gives None.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Weak;\nuse std::alloc::System;\n\nlet empty: Weak<i64, _> = Weak::new_in(System);\nassert!(empty.upgrade().is_none());
\n
",0,"karyon_core::event::WeakEventSys"],["
source§

impl<T> Weak<T>
where\n T: ?Sized,

1.45.0 · source

pub unsafe fn from_raw(ptr: *const T) -> Weak<T>

Converts a raw pointer previously created by into_raw back into Weak<T>.

\n

This can be used to safely get a strong reference (by calling upgrade\nlater) or to deallocate the weak count by dropping the Weak<T>.

\n

It takes ownership of one weak reference (with the exception of pointers created by new,\nas these don’t own anything; the method still works on them).

\n
Safety
\n

The pointer must have originated from the into_raw and must still own its potential\nweak reference.

\n

It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this\ntakes ownership of one weak reference currently represented as a raw pointer (the weak\ncount is not modified by this operation) and therefore it must be paired with a previous\ncall to into_raw.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\n\nlet raw_1 = Arc::downgrade(&strong).into_raw();\nlet raw_2 = Arc::downgrade(&strong).into_raw();\n\nassert_eq!(2, Arc::weak_count(&strong));\n\nassert_eq!(\"hello\", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());\nassert_eq!(1, Arc::weak_count(&strong));\n\ndrop(strong);\n\n// Decrement the last weak count.\nassert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
\n
",0,"karyon_core::event::WeakEventSys"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

1.45.0 · source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the object T pointed to by this Weak<T>.

\n

The pointer is valid only if there are some strong references. The pointer may be dangling,\nunaligned or even null otherwise.

\n
Examples
\n
use std::sync::Arc;\nuse std::ptr;\n\nlet strong = Arc::new(\"hello\".to_owned());\nlet weak = Arc::downgrade(&strong);\n// Both point to the same object\nassert!(ptr::eq(&*strong, weak.as_ptr()));\n// The strong here keeps it alive, so we can still access the object.\nassert_eq!(\"hello\", unsafe { &*weak.as_ptr() });\n\ndrop(strong);\n// But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to\n// undefined behaviour.\n// assert_eq!(\"hello\", unsafe { &*weak.as_ptr() });
\n
1.45.0 · source

pub fn into_raw(self) -> *const T

Consumes the Weak<T> and turns it into a raw pointer.

\n

This converts the weak pointer into a raw pointer, while still preserving the ownership of\none weak reference (the weak count is not modified by this operation). It can be turned\nback into the Weak<T> with from_raw.

\n

The same restrictions of accessing the target of the pointer as with\nas_ptr apply.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\nlet weak = Arc::downgrade(&strong);\nlet raw = weak.into_raw();\n\nassert_eq!(1, Arc::weak_count(&strong));\nassert_eq!(\"hello\", unsafe { &*raw });\n\ndrop(unsafe { Weak::from_raw(raw) });\nassert_eq!(0, Arc::weak_count(&strong));
\n
source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Weak<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Converts a raw pointer previously created by into_raw back into Weak<T> in the provided\nallocator.

\n

This can be used to safely get a strong reference (by calling upgrade\nlater) or to deallocate the weak count by dropping the Weak<T>.

\n

It takes ownership of one weak reference (with the exception of pointers created by new,\nas these don’t own anything; the method still works on them).

\n
Safety
\n

The pointer must have originated from the into_raw and must still own its potential\nweak reference, and must point to a block of memory allocated by alloc.

\n

It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this\ntakes ownership of one weak reference currently represented as a raw pointer (the weak\ncount is not modified by this operation) and therefore it must be paired with a previous\ncall to into_raw.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\n\nlet raw_1 = Arc::downgrade(&strong).into_raw();\nlet raw_2 = Arc::downgrade(&strong).into_raw();\n\nassert_eq!(2, Arc::weak_count(&strong));\n\nassert_eq!(\"hello\", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());\nassert_eq!(1, Arc::weak_count(&strong));\n\ndrop(strong);\n\n// Decrement the last weak count.\nassert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
\n
",0,"karyon_core::event::WeakEventSys"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

1.4.0 · source

pub fn upgrade(&self) -> Option<Arc<T, A>>
where\n A: Clone,

Attempts to upgrade the Weak pointer to an Arc, delaying\ndropping of the inner value if successful.

\n

Returns None if the inner value has since been dropped.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet weak_five = Arc::downgrade(&five);\n\nlet strong_five: Option<Arc<_>> = weak_five.upgrade();\nassert!(strong_five.is_some());\n\n// Destroy all strong pointers.\ndrop(strong_five);\ndrop(five);\n\nassert!(weak_five.upgrade().is_none());
\n
1.41.0 · source

pub fn strong_count(&self) -> usize

Gets the number of strong (Arc) pointers pointing to this allocation.

\n

If self was created using Weak::new, this will return 0.

\n
1.41.0 · source

pub fn weak_count(&self) -> usize

Gets an approximation of the number of Weak pointers pointing to this\nallocation.

\n

If self was created using Weak::new, or if there are no remaining\nstrong pointers, this will return 0.

\n
Accuracy
\n

Due to implementation details, the returned value can be off by 1 in\neither direction when other threads are manipulating any Arcs or\nWeaks pointing to the same allocation.

\n
1.39.0 · source

pub fn ptr_eq(&self, other: &Weak<T, A>) -> bool

Returns true if the two Weaks point to the same allocation similar to ptr::eq, or if\nboth don’t point to any allocation (because they were created with Weak::new()). However,\nthis function ignores the metadata of dyn Trait pointers.

\n
Notes
\n

Since this compares pointers it means that Weak::new() will equal each\nother, even though they don’t point to any allocation.

\n
Examples
\n
use std::sync::Arc;\n\nlet first_rc = Arc::new(5);\nlet first = Arc::downgrade(&first_rc);\nlet second = Arc::downgrade(&first_rc);\n\nassert!(first.ptr_eq(&second));\n\nlet third_rc = Arc::new(5);\nlet third = Arc::downgrade(&third_rc);\n\nassert!(!first.ptr_eq(&third));
\n

Comparing Weak::new.

\n\n
use std::sync::{Arc, Weak};\n\nlet first = Weak::new();\nlet second = Weak::new();\nassert!(first.ptr_eq(&second));\n\nlet third_rc = Arc::new(());\nlet third = Arc::downgrade(&third_rc);\nassert!(!first.ptr_eq(&third));
\n
",0,"karyon_core::event::WeakEventSys"],["
source§

impl<T, U> DispatchFromDyn<Weak<U>> for Weak<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_core::event::WeakEventSys"],["
1.4.0 · source§

impl<T, A> Drop for Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Drops the Weak pointer.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nstruct Foo;\n\nimpl Drop for Foo {\n    fn drop(&mut self) {\n        println!(\"dropped!\");\n    }\n}\n\nlet foo = Arc::new(Foo);\nlet weak_foo = Arc::downgrade(&foo);\nlet other_weak_foo = Weak::clone(&weak_foo);\n\ndrop(weak_foo);   // Doesn't print anything\ndrop(foo);        // Prints \"dropped!\"\n\nassert!(other_weak_foo.upgrade().is_none());
\n
","Drop","karyon_core::event::WeakEventSys"],["
source§

impl<T, U, A> CoerceUnsized<Weak<U, A>> for Weak<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_core::event::WeakEventSys"],["
1.4.0 · source§

impl<T, A> Sync for Weak<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Sync,

","Sync","karyon_core::event::WeakEventSys"],["
1.4.0 · source§

impl<T, A> Send for Weak<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Send,

","Send","karyon_core::event::WeakEventSys"],["
1.4.0 · source§

impl<T, A> Clone for Weak<T, A>
where\n A: Allocator + Clone,\n T: ?Sized,

source§

fn clone(&self) -> Weak<T, A>

Makes a clone of the Weak pointer that points to the same allocation.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet weak_five = Arc::downgrade(&Arc::new(5));\n\nlet _ = Weak::clone(&weak_five);
\n
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","karyon_core::event::WeakEventSys"],["
1.10.0 · source§

impl<T> Default for Weak<T>

source§

fn default() -> Weak<T>

Constructs a new Weak<T>, without allocating memory.\nCalling upgrade on the return value always\ngives None.

\n
Examples
\n
use std::sync::Weak;\n\nlet empty: Weak<i64> = Default::default();\nassert!(empty.upgrade().is_none());
\n
","Default","karyon_core::event::WeakEventSys"],["
1.4.0 · source§

impl<T> Debug for Weak<T>
where\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_core::event::WeakEventSys"]], +"karyon_p2p":[["
source§

impl<T> Weak<T>

1.10.0 (const: 1.73.0) · source

pub const fn new() -> Weak<T>

Constructs a new Weak<T>, without allocating any memory.\nCalling upgrade on the return value always gives None.

\n
Examples
\n
use std::sync::Weak;\n\nlet empty: Weak<i64> = Weak::new();\nassert!(empty.upgrade().is_none());
\n
",0,"karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,

source

pub fn new_in(alloc: A) -> Weak<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Constructs a new Weak<T, A>, without allocating any memory, technically in the provided\nallocator.\nCalling upgrade on the return value always gives None.

\n
Examples
\n
#![feature(allocator_api)]\n\nuse std::sync::Weak;\nuse std::alloc::System;\n\nlet empty: Weak<i64, _> = Weak::new_in(System);\nassert!(empty.upgrade().is_none());
\n
",0,"karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T> Weak<T>
where\n T: ?Sized,

1.45.0 · source

pub unsafe fn from_raw(ptr: *const T) -> Weak<T>

Converts a raw pointer previously created by into_raw back into Weak<T>.

\n

This can be used to safely get a strong reference (by calling upgrade\nlater) or to deallocate the weak count by dropping the Weak<T>.

\n

It takes ownership of one weak reference (with the exception of pointers created by new,\nas these don’t own anything; the method still works on them).

\n
Safety
\n

The pointer must have originated from the into_raw and must still own its potential\nweak reference.

\n

It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this\ntakes ownership of one weak reference currently represented as a raw pointer (the weak\ncount is not modified by this operation) and therefore it must be paired with a previous\ncall to into_raw.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\n\nlet raw_1 = Arc::downgrade(&strong).into_raw();\nlet raw_2 = Arc::downgrade(&strong).into_raw();\n\nassert_eq!(2, Arc::weak_count(&strong));\n\nassert_eq!(\"hello\", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());\nassert_eq!(1, Arc::weak_count(&strong));\n\ndrop(strong);\n\n// Decrement the last weak count.\nassert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
\n
",0,"karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

1.45.0 · source

pub fn as_ptr(&self) -> *const T

Returns a raw pointer to the object T pointed to by this Weak<T>.

\n

The pointer is valid only if there are some strong references. The pointer may be dangling,\nunaligned or even null otherwise.

\n
Examples
\n
use std::sync::Arc;\nuse std::ptr;\n\nlet strong = Arc::new(\"hello\".to_owned());\nlet weak = Arc::downgrade(&strong);\n// Both point to the same object\nassert!(ptr::eq(&*strong, weak.as_ptr()));\n// The strong here keeps it alive, so we can still access the object.\nassert_eq!(\"hello\", unsafe { &*weak.as_ptr() });\n\ndrop(strong);\n// But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to\n// undefined behaviour.\n// assert_eq!(\"hello\", unsafe { &*weak.as_ptr() });
\n
1.45.0 · source

pub fn into_raw(self) -> *const T

Consumes the Weak<T> and turns it into a raw pointer.

\n

This converts the weak pointer into a raw pointer, while still preserving the ownership of\none weak reference (the weak count is not modified by this operation). It can be turned\nback into the Weak<T> with from_raw.

\n

The same restrictions of accessing the target of the pointer as with\nas_ptr apply.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\nlet weak = Arc::downgrade(&strong);\nlet raw = weak.into_raw();\n\nassert_eq!(1, Arc::weak_count(&strong));\nassert_eq!(\"hello\", unsafe { &*raw });\n\ndrop(unsafe { Weak::from_raw(raw) });\nassert_eq!(0, Arc::weak_count(&strong));
\n
source

pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Weak<T, A>

🔬This is a nightly-only experimental API. (allocator_api)

Converts a raw pointer previously created by into_raw back into Weak<T> in the provided\nallocator.

\n

This can be used to safely get a strong reference (by calling upgrade\nlater) or to deallocate the weak count by dropping the Weak<T>.

\n

It takes ownership of one weak reference (with the exception of pointers created by new,\nas these don’t own anything; the method still works on them).

\n
Safety
\n

The pointer must have originated from the into_raw and must still own its potential\nweak reference, and must point to a block of memory allocated by alloc.

\n

It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this\ntakes ownership of one weak reference currently represented as a raw pointer (the weak\ncount is not modified by this operation) and therefore it must be paired with a previous\ncall to into_raw.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet strong = Arc::new(\"hello\".to_owned());\n\nlet raw_1 = Arc::downgrade(&strong).into_raw();\nlet raw_2 = Arc::downgrade(&strong).into_raw();\n\nassert_eq!(2, Arc::weak_count(&strong));\n\nassert_eq!(\"hello\", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());\nassert_eq!(1, Arc::weak_count(&strong));\n\ndrop(strong);\n\n// Decrement the last weak count.\nassert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
\n
",0,"karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T, A> Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

1.4.0 · source

pub fn upgrade(&self) -> Option<Arc<T, A>>
where\n A: Clone,

Attempts to upgrade the Weak pointer to an Arc, delaying\ndropping of the inner value if successful.

\n

Returns None if the inner value has since been dropped.

\n
Examples
\n
use std::sync::Arc;\n\nlet five = Arc::new(5);\n\nlet weak_five = Arc::downgrade(&five);\n\nlet strong_five: Option<Arc<_>> = weak_five.upgrade();\nassert!(strong_five.is_some());\n\n// Destroy all strong pointers.\ndrop(strong_five);\ndrop(five);\n\nassert!(weak_five.upgrade().is_none());
\n
1.41.0 · source

pub fn strong_count(&self) -> usize

Gets the number of strong (Arc) pointers pointing to this allocation.

\n

If self was created using Weak::new, this will return 0.

\n
1.41.0 · source

pub fn weak_count(&self) -> usize

Gets an approximation of the number of Weak pointers pointing to this\nallocation.

\n

If self was created using Weak::new, or if there are no remaining\nstrong pointers, this will return 0.

\n
Accuracy
\n

Due to implementation details, the returned value can be off by 1 in\neither direction when other threads are manipulating any Arcs or\nWeaks pointing to the same allocation.

\n
1.39.0 · source

pub fn ptr_eq(&self, other: &Weak<T, A>) -> bool

Returns true if the two Weaks point to the same allocation similar to ptr::eq, or if\nboth don’t point to any allocation (because they were created with Weak::new()). However,\nthis function ignores the metadata of dyn Trait pointers.

\n
Notes
\n

Since this compares pointers it means that Weak::new() will equal each\nother, even though they don’t point to any allocation.

\n
Examples
\n
use std::sync::Arc;\n\nlet first_rc = Arc::new(5);\nlet first = Arc::downgrade(&first_rc);\nlet second = Arc::downgrade(&first_rc);\n\nassert!(first.ptr_eq(&second));\n\nlet third_rc = Arc::new(5);\nlet third = Arc::downgrade(&third_rc);\n\nassert!(!first.ptr_eq(&third));
\n

Comparing Weak::new.

\n\n
use std::sync::{Arc, Weak};\n\nlet first = Weak::new();\nlet second = Weak::new();\nassert!(first.ptr_eq(&second));\n\nlet third_rc = Arc::new(());\nlet third = Arc::downgrade(&third_rc);\nassert!(!first.ptr_eq(&third));
\n
",0,"karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T, U> DispatchFromDyn<Weak<U>> for Weak<T>
where\n T: Unsize<U> + ?Sized,\n U: ?Sized,

","DispatchFromDyn>","karyon_p2p::peer_pool::WeakPeerPool"],["
1.4.0 · source§

impl<T, A> Drop for Weak<T, A>
where\n A: Allocator,\n T: ?Sized,

source§

fn drop(&mut self)

Drops the Weak pointer.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nstruct Foo;\n\nimpl Drop for Foo {\n    fn drop(&mut self) {\n        println!(\"dropped!\");\n    }\n}\n\nlet foo = Arc::new(Foo);\nlet weak_foo = Arc::downgrade(&foo);\nlet other_weak_foo = Weak::clone(&weak_foo);\n\ndrop(weak_foo);   // Doesn't print anything\ndrop(foo);        // Prints \"dropped!\"\n\nassert!(other_weak_foo.upgrade().is_none());
\n
","Drop","karyon_p2p::peer_pool::WeakPeerPool"],["
source§

impl<T, U, A> CoerceUnsized<Weak<U, A>> for Weak<T, A>
where\n T: Unsize<U> + ?Sized,\n A: Allocator,\n U: ?Sized,

","CoerceUnsized>","karyon_p2p::peer_pool::WeakPeerPool"],["
1.4.0 · source§

impl<T, A> Sync for Weak<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Sync,

","Sync","karyon_p2p::peer_pool::WeakPeerPool"],["
1.4.0 · source§

impl<T, A> Send for Weak<T, A>
where\n T: Sync + Send + ?Sized,\n A: Allocator + Send,

","Send","karyon_p2p::peer_pool::WeakPeerPool"],["
1.4.0 · source§

impl<T, A> Clone for Weak<T, A>
where\n A: Allocator + Clone,\n T: ?Sized,

source§

fn clone(&self) -> Weak<T, A>

Makes a clone of the Weak pointer that points to the same allocation.

\n
Examples
\n
use std::sync::{Arc, Weak};\n\nlet weak_five = Arc::downgrade(&Arc::new(5));\n\nlet _ = Weak::clone(&weak_five);
\n
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","karyon_p2p::peer_pool::WeakPeerPool"],["
1.10.0 · source§

impl<T> Default for Weak<T>

source§

fn default() -> Weak<T>

Constructs a new Weak<T>, without allocating memory.\nCalling upgrade on the return value always\ngives None.

\n
Examples
\n
use std::sync::Weak;\n\nlet empty: Weak<i64> = Default::default();\nassert!(empty.upgrade().is_none());
\n
","Default","karyon_p2p::peer_pool::WeakPeerPool"],["
1.4.0 · source§

impl<T> Debug for Weak<T>
where\n T: ?Sized,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_p2p::peer_pool::WeakPeerPool"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/core/ops/function/trait.Fn.js b/type.impl/core/ops/function/trait.Fn.js new file mode 100644 index 00000000..b9551e80 --- /dev/null +++ b/type.impl/core/ops/function/trait.Fn.js @@ -0,0 +1,3 @@ +(function() {var type_impls = { +"karyon_p2p":[] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/core/pin/struct.Pin.js b/type.impl/core/pin/struct.Pin.js new file mode 100644 index 00000000..757a2b82 --- /dev/null +++ b/type.impl/core/pin/struct.Pin.js @@ -0,0 +1,3 @@ +(function() {var type_impls = { +"karyon_jsonrpc":[["
source§

impl<P> Pin<P>
where\n P: Deref,\n <P as Deref>::Target: Unpin,

1.33.0 (const: unstable) · source

pub fn new(pointer: P) -> Pin<P>

Construct a new Pin<P> around a pointer to some data of a type that\nimplements Unpin.

\n

Unlike Pin::new_unchecked, this method is safe because the pointer\nP dereferences to an Unpin type, which cancels the pinning guarantees.

\n
Examples
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\n// We can pin the value, since it doesn't care about being moved\nlet mut pinned: Pin<&mut u8> = Pin::new(&mut val);
\n
1.39.0 (const: unstable) · source

pub fn into_inner(pin: Pin<P>) -> P

Unwraps this Pin<P> returning the underlying pointer.

\n

This requires that the data inside this Pin implements Unpin so that we\ncan ignore the pinning invariants when unwrapping it.

\n
Examples
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\nlet pinned: Pin<&mut u8> = Pin::new(&mut val);\n// Unwrap the pin to get a reference to the value\nlet r = Pin::into_inner(pinned);\nassert_eq!(*r, 5);
\n
",0,"karyon_jsonrpc::service::RPCMethodOutput"],["
source§

impl<P> Pin<P>
where\n P: Deref,

1.33.0 (const: unstable) · source

pub unsafe fn new_unchecked(pointer: P) -> Pin<P>

Construct a new Pin<P> around a reference to some data of a type that\nmay or may not implement Unpin.

\n

If pointer dereferences to an Unpin type, Pin::new should be used\ninstead.

\n
Safety
\n

This constructor is unsafe because we cannot guarantee that the data\npointed to by pointer is pinned, meaning that the data will not be moved or\nits storage invalidated until it gets dropped. If the constructed Pin<P> does\nnot guarantee that the data P points to is pinned, that is a violation of\nthe API contract and may lead to undefined behavior in later (safe) operations.

\n

By using this method, you are making a promise about the P::Deref and\nP::DerefMut implementations, if they exist. Most importantly, they\nmust not move out of their self arguments: Pin::as_mut and Pin::as_ref\nwill call DerefMut::deref_mut and Deref::deref on the pinned pointer\nand expect these methods to uphold the pinning invariants.\nMoreover, by calling this method you promise that the reference P\ndereferences to will not be moved out of again; in particular, it\nmust not be possible to obtain a &mut P::Target and then\nmove out of that reference (using, for example mem::swap).

\n

For example, calling Pin::new_unchecked on an &'a mut T is unsafe because\nwhile you are able to pin it for the given lifetime 'a, you have no control\nover whether it is kept pinned once 'a ends:

\n\n
use std::mem;\nuse std::pin::Pin;\n\nfn move_pinned_ref<T>(mut a: T, mut b: T) {\n    unsafe {\n        let p: Pin<&mut T> = Pin::new_unchecked(&mut a);\n        // This should mean the pointee `a` can never move again.\n    }\n    mem::swap(&mut a, &mut b); // Potential UB down the road ⚠️\n    // The address of `a` changed to `b`'s stack slot, so `a` got moved even\n    // though we have previously pinned it! We have violated the pinning API contract.\n}
\n

A value, once pinned, must remain pinned until it is dropped (unless its type implements\nUnpin). Because Pin<&mut T> does not own the value, dropping the Pin will not drop\nthe value and will not end the pinning contract. So moving the value after dropping the\nPin<&mut T> is still a violation of the API contract.

\n

Similarly, calling Pin::new_unchecked on an Rc<T> is unsafe because there could be\naliases to the same data that are not subject to the pinning restrictions:

\n\n
use std::rc::Rc;\nuse std::pin::Pin;\n\nfn move_pinned_rc<T>(mut x: Rc<T>) {\n    let pinned = unsafe { Pin::new_unchecked(Rc::clone(&x)) };\n    {\n        let p: Pin<&T> = pinned.as_ref();\n        // This should mean the pointee can never move again.\n    }\n    drop(pinned);\n    let content = Rc::get_mut(&mut x).unwrap(); // Potential UB down the road ⚠️\n    // Now, if `x` was the only reference, we have a mutable reference to\n    // data that we pinned above, which we could use to move it as we have\n    // seen in the previous example. We have violated the pinning API contract.\n }
\n
Pinning of closure captures
\n

Particular care is required when using Pin::new_unchecked in a closure:\nPin::new_unchecked(&mut var) where var is a by-value (moved) closure capture\nimplicitly makes the promise that the closure itself is pinned, and that all uses\nof this closure capture respect that pinning.

\n\n
use std::pin::Pin;\nuse std::task::Context;\nuse std::future::Future;\n\nfn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) {\n    // Create a closure that moves `x`, and then internally uses it in a pinned way.\n    let mut closure = move || unsafe {\n        let _ignore = Pin::new_unchecked(&mut x).poll(cx);\n    };\n    // Call the closure, so the future can assume it has been pinned.\n    closure();\n    // Move the closure somewhere else. This also moves `x`!\n    let mut moved = closure;\n    // Calling it again means we polled the future from two different locations,\n    // violating the pinning API contract.\n    moved(); // Potential UB ⚠️\n}
\n

When passing a closure to another API, it might be moving the closure any time, so\nPin::new_unchecked on closure captures may only be used if the API explicitly documents\nthat the closure is pinned.

\n

The better alternative is to avoid all that trouble and do the pinning in the outer function\ninstead (here using the pin! macro):

\n\n
use std::pin::pin;\nuse std::task::Context;\nuse std::future::Future;\n\nfn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) {\n    let mut x = pin!(x);\n    // Create a closure that captures `x: Pin<&mut _>`, which is safe to move.\n    let mut closure = move || {\n        let _ignore = x.as_mut().poll(cx);\n    };\n    // Call the closure, so the future can assume it has been pinned.\n    closure();\n    // Move the closure somewhere else.\n    let mut moved = closure;\n    // Calling it again here is fine (except that we might be polling a future that already\n    // returned `Poll::Ready`, but that is a separate problem).\n    moved();\n}
\n
1.33.0 · source

pub fn as_ref(&self) -> Pin<&<P as Deref>::Target>

Gets a pinned shared reference from this pinned pointer.

\n

This is a generic method to go from &Pin<Pointer<T>> to Pin<&T>.\nIt is safe because, as part of the contract of Pin::new_unchecked,\nthe pointee cannot move after Pin<Pointer<T>> got created.\n“Malicious” implementations of Pointer::Deref are likewise\nruled out by the contract of Pin::new_unchecked.

\n
1.39.0 (const: unstable) · source

pub unsafe fn into_inner_unchecked(pin: Pin<P>) -> P

Unwraps this Pin<P> returning the underlying pointer.

\n
Safety
\n

This function is unsafe. You must guarantee that you will continue to\ntreat the pointer P as pinned after you call this function, so that\nthe invariants on the Pin type can be upheld. If the code using the\nresulting P does not continue to maintain the pinning invariants that\nis a violation of the API contract and may lead to undefined behavior in\nlater (safe) operations.

\n

If the underlying data is Unpin, Pin::into_inner should be used\ninstead.

\n
",0,"karyon_jsonrpc::service::RPCMethodOutput"],["
source§

impl<P> Pin<P>
where\n P: DerefMut,

1.33.0 · source

pub fn as_mut(&mut self) -> Pin<&mut <P as Deref>::Target>

Gets a pinned mutable reference from this pinned pointer.

\n

This is a generic method to go from &mut Pin<Pointer<T>> to Pin<&mut T>.\nIt is safe because, as part of the contract of Pin::new_unchecked,\nthe pointee cannot move after Pin<Pointer<T>> got created.\n“Malicious” implementations of Pointer::DerefMut are likewise\nruled out by the contract of Pin::new_unchecked.

\n

This method is useful when doing multiple calls to functions that consume the pinned type.

\n
Example
\n
use std::pin::Pin;\n\nimpl Type {\n    fn method(self: Pin<&mut Self>) {\n        // do something\n    }\n\n    fn call_method_twice(mut self: Pin<&mut Self>) {\n        // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`.\n        self.as_mut().method();\n        self.as_mut().method();\n    }\n}
\n
1.33.0 · source

pub fn set(&mut self, value: <P as Deref>::Target)
where\n <P as Deref>::Target: Sized,

Assigns a new value to the memory behind the pinned reference.

\n

This overwrites pinned data, but that is okay: its destructor gets\nrun before being overwritten, so no pinning guarantee is violated.

\n
Example
\n
use std::pin::Pin;\n\nlet mut val: u8 = 5;\nlet mut pinned: Pin<&mut u8> = Pin::new(&mut val);\nprintln!(\"{}\", pinned); // 5\npinned.as_mut().set(10);\nprintln!(\"{}\", pinned); // 10
\n
",0,"karyon_jsonrpc::service::RPCMethodOutput"],["
1.41.0 · source§

impl<P, Q> PartialOrd<Pin<Q>> for Pin<P>
where\n P: Deref,\n Q: Deref,\n <P as Deref>::Target: PartialOrd<<Q as Deref>::Target>,

source§

fn partial_cmp(&self, other: &Pin<Q>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
source§

fn lt(&self, other: &Pin<Q>) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
source§

fn le(&self, other: &Pin<Q>) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
source§

fn gt(&self, other: &Pin<Q>) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
source§

fn ge(&self, other: &Pin<Q>) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd>","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> DerefMut for Pin<P>
where\n P: DerefMut,\n <P as Deref>::Target: Unpin,

source§

fn deref_mut(&mut self) -> &mut <P as Deref>::Target

Mutably dereferences the value.
","DerefMut","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Clone for Pin<P>
where\n P: Clone,

source§

fn clone(&self) -> Pin<P>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
","Clone","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P, U> CoerceUnsized<Pin<U>> for Pin<P>
where\n P: CoerceUnsized<U>,

","CoerceUnsized>","karyon_jsonrpc::service::RPCMethodOutput"],["
1.41.0 · source§

impl<P> Eq for Pin<P>
where\n P: Deref,\n <P as Deref>::Target: Eq,

","Eq","karyon_jsonrpc::service::RPCMethodOutput"],["
1.41.0 · source§

impl<P> Hash for Pin<P>
where\n P: Deref,\n <P as Deref>::Target: Hash,

source§

fn hash<H>(&self, state: &mut H)
where\n H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Deref for Pin<P>
where\n P: Deref,

§

type Target = <P as Deref>::Target

The resulting type after dereferencing.
source§

fn deref(&self) -> &<P as Deref>::Target

Dereferences the value.
","Deref","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Pointer for Pin<P>
where\n P: Pointer,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter.
","Pointer","karyon_jsonrpc::service::RPCMethodOutput"],["
1.41.0 · source§

impl<P> Ord for Pin<P>
where\n P: Deref,\n <P as Deref>::Target: Ord,

source§

fn cmp(&self, other: &Pin<P>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_jsonrpc::service::RPCMethodOutput"],["
source§

impl<P> AsyncIterator for Pin<P>
where\n P: DerefMut,\n <P as Deref>::Target: AsyncIterator,

§

type Item = <<P as Deref>::Target as AsyncIterator>::Item

🔬This is a nightly-only experimental API. (async_iterator)
The type of items yielded by the async iterator.
source§

fn poll_next(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Pin<P> as AsyncIterator>::Item>>

🔬This is a nightly-only experimental API. (async_iterator)
Attempt to pull out the next value of this async iterator, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the async iterator is exhausted. Read more
source§

fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (async_iterator)
Returns the bounds on the remaining length of the async iterator. Read more
","AsyncIterator","karyon_jsonrpc::service::RPCMethodOutput"],["
1.41.0 · source§

impl<P, Q> PartialEq<Pin<Q>> for Pin<P>
where\n P: Deref,\n Q: Deref,\n <P as Deref>::Target: PartialEq<<Q as Deref>::Target>,

source§

fn eq(&self, other: &Pin<Q>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
source§

fn ne(&self, other: &Pin<Q>) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq>","karyon_jsonrpc::service::RPCMethodOutput"],["
1.36.0 · source§

impl<P> Future for Pin<P>
where\n P: DerefMut,\n <P as Deref>::Target: Future,

§

type Output = <<P as Deref>::Target as Future>::Output

The type of value produced on completion.
source§

fn poll(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<<Pin<P> as Future>::Output>

Attempt to resolve the future to a final value, registering\nthe current task for wakeup if the value is not yet available. Read more
","Future","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Display for Pin<P>
where\n P: Display,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Display","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Debug for Pin<P>
where\n P: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P, U> DispatchFromDyn<Pin<U>> for Pin<P>
where\n P: DispatchFromDyn<U>,

","DispatchFromDyn>","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<P> Copy for Pin<P>
where\n P: Copy,

","Copy","karyon_jsonrpc::service::RPCMethodOutput"],["
1.33.0 · source§

impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
where\n A: Allocator + 'static,\n T: ?Sized,

source§

fn from(boxed: Box<T, A>) -> Pin<Box<T, A>>

Converts a Box<T> into a Pin<Box<T>>. If T does not implement Unpin, then\n*boxed will be pinned in memory and unable to be moved.

\n

This conversion does not allocate on the heap and happens in place.

\n

This is also available via Box::into_pin.

\n

Constructing and pinning a Box with <Pin<Box<T>>>::from(Box::new(x))\ncan also be written more concisely using Box::pin(x).\nThis From implementation is useful if you already have a Box<T>, or you are\nconstructing a (pinned) Box in a different way than with Box::new.

\n
","From>","karyon_jsonrpc::service::RPCMethodOutput"],["
source§

impl<G, R, A> Coroutine<R> for Pin<Box<G, A>>
where\n G: Coroutine<R> + ?Sized,\n A: Allocator + 'static,

§

type Yield = <G as Coroutine<R>>::Yield

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine yields. Read more
§

type Return = <G as Coroutine<R>>::Return

🔬This is a nightly-only experimental API. (coroutine_trait)
The type of value this coroutine returns. Read more
source§

fn resume(\n self: Pin<&mut Pin<Box<G, A>>>,\n arg: R\n) -> CoroutineState<<Pin<Box<G, A>> as Coroutine<R>>::Yield, <Pin<Box<G, A>> as Coroutine<R>>::Return>

🔬This is a nightly-only experimental API. (coroutine_trait)
Resumes the execution of this coroutine. Read more
","Coroutine","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> Stream for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: Stream,

§

type Item = <<P as Deref>::Target as Stream>::Item

Values yielded by the stream.
§

fn poll_next(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<Option<<Pin<P> as Stream>::Item>>

Attempt to pull out the next value of this stream, registering the\ncurrent task for wakeup if the value is not yet available, and returning\nNone if the stream is exhausted. Read more
§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more
","Stream","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> FusedFuture for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: FusedFuture,

§

fn is_terminated(&self) -> bool

Returns true if the underlying future should no longer be polled.
","FusedFuture","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> FusedStream for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: FusedStream,

§

fn is_terminated(&self) -> bool

Returns true if the stream should no longer be polled.
","FusedStream","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> AsyncWrite for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: AsyncWrite,

§

fn poll_write(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n buf: &[u8]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
§

fn poll_write_vectored(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n bufs: &[IoSlice<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to write bytes from bufs into the object using vectored\nIO operations. Read more
§

fn poll_flush(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to flush the object, ensuring that any buffered data reach\ntheir destination. Read more
§

fn poll_close(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<Result<(), Error>>

Attempt to close the object. Read more
","AsyncWrite","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> AsyncRead for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: AsyncRead,

§

fn poll_read(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n buf: &mut [u8]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into buf. Read more
§

fn poll_read_vectored(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n bufs: &mut [IoSliceMut<'_>]\n) -> Poll<Result<usize, Error>>

Attempt to read from the AsyncRead into bufs using vectored\nIO operations. Read more
","AsyncRead","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> AsyncSeek for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: AsyncSeek,

§

fn poll_seek(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>,\n pos: SeekFrom\n) -> Poll<Result<u64, Error>>

Attempt to seek to an offset, in bytes, in a stream. Read more
","AsyncSeek","karyon_jsonrpc::service::RPCMethodOutput"],["
§

impl<P> AsyncBufRead for Pin<P>
where\n P: DerefMut + Unpin,\n <P as Deref>::Target: AsyncBufRead,

§

fn poll_fill_buf(\n self: Pin<&mut Pin<P>>,\n cx: &mut Context<'_>\n) -> Poll<Result<&[u8], Error>>

Attempt to return the contents of the internal buffer, filling it with more data\nfrom the inner reader if it is empty. Read more
§

fn consume(self: Pin<&mut Pin<P>>, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer,\nso they should no longer be returned in calls to poll_read. Read more
","AsyncBufRead","karyon_jsonrpc::service::RPCMethodOutput"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/core/result/enum.Result.js b/type.impl/core/result/enum.Result.js new file mode 100644 index 00000000..9cba18f2 --- /dev/null +++ b/type.impl/core/result/enum.Result.js @@ -0,0 +1,6 @@ +(function() {var type_impls = { +"karyon_core":[["
source§

impl<T, E> Result<T, E>

1.0.0 (const: 1.48.0) · source

pub const fn is_ok(&self) -> bool

Returns true if the result is Ok.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_ok(), true);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_ok(), false);
\n
1.70.0 · source

pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool

Returns true if the result is Ok and the value inside of it matches a predicate.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n
1.0.0 (const: 1.48.0) · source

pub const fn is_err(&self) -> bool

Returns true if the result is Err.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_err(), false);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_err(), true);
\n
1.70.0 · source

pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool

Returns true if the result is Err and the value inside of it matches a predicate.

\n
Examples
\n
use std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n
1.0.0 · source

pub fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>.

\n

Converts self into an Option<T>, consuming self,\nand discarding the error, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.ok(), Some(2));\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.ok(), None);
\n
1.0.0 · source

pub fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>.

\n

Converts self into an Option<E>, consuming self,\nand discarding the success value, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n
1.0.0 (const: 1.48.0) · source

pub const fn as_ref(&self) -> Result<&T, &E>

Converts from &Result<T, E> to Result<&T, &E>.

\n

Produces a new Result, containing a reference\ninto the original, leaving the original in place.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n
1.0.0 (const: unstable) · source

pub fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from &mut Result<T, E> to Result<&mut T, &mut E>.

\n
Examples
\n
fn mutate(r: &mut Result<i32, i32>) {\n    match r.as_mut() {\n        Ok(v) => *v = 42,\n        Err(e) => *e = 0,\n    }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n
1.0.0 · source

pub fn map<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> U,

Maps a Result<T, E> to Result<U, E> by applying a function to a\ncontained Ok value, leaving an Err value untouched.

\n

This function can be used to compose the results of two functions.

\n
Examples
\n

Print the numbers on each line of a string multiplied by two.

\n\n
let line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n    match num.parse::<i32>().map(|i| i * 2) {\n        Ok(n) => println!(\"{n}\"),\n        Err(..) => {}\n    }\n}
\n
1.41.0 · source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where\n F: FnOnce(T) -> U,

Returns the provided default (if Err), or\napplies a function to the contained value (if Ok).

\n

Arguments passed to map_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n
1.41.0 · source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where\n D: FnOnce(E) -> U,\n F: FnOnce(T) -> U,

Maps a Result<T, E> to U by applying fallback function default to\na contained Err value, or function f to a contained Ok value.

\n

This function can be used to unpack a successful result\nwhile handling an error.

\n
Examples
\n
let k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n
1.0.0 · source

pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> F,

Maps a Result<T, E> to Result<T, F> by applying a function to a\ncontained Err value, leaving an Ok value untouched.

\n

This function can be used to pass through a successful result while handling\nan error.

\n
Examples
\n
fn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n
1.76.0 · source

pub fn inspect<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&T),

Calls the provided closure with a reference to the contained value (if Ok).

\n
Examples
\n
let x: u8 = \"4\"\n    .parse::<u8>()\n    .inspect(|x| println!(\"original: {x}\"))\n    .map(|x| x.pow(3))\n    .expect(\"failed to parse number\");
\n
1.76.0 · source

pub fn inspect_err<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&E),

Calls the provided closure with a reference to the contained error (if Err).

\n
Examples
\n
use std::{fs, io};\n\nfn read() -> io::Result<String> {\n    fs::read_to_string(\"address.txt\")\n        .inspect_err(|e| eprintln!(\"failed to read file: {e}\"))\n}
\n
1.47.0 · source

pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>
where\n T: Deref,

Converts from Result<T, E> (or &Result<T, E>) to Result<&<T as Deref>::Target, &E>.

\n

Coerces the Ok variant of the original Result via Deref\nand returns the new Result.

\n
Examples
\n
let x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n
1.47.0 · source

pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>
where\n T: DerefMut,

Converts from Result<T, E> (or &mut Result<T, E>) to Result<&mut <T as DerefMut>::Target, &mut E>.

\n

Coerces the Ok variant of the original Result via DerefMut\nand returns the new Result.

\n
Examples
\n
let mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n
1.0.0 · source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n
1.0.0 · source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n    Some(v) => *v = 40,\n    None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n
1.4.0 · source

pub fn expect(self, msg: &str) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message including the\npassed message, and the content of the Err.

\n
Examples
\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n
Recommended Message Style
\n

We recommend that expect messages are used to describe the reason you\nexpect the Result should be Ok.

\n\n
let path = std::env::var(\"IMPORTANT_PATH\")\n    .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\n

Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.

\n

For more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error module docs.

\n
1.0.0 · source

pub fn unwrap(self) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message provided by the\nErr’s value.

\n
Examples
\n

Basic usage:

\n\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n
1.16.0 · source

pub fn unwrap_or_default(self) -> T
where\n T: Default,

Returns the contained Ok value or a default

\n

Consumes the self argument then, if Ok, returns the contained\nvalue, otherwise if Err, returns the default value for that\ntype.

\n
Examples
\n

Converts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse converts\na string to any other type that implements FromStr, returning an\nErr on error.

\n\n
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n
1.17.0 · source

pub fn expect_err(self, msg: &str) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a panic message including the\npassed message, and the content of the Ok.

\n
Examples
\n
let x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n
1.0.0 · source

pub fn unwrap_err(self) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a custom panic message provided\nby the Ok’s value.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\n
source

pub fn into_ok(self) -> T
where\n E: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Ok value, but never panics.

\n

Unlike unwrap, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap as a maintainability safeguard that will fail\nto compile if the error type of the Result is later changed\nto an error that can actually occur.

\n
Examples
\n
\nfn only_good_news() -> Result<String, !> {\n    Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\n
source

pub fn into_err(self) -> E
where\n T: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Err value, but never panics.

\n

Unlike unwrap_err, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err as a maintainability safeguard that will fail\nto compile if the ok type of the Result is later changed\nto a type that can actually occur.

\n
Examples
\n
\nfn only_bad_news() -> Result<!, String> {\n    Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n
1.0.0 · source

pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

\n

Arguments passed to and are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n
1.0.0 · source

pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> Result<U, E>,

Calls op if the result is Ok, otherwise returns the Err value of self.

\n

This function can be used for control flow based on Result values.

\n
Examples
\n
fn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n    x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\n

Often used to chain fallible operations that may return Err.

\n\n
use std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n
1.0.0 · source

pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

\n

Arguments passed to or are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n
1.0.0 · source

pub fn or_else<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> Result<T, F>,

Calls op if the result is Err, otherwise returns the Ok value of self.

\n

This function can be used for control flow based on result values.

\n
Examples
\n
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n
1.0.0 · source

pub fn unwrap_or(self, default: T) -> T

Returns the contained Ok value or a provided default.

\n

Arguments passed to unwrap_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n
1.0.0 · source

pub fn unwrap_or_else<F>(self, op: F) -> T
where\n F: FnOnce(E) -> T,

Returns the contained Ok value or computes it from a closure.

\n
Examples
\n
fn count(x: &str) -> usize { x.len() }\n\nassert_eq!(Ok(2).unwrap_or_else(count), 2);\nassert_eq!(Err(\"foo\").unwrap_or_else(count), 3);
\n
1.58.0 · source

pub unsafe fn unwrap_unchecked(self) -> T

Returns the contained Ok value, consuming the self value,\nwithout checking that the value is not an Err.

\n
Safety
\n

Calling this method on an Err is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n
1.58.0 · source

pub unsafe fn unwrap_err_unchecked(self) -> E

Returns the contained Err value, consuming the self value,\nwithout checking that the value is not an Ok.

\n
Safety
\n

Calling this method on an Ok is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n
",0,"karyon_core::error::Result"],["
source§

impl<T, E> Result<&T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_core::error::Result"],["
source§

impl<T, E> Result<&mut T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&mut T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&mut T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_core::error::Result"],["
source§

impl<T, E> Result<Option<T>, E>

1.33.0 (const: unstable) · source

pub fn transpose(self) -> Option<Result<T, E>>

Transposes a Result of an Option into an Option of a Result.

\n

Ok(None) will be mapped to None.\nOk(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

\n
Examples
\n
#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n
",0,"karyon_core::error::Result"],["
source§

impl<T, E> Result<Result<T, E>, E>

source

pub fn flatten(self) -> Result<T, E>

🔬This is a nightly-only experimental API. (result_flattening)

Converts from Result<Result<T, E>, E> to Result<T, E>

\n
Examples
\n
#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\n

Flattening only removes one level of nesting at a time:

\n\n
#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n
",0,"karyon_core::error::Result"],["
1.61.0 · source§

impl<T, E> Termination for Result<T, E>
where\n T: Termination,\n E: Debug,

source§

fn report(self) -> ExitCode

Is called to get the representation of the value as status code.\nThis status code is returned to the operating system.
","Termination","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> PartialOrd for Result<T, E>
where\n T: PartialOrd,\n E: PartialOrd,

source§

fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd","karyon_core::error::Result"],["
1.16.0 · source§

impl<T, U, E> Product<Result<U, E>> for Result<T, E>
where\n T: Product<U>,

source§

fn product<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the product of all elements is returned.

\n
Examples
\n

This multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err:

\n\n
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n
","Product>","karyon_core::error::Result"],["
source§

impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_core::error::Result"],["
source§

impl<T, E, F> FromResidual<Yeet<E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(_: Yeet<E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_core::error::Result"],["
source§

impl<T, E> Try for Result<T, E>

§

type Output = T

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value produced by ? when not short-circuiting.
§

type Residual = Result<Infallible, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value passed to FromResidual::from_residual\nas part of ? when short-circuiting. Read more
source§

fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from its Output type. Read more
source§

fn branch(\n self\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2)
Used in ? to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break). Read more
","Try","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Clone for Result<T, E>
where\n T: Clone,\n E: Clone,

source§

fn clone(&self) -> Result<T, E>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Result<T, E>)

Performs copy-assignment from source. Read more
","Clone","karyon_core::error::Result"],["
1.0.0 · source§

impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>
where\n V: FromIterator<A>,

source§

fn from_iter<I>(iter: I) -> Result<V, E>
where\n I: IntoIterator<Item = Result<A, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err occur, a\ncontainer with the values of each Result is returned.

\n

Here is an example which increments every integer in a vector,\nchecking for overflow:

\n\n
let v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\n

Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:

\n\n
let v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\n

Here is a variation on the previous example, showing that no\nfurther elements are taken from iter after the first Err.

\n\n
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n    shared += x;\n    x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\n

Since the third element caused an underflow, no further elements were taken,\nso the final value of shared is 6 (= 3 + 2 + 1), not 16.

\n
","FromIterator>","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralEq for Result<T, E>

","StructuralEq","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Eq for Result<T, E>
where\n T: Eq,\n E: Eq,

","Eq","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Hash for Result<T, E>
where\n T: Hash,\n E: Hash,

source§

fn hash<__H>(&self, state: &mut __H)
where\n __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Ord for Result<T, E>
where\n T: Ord,\n E: Ord,

source§

fn cmp(&self, other: &Result<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_core::error::Result"],["
source§

impl<T, E> Residual<T> for Result<Infallible, E>

§

type TryType = Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2_residual)
The “return” type of this meta-function.
","Residual","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> PartialEq for Result<T, E>
where\n T: PartialEq,\n E: PartialEq,

source§

fn eq(&self, other: &Result<T, E>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> IntoIterator for Result<T, E>

source§

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n
§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
","IntoIterator","karyon_core::error::Result"],["
1.16.0 · source§

impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
where\n T: Sum<U>,

source§

fn sum<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the sum of all elements is returned.

\n
Examples
\n

This sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:

\n\n
let f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n
","Sum>","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralPartialEq for Result<T, E>

","StructuralPartialEq","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Debug for Result<T, E>
where\n T: Debug,\n E: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_core::error::Result"],["
1.0.0 · source§

impl<T, E> Copy for Result<T, E>
where\n T: Copy,\n E: Copy,

","Copy","karyon_core::error::Result"],["
source§

impl<T, U> Encode for Result<T, U>
where\n T: Encode,\n U: Encode,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_core::error::Result"],["
source§

impl<'de, T, U> BorrowDecode<'de> for Result<T, U>
where\n T: BorrowDecode<'de>,\n U: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_core::error::Result"],["
source§

impl<T, U> Decode for Result<T, U>
where\n T: Decode,\n U: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_core::error::Result"]], +"karyon_jsonrpc":[["
source§

impl<T, E> Result<T, E>

1.0.0 (const: 1.48.0) · source

pub const fn is_ok(&self) -> bool

Returns true if the result is Ok.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_ok(), true);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_ok(), false);
\n
1.70.0 · source

pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool

Returns true if the result is Ok and the value inside of it matches a predicate.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n
1.0.0 (const: 1.48.0) · source

pub const fn is_err(&self) -> bool

Returns true if the result is Err.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_err(), false);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_err(), true);
\n
1.70.0 · source

pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool

Returns true if the result is Err and the value inside of it matches a predicate.

\n
Examples
\n
use std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n
1.0.0 · source

pub fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>.

\n

Converts self into an Option<T>, consuming self,\nand discarding the error, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.ok(), Some(2));\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.ok(), None);
\n
1.0.0 · source

pub fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>.

\n

Converts self into an Option<E>, consuming self,\nand discarding the success value, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n
1.0.0 (const: 1.48.0) · source

pub const fn as_ref(&self) -> Result<&T, &E>

Converts from &Result<T, E> to Result<&T, &E>.

\n

Produces a new Result, containing a reference\ninto the original, leaving the original in place.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n
1.0.0 (const: unstable) · source

pub fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from &mut Result<T, E> to Result<&mut T, &mut E>.

\n
Examples
\n
fn mutate(r: &mut Result<i32, i32>) {\n    match r.as_mut() {\n        Ok(v) => *v = 42,\n        Err(e) => *e = 0,\n    }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n
1.0.0 · source

pub fn map<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> U,

Maps a Result<T, E> to Result<U, E> by applying a function to a\ncontained Ok value, leaving an Err value untouched.

\n

This function can be used to compose the results of two functions.

\n
Examples
\n

Print the numbers on each line of a string multiplied by two.

\n\n
let line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n    match num.parse::<i32>().map(|i| i * 2) {\n        Ok(n) => println!(\"{n}\"),\n        Err(..) => {}\n    }\n}
\n
1.41.0 · source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where\n F: FnOnce(T) -> U,

Returns the provided default (if Err), or\napplies a function to the contained value (if Ok).

\n

Arguments passed to map_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n
1.41.0 · source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where\n D: FnOnce(E) -> U,\n F: FnOnce(T) -> U,

Maps a Result<T, E> to U by applying fallback function default to\na contained Err value, or function f to a contained Ok value.

\n

This function can be used to unpack a successful result\nwhile handling an error.

\n
Examples
\n
let k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n
1.0.0 · source

pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> F,

Maps a Result<T, E> to Result<T, F> by applying a function to a\ncontained Err value, leaving an Ok value untouched.

\n

This function can be used to pass through a successful result while handling\nan error.

\n
Examples
\n
fn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n
1.76.0 · source

pub fn inspect<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&T),

Calls the provided closure with a reference to the contained value (if Ok).

\n
Examples
\n
let x: u8 = \"4\"\n    .parse::<u8>()\n    .inspect(|x| println!(\"original: {x}\"))\n    .map(|x| x.pow(3))\n    .expect(\"failed to parse number\");
\n
1.76.0 · source

pub fn inspect_err<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&E),

Calls the provided closure with a reference to the contained error (if Err).

\n
Examples
\n
use std::{fs, io};\n\nfn read() -> io::Result<String> {\n    fs::read_to_string(\"address.txt\")\n        .inspect_err(|e| eprintln!(\"failed to read file: {e}\"))\n}
\n
1.47.0 · source

pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>
where\n T: Deref,

Converts from Result<T, E> (or &Result<T, E>) to Result<&<T as Deref>::Target, &E>.

\n

Coerces the Ok variant of the original Result via Deref\nand returns the new Result.

\n
Examples
\n
let x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n
1.47.0 · source

pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>
where\n T: DerefMut,

Converts from Result<T, E> (or &mut Result<T, E>) to Result<&mut <T as DerefMut>::Target, &mut E>.

\n

Coerces the Ok variant of the original Result via DerefMut\nand returns the new Result.

\n
Examples
\n
let mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n
1.0.0 · source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n
1.0.0 · source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n    Some(v) => *v = 40,\n    None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n
1.4.0 · source

pub fn expect(self, msg: &str) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message including the\npassed message, and the content of the Err.

\n
Examples
\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n
Recommended Message Style
\n

We recommend that expect messages are used to describe the reason you\nexpect the Result should be Ok.

\n\n
let path = std::env::var(\"IMPORTANT_PATH\")\n    .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\n

Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.

\n

For more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error module docs.

\n
1.0.0 · source

pub fn unwrap(self) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message provided by the\nErr’s value.

\n
Examples
\n

Basic usage:

\n\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n
1.16.0 · source

pub fn unwrap_or_default(self) -> T
where\n T: Default,

Returns the contained Ok value or a default

\n

Consumes the self argument then, if Ok, returns the contained\nvalue, otherwise if Err, returns the default value for that\ntype.

\n
Examples
\n

Converts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse converts\na string to any other type that implements FromStr, returning an\nErr on error.

\n\n
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n
1.17.0 · source

pub fn expect_err(self, msg: &str) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a panic message including the\npassed message, and the content of the Ok.

\n
Examples
\n
let x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n
1.0.0 · source

pub fn unwrap_err(self) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a custom panic message provided\nby the Ok’s value.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\n
source

pub fn into_ok(self) -> T
where\n E: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Ok value, but never panics.

\n

Unlike unwrap, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap as a maintainability safeguard that will fail\nto compile if the error type of the Result is later changed\nto an error that can actually occur.

\n
Examples
\n
\nfn only_good_news() -> Result<String, !> {\n    Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\n
source

pub fn into_err(self) -> E
where\n T: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Err value, but never panics.

\n

Unlike unwrap_err, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err as a maintainability safeguard that will fail\nto compile if the ok type of the Result is later changed\nto a type that can actually occur.

\n
Examples
\n
\nfn only_bad_news() -> Result<!, String> {\n    Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n
1.0.0 · source

pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

\n

Arguments passed to and are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n
1.0.0 · source

pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> Result<U, E>,

Calls op if the result is Ok, otherwise returns the Err value of self.

\n

This function can be used for control flow based on Result values.

\n
Examples
\n
fn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n    x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\n

Often used to chain fallible operations that may return Err.

\n\n
use std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n
1.0.0 · source

pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

\n

Arguments passed to or are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n
1.0.0 · source

pub fn or_else<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> Result<T, F>,

Calls op if the result is Err, otherwise returns the Ok value of self.

\n

This function can be used for control flow based on result values.

\n
Examples
\n
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n
1.0.0 · source

pub fn unwrap_or(self, default: T) -> T

Returns the contained Ok value or a provided default.

\n

Arguments passed to unwrap_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n
1.0.0 · source

pub fn unwrap_or_else<F>(self, op: F) -> T
where\n F: FnOnce(E) -> T,

Returns the contained Ok value or computes it from a closure.

\n
Examples
\n
fn count(x: &str) -> usize { x.len() }\n\nassert_eq!(Ok(2).unwrap_or_else(count), 2);\nassert_eq!(Err(\"foo\").unwrap_or_else(count), 3);
\n
1.58.0 · source

pub unsafe fn unwrap_unchecked(self) -> T

Returns the contained Ok value, consuming the self value,\nwithout checking that the value is not an Err.

\n
Safety
\n

Calling this method on an Err is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n
1.58.0 · source

pub unsafe fn unwrap_err_unchecked(self) -> E

Returns the contained Err value, consuming the self value,\nwithout checking that the value is not an Ok.

\n
Safety
\n

Calling this method on an Ok is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n
",0,"karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Result<&T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Result<&mut T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&mut T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&mut T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Result<Option<T>, E>

1.33.0 (const: unstable) · source

pub fn transpose(self) -> Option<Result<T, E>>

Transposes a Result of an Option into an Option of a Result.

\n

Ok(None) will be mapped to None.\nOk(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

\n
Examples
\n
#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n
",0,"karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Result<Result<T, E>, E>

source

pub fn flatten(self) -> Result<T, E>

🔬This is a nightly-only experimental API. (result_flattening)

Converts from Result<Result<T, E>, E> to Result<T, E>

\n
Examples
\n
#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\n

Flattening only removes one level of nesting at a time:

\n\n
#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n
",0,"karyon_jsonrpc::error::Result"],["
1.61.0 · source§

impl<T, E> Termination for Result<T, E>
where\n T: Termination,\n E: Debug,

source§

fn report(self) -> ExitCode

Is called to get the representation of the value as status code.\nThis status code is returned to the operating system.
","Termination","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> PartialOrd for Result<T, E>
where\n T: PartialOrd,\n E: PartialOrd,

source§

fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd","karyon_jsonrpc::error::Result"],["
1.16.0 · source§

impl<T, U, E> Product<Result<U, E>> for Result<T, E>
where\n T: Product<U>,

source§

fn product<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the product of all elements is returned.

\n
Examples
\n

This multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err:

\n\n
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n
","Product>","karyon_jsonrpc::error::Result"],["
source§

impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_jsonrpc::error::Result"],["
source§

impl<T, E, F> FromResidual<Yeet<E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(_: Yeet<E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Try for Result<T, E>

§

type Output = T

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value produced by ? when not short-circuiting.
§

type Residual = Result<Infallible, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value passed to FromResidual::from_residual\nas part of ? when short-circuiting. Read more
source§

fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from its Output type. Read more
source§

fn branch(\n self\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2)
Used in ? to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break). Read more
","Try","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Clone for Result<T, E>
where\n T: Clone,\n E: Clone,

source§

fn clone(&self) -> Result<T, E>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Result<T, E>)

Performs copy-assignment from source. Read more
","Clone","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>
where\n V: FromIterator<A>,

source§

fn from_iter<I>(iter: I) -> Result<V, E>
where\n I: IntoIterator<Item = Result<A, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err occur, a\ncontainer with the values of each Result is returned.

\n

Here is an example which increments every integer in a vector,\nchecking for overflow:

\n\n
let v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\n

Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:

\n\n
let v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\n

Here is a variation on the previous example, showing that no\nfurther elements are taken from iter after the first Err.

\n\n
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n    shared += x;\n    x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\n

Since the third element caused an underflow, no further elements were taken,\nso the final value of shared is 6 (= 3 + 2 + 1), not 16.

\n
","FromIterator>","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralEq for Result<T, E>

","StructuralEq","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Eq for Result<T, E>
where\n T: Eq,\n E: Eq,

","Eq","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Hash for Result<T, E>
where\n T: Hash,\n E: Hash,

source§

fn hash<__H>(&self, state: &mut __H)
where\n __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Ord for Result<T, E>
where\n T: Ord,\n E: Ord,

source§

fn cmp(&self, other: &Result<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Residual<T> for Result<Infallible, E>

§

type TryType = Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2_residual)
The “return” type of this meta-function.
","Residual","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> PartialEq for Result<T, E>
where\n T: PartialEq,\n E: PartialEq,

source§

fn eq(&self, other: &Result<T, E>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> IntoIterator for Result<T, E>

source§

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n
§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
","IntoIterator","karyon_jsonrpc::error::Result"],["
1.16.0 · source§

impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
where\n T: Sum<U>,

source§

fn sum<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the sum of all elements is returned.

\n
Examples
\n

This sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:

\n\n
let f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n
","Sum>","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralPartialEq for Result<T, E>

","StructuralPartialEq","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Debug for Result<T, E>
where\n T: Debug,\n E: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_jsonrpc::error::Result"],["
1.0.0 · source§

impl<T, E> Copy for Result<T, E>
where\n T: Copy,\n E: Copy,

","Copy","karyon_jsonrpc::error::Result"],["
source§

impl<'de, T, E> Deserialize<'de> for Result<T, E>
where\n T: Deserialize<'de>,\n E: Deserialize<'de>,

source§

fn deserialize<D>(\n deserializer: D\n) -> Result<Result<T, E>, <D as Deserializer<'de>>::Error>
where\n D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
","Deserialize<'de>","karyon_jsonrpc::error::Result"],["
source§

impl<T, E> Serialize for Result<T, E>
where\n T: Serialize,\n E: Serialize,

source§

fn serialize<S>(\n &self,\n serializer: S\n) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where\n S: Serializer,

Serialize this value into the given Serde serializer. Read more
","Serialize","karyon_jsonrpc::error::Result"],["
source§

impl<T, U> Encode for Result<T, U>
where\n T: Encode,\n U: Encode,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_jsonrpc::error::Result"],["
source§

impl<'de, T, U> BorrowDecode<'de> for Result<T, U>
where\n T: BorrowDecode<'de>,\n U: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_jsonrpc::error::Result"],["
source§

impl<T, U> Decode for Result<T, U>
where\n T: Decode,\n U: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_jsonrpc::error::Result"]], +"karyon_net":[["
source§

impl<T, E> Result<T, E>

1.0.0 (const: 1.48.0) · source

pub const fn is_ok(&self) -> bool

Returns true if the result is Ok.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_ok(), true);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_ok(), false);
\n
1.70.0 · source

pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool

Returns true if the result is Ok and the value inside of it matches a predicate.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n
1.0.0 (const: 1.48.0) · source

pub const fn is_err(&self) -> bool

Returns true if the result is Err.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_err(), false);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_err(), true);
\n
1.70.0 · source

pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool

Returns true if the result is Err and the value inside of it matches a predicate.

\n
Examples
\n
use std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n
1.0.0 · source

pub fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>.

\n

Converts self into an Option<T>, consuming self,\nand discarding the error, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.ok(), Some(2));\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.ok(), None);
\n
1.0.0 · source

pub fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>.

\n

Converts self into an Option<E>, consuming self,\nand discarding the success value, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n
1.0.0 (const: 1.48.0) · source

pub const fn as_ref(&self) -> Result<&T, &E>

Converts from &Result<T, E> to Result<&T, &E>.

\n

Produces a new Result, containing a reference\ninto the original, leaving the original in place.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n
1.0.0 (const: unstable) · source

pub fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from &mut Result<T, E> to Result<&mut T, &mut E>.

\n
Examples
\n
fn mutate(r: &mut Result<i32, i32>) {\n    match r.as_mut() {\n        Ok(v) => *v = 42,\n        Err(e) => *e = 0,\n    }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n
1.0.0 · source

pub fn map<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> U,

Maps a Result<T, E> to Result<U, E> by applying a function to a\ncontained Ok value, leaving an Err value untouched.

\n

This function can be used to compose the results of two functions.

\n
Examples
\n

Print the numbers on each line of a string multiplied by two.

\n\n
let line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n    match num.parse::<i32>().map(|i| i * 2) {\n        Ok(n) => println!(\"{n}\"),\n        Err(..) => {}\n    }\n}
\n
1.41.0 · source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where\n F: FnOnce(T) -> U,

Returns the provided default (if Err), or\napplies a function to the contained value (if Ok).

\n

Arguments passed to map_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n
1.41.0 · source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where\n D: FnOnce(E) -> U,\n F: FnOnce(T) -> U,

Maps a Result<T, E> to U by applying fallback function default to\na contained Err value, or function f to a contained Ok value.

\n

This function can be used to unpack a successful result\nwhile handling an error.

\n
Examples
\n
let k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n
1.0.0 · source

pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> F,

Maps a Result<T, E> to Result<T, F> by applying a function to a\ncontained Err value, leaving an Ok value untouched.

\n

This function can be used to pass through a successful result while handling\nan error.

\n
Examples
\n
fn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n
1.76.0 · source

pub fn inspect<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&T),

Calls the provided closure with a reference to the contained value (if Ok).

\n
Examples
\n
let x: u8 = \"4\"\n    .parse::<u8>()\n    .inspect(|x| println!(\"original: {x}\"))\n    .map(|x| x.pow(3))\n    .expect(\"failed to parse number\");
\n
1.76.0 · source

pub fn inspect_err<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&E),

Calls the provided closure with a reference to the contained error (if Err).

\n
Examples
\n
use std::{fs, io};\n\nfn read() -> io::Result<String> {\n    fs::read_to_string(\"address.txt\")\n        .inspect_err(|e| eprintln!(\"failed to read file: {e}\"))\n}
\n
1.47.0 · source

pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>
where\n T: Deref,

Converts from Result<T, E> (or &Result<T, E>) to Result<&<T as Deref>::Target, &E>.

\n

Coerces the Ok variant of the original Result via Deref\nand returns the new Result.

\n
Examples
\n
let x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n
1.47.0 · source

pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>
where\n T: DerefMut,

Converts from Result<T, E> (or &mut Result<T, E>) to Result<&mut <T as DerefMut>::Target, &mut E>.

\n

Coerces the Ok variant of the original Result via DerefMut\nand returns the new Result.

\n
Examples
\n
let mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n
1.0.0 · source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n
1.0.0 · source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n    Some(v) => *v = 40,\n    None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n
1.4.0 · source

pub fn expect(self, msg: &str) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message including the\npassed message, and the content of the Err.

\n
Examples
\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n
Recommended Message Style
\n

We recommend that expect messages are used to describe the reason you\nexpect the Result should be Ok.

\n\n
let path = std::env::var(\"IMPORTANT_PATH\")\n    .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\n

Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.

\n

For more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error module docs.

\n
1.0.0 · source

pub fn unwrap(self) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message provided by the\nErr’s value.

\n
Examples
\n

Basic usage:

\n\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n
1.16.0 · source

pub fn unwrap_or_default(self) -> T
where\n T: Default,

Returns the contained Ok value or a default

\n

Consumes the self argument then, if Ok, returns the contained\nvalue, otherwise if Err, returns the default value for that\ntype.

\n
Examples
\n

Converts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse converts\na string to any other type that implements FromStr, returning an\nErr on error.

\n\n
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n
1.17.0 · source

pub fn expect_err(self, msg: &str) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a panic message including the\npassed message, and the content of the Ok.

\n
Examples
\n
let x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n
1.0.0 · source

pub fn unwrap_err(self) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a custom panic message provided\nby the Ok’s value.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\n
source

pub fn into_ok(self) -> T
where\n E: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Ok value, but never panics.

\n

Unlike unwrap, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap as a maintainability safeguard that will fail\nto compile if the error type of the Result is later changed\nto an error that can actually occur.

\n
Examples
\n
\nfn only_good_news() -> Result<String, !> {\n    Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\n
source

pub fn into_err(self) -> E
where\n T: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Err value, but never panics.

\n

Unlike unwrap_err, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err as a maintainability safeguard that will fail\nto compile if the ok type of the Result is later changed\nto a type that can actually occur.

\n
Examples
\n
\nfn only_bad_news() -> Result<!, String> {\n    Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n
1.0.0 · source

pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

\n

Arguments passed to and are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n
1.0.0 · source

pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> Result<U, E>,

Calls op if the result is Ok, otherwise returns the Err value of self.

\n

This function can be used for control flow based on Result values.

\n
Examples
\n
fn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n    x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\n

Often used to chain fallible operations that may return Err.

\n\n
use std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n
1.0.0 · source

pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

\n

Arguments passed to or are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n
1.0.0 · source

pub fn or_else<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> Result<T, F>,

Calls op if the result is Err, otherwise returns the Ok value of self.

\n

This function can be used for control flow based on result values.

\n
Examples
\n
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n
1.0.0 · source

pub fn unwrap_or(self, default: T) -> T

Returns the contained Ok value or a provided default.

\n

Arguments passed to unwrap_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n
1.0.0 · source

pub fn unwrap_or_else<F>(self, op: F) -> T
where\n F: FnOnce(E) -> T,

Returns the contained Ok value or computes it from a closure.

\n
Examples
\n
fn count(x: &str) -> usize { x.len() }\n\nassert_eq!(Ok(2).unwrap_or_else(count), 2);\nassert_eq!(Err(\"foo\").unwrap_or_else(count), 3);
\n
1.58.0 · source

pub unsafe fn unwrap_unchecked(self) -> T

Returns the contained Ok value, consuming the self value,\nwithout checking that the value is not an Err.

\n
Safety
\n

Calling this method on an Err is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n
1.58.0 · source

pub unsafe fn unwrap_err_unchecked(self) -> E

Returns the contained Err value, consuming the self value,\nwithout checking that the value is not an Ok.

\n
Safety
\n

Calling this method on an Ok is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n
",0,"karyon_net::error::Result"],["
source§

impl<T, E> Result<&T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_net::error::Result"],["
source§

impl<T, E> Result<&mut T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&mut T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&mut T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_net::error::Result"],["
source§

impl<T, E> Result<Option<T>, E>

1.33.0 (const: unstable) · source

pub fn transpose(self) -> Option<Result<T, E>>

Transposes a Result of an Option into an Option of a Result.

\n

Ok(None) will be mapped to None.\nOk(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

\n
Examples
\n
#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n
",0,"karyon_net::error::Result"],["
source§

impl<T, E> Result<Result<T, E>, E>

source

pub fn flatten(self) -> Result<T, E>

🔬This is a nightly-only experimental API. (result_flattening)

Converts from Result<Result<T, E>, E> to Result<T, E>

\n
Examples
\n
#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\n

Flattening only removes one level of nesting at a time:

\n\n
#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n
",0,"karyon_net::error::Result"],["
1.61.0 · source§

impl<T, E> Termination for Result<T, E>
where\n T: Termination,\n E: Debug,

source§

fn report(self) -> ExitCode

Is called to get the representation of the value as status code.\nThis status code is returned to the operating system.
","Termination","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> PartialOrd for Result<T, E>
where\n T: PartialOrd,\n E: PartialOrd,

source§

fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd","karyon_net::error::Result"],["
1.16.0 · source§

impl<T, U, E> Product<Result<U, E>> for Result<T, E>
where\n T: Product<U>,

source§

fn product<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the product of all elements is returned.

\n
Examples
\n

This multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err:

\n\n
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n
","Product>","karyon_net::error::Result"],["
source§

impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_net::error::Result"],["
source§

impl<T, E, F> FromResidual<Yeet<E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(_: Yeet<E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_net::error::Result"],["
source§

impl<T, E> Try for Result<T, E>

§

type Output = T

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value produced by ? when not short-circuiting.
§

type Residual = Result<Infallible, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value passed to FromResidual::from_residual\nas part of ? when short-circuiting. Read more
source§

fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from its Output type. Read more
source§

fn branch(\n self\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2)
Used in ? to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break). Read more
","Try","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Clone for Result<T, E>
where\n T: Clone,\n E: Clone,

source§

fn clone(&self) -> Result<T, E>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Result<T, E>)

Performs copy-assignment from source. Read more
","Clone","karyon_net::error::Result"],["
1.0.0 · source§

impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>
where\n V: FromIterator<A>,

source§

fn from_iter<I>(iter: I) -> Result<V, E>
where\n I: IntoIterator<Item = Result<A, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err occur, a\ncontainer with the values of each Result is returned.

\n

Here is an example which increments every integer in a vector,\nchecking for overflow:

\n\n
let v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\n

Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:

\n\n
let v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\n

Here is a variation on the previous example, showing that no\nfurther elements are taken from iter after the first Err.

\n\n
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n    shared += x;\n    x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\n

Since the third element caused an underflow, no further elements were taken,\nso the final value of shared is 6 (= 3 + 2 + 1), not 16.

\n
","FromIterator>","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralEq for Result<T, E>

","StructuralEq","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Eq for Result<T, E>
where\n T: Eq,\n E: Eq,

","Eq","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Hash for Result<T, E>
where\n T: Hash,\n E: Hash,

source§

fn hash<__H>(&self, state: &mut __H)
where\n __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Ord for Result<T, E>
where\n T: Ord,\n E: Ord,

source§

fn cmp(&self, other: &Result<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_net::error::Result"],["
source§

impl<T, E> Residual<T> for Result<Infallible, E>

§

type TryType = Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2_residual)
The “return” type of this meta-function.
","Residual","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> PartialEq for Result<T, E>
where\n T: PartialEq,\n E: PartialEq,

source§

fn eq(&self, other: &Result<T, E>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> IntoIterator for Result<T, E>

source§

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n
§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
","IntoIterator","karyon_net::error::Result"],["
1.16.0 · source§

impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
where\n T: Sum<U>,

source§

fn sum<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the sum of all elements is returned.

\n
Examples
\n

This sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:

\n\n
let f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n
","Sum>","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralPartialEq for Result<T, E>

","StructuralPartialEq","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Debug for Result<T, E>
where\n T: Debug,\n E: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_net::error::Result"],["
1.0.0 · source§

impl<T, E> Copy for Result<T, E>
where\n T: Copy,\n E: Copy,

","Copy","karyon_net::error::Result"],["
source§

impl<T, U> Encode for Result<T, U>
where\n T: Encode,\n U: Encode,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_net::error::Result"],["
source§

impl<'de, T, U> BorrowDecode<'de> for Result<T, U>
where\n T: BorrowDecode<'de>,\n U: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_net::error::Result"],["
source§

impl<T, U> Decode for Result<T, U>
where\n T: Decode,\n U: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_net::error::Result"]], +"karyon_p2p":[["
source§

impl<T, E> Result<T, E>

1.0.0 (const: 1.48.0) · source

pub const fn is_ok(&self) -> bool

Returns true if the result is Ok.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_ok(), true);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_ok(), false);
\n
1.70.0 · source

pub fn is_ok_and(self, f: impl FnOnce(T) -> bool) -> bool

Returns true if the result is Ok and the value inside of it matches a predicate.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.is_ok_and(|x| x > 1), true);\n\nlet x: Result<u32, &str> = Ok(0);\nassert_eq!(x.is_ok_and(|x| x > 1), false);\n\nlet x: Result<u32, &str> = Err(\"hey\");\nassert_eq!(x.is_ok_and(|x| x > 1), false);
\n
1.0.0 (const: 1.48.0) · source

pub const fn is_err(&self) -> bool

Returns true if the result is Err.

\n
Examples
\n
let x: Result<i32, &str> = Ok(-3);\nassert_eq!(x.is_err(), false);\n\nlet x: Result<i32, &str> = Err(\"Some error message\");\nassert_eq!(x.is_err(), true);
\n
1.70.0 · source

pub fn is_err_and(self, f: impl FnOnce(E) -> bool) -> bool

Returns true if the result is Err and the value inside of it matches a predicate.

\n
Examples
\n
use std::io::{Error, ErrorKind};\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::NotFound, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true);\n\nlet x: Result<u32, Error> = Err(Error::new(ErrorKind::PermissionDenied, \"!\"));\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);\n\nlet x: Result<u32, Error> = Ok(123);\nassert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false);
\n
1.0.0 · source

pub fn ok(self) -> Option<T>

Converts from Result<T, E> to Option<T>.

\n

Converts self into an Option<T>, consuming self,\nand discarding the error, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.ok(), Some(2));\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.ok(), None);
\n
1.0.0 · source

pub fn err(self) -> Option<E>

Converts from Result<T, E> to Option<E>.

\n

Converts self into an Option<E>, consuming self,\nand discarding the success value, if any.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.err(), None);\n\nlet x: Result<u32, &str> = Err(\"Nothing here\");\nassert_eq!(x.err(), Some(\"Nothing here\"));
\n
1.0.0 (const: 1.48.0) · source

pub const fn as_ref(&self) -> Result<&T, &E>

Converts from &Result<T, E> to Result<&T, &E>.

\n

Produces a new Result, containing a reference\ninto the original, leaving the original in place.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.as_ref(), Ok(&2));\n\nlet x: Result<u32, &str> = Err(\"Error\");\nassert_eq!(x.as_ref(), Err(&\"Error\"));
\n
1.0.0 (const: unstable) · source

pub fn as_mut(&mut self) -> Result<&mut T, &mut E>

Converts from &mut Result<T, E> to Result<&mut T, &mut E>.

\n
Examples
\n
fn mutate(r: &mut Result<i32, i32>) {\n    match r.as_mut() {\n        Ok(v) => *v = 42,\n        Err(e) => *e = 0,\n    }\n}\n\nlet mut x: Result<i32, i32> = Ok(2);\nmutate(&mut x);\nassert_eq!(x.unwrap(), 42);\n\nlet mut x: Result<i32, i32> = Err(13);\nmutate(&mut x);\nassert_eq!(x.unwrap_err(), 0);
\n
1.0.0 · source

pub fn map<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> U,

Maps a Result<T, E> to Result<U, E> by applying a function to a\ncontained Ok value, leaving an Err value untouched.

\n

This function can be used to compose the results of two functions.

\n
Examples
\n

Print the numbers on each line of a string multiplied by two.

\n\n
let line = \"1\\n2\\n3\\n4\\n\";\n\nfor num in line.lines() {\n    match num.parse::<i32>().map(|i| i * 2) {\n        Ok(n) => println!(\"{n}\"),\n        Err(..) => {}\n    }\n}
\n
1.41.0 · source

pub fn map_or<U, F>(self, default: U, f: F) -> U
where\n F: FnOnce(T) -> U,

Returns the provided default (if Err), or\napplies a function to the contained value (if Ok).

\n

Arguments passed to map_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let x: Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or(42, |v| v.len()), 42);
\n
1.41.0 · source

pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
where\n D: FnOnce(E) -> U,\n F: FnOnce(T) -> U,

Maps a Result<T, E> to U by applying fallback function default to\na contained Err value, or function f to a contained Ok value.

\n

This function can be used to unpack a successful result\nwhile handling an error.

\n
Examples
\n
let k = 21;\n\nlet x : Result<_, &str> = Ok(\"foo\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);\n\nlet x : Result<&str, _> = Err(\"bar\");\nassert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
\n
1.0.0 · source

pub fn map_err<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> F,

Maps a Result<T, E> to Result<T, F> by applying a function to a\ncontained Err value, leaving an Ok value untouched.

\n

This function can be used to pass through a successful result while handling\nan error.

\n
Examples
\n
fn stringify(x: u32) -> String { format!(\"error code: {x}\") }\n\nlet x: Result<u32, u32> = Ok(2);\nassert_eq!(x.map_err(stringify), Ok(2));\n\nlet x: Result<u32, u32> = Err(13);\nassert_eq!(x.map_err(stringify), Err(\"error code: 13\".to_string()));
\n
1.76.0 · source

pub fn inspect<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&T),

Calls the provided closure with a reference to the contained value (if Ok).

\n
Examples
\n
let x: u8 = \"4\"\n    .parse::<u8>()\n    .inspect(|x| println!(\"original: {x}\"))\n    .map(|x| x.pow(3))\n    .expect(\"failed to parse number\");
\n
1.76.0 · source

pub fn inspect_err<F>(self, f: F) -> Result<T, E>
where\n F: FnOnce(&E),

Calls the provided closure with a reference to the contained error (if Err).

\n
Examples
\n
use std::{fs, io};\n\nfn read() -> io::Result<String> {\n    fs::read_to_string(\"address.txt\")\n        .inspect_err(|e| eprintln!(\"failed to read file: {e}\"))\n}
\n
1.47.0 · source

pub fn as_deref(&self) -> Result<&<T as Deref>::Target, &E>
where\n T: Deref,

Converts from Result<T, E> (or &Result<T, E>) to Result<&<T as Deref>::Target, &E>.

\n

Coerces the Ok variant of the original Result via Deref\nand returns the new Result.

\n
Examples
\n
let x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&str, &u32> = Ok(\"hello\");\nassert_eq!(x.as_deref(), y);\n\nlet x: Result<String, u32> = Err(42);\nlet y: Result<&str, &u32> = Err(&42);\nassert_eq!(x.as_deref(), y);
\n
1.47.0 · source

pub fn as_deref_mut(&mut self) -> Result<&mut <T as Deref>::Target, &mut E>
where\n T: DerefMut,

Converts from Result<T, E> (or &mut Result<T, E>) to Result<&mut <T as DerefMut>::Target, &mut E>.

\n

Coerces the Ok variant of the original Result via DerefMut\nand returns the new Result.

\n
Examples
\n
let mut s = \"HELLO\".to_string();\nlet mut x: Result<String, u32> = Ok(\"hello\".to_string());\nlet y: Result<&mut str, &mut u32> = Ok(&mut s);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);\n\nlet mut i = 42;\nlet mut x: Result<String, u32> = Err(42);\nlet y: Result<&mut str, &mut u32> = Err(&mut i);\nassert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y);
\n
1.0.0 · source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(7);\nassert_eq!(x.iter().next(), Some(&7));\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter().next(), None);
\n
1.0.0 · source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns a mutable iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let mut x: Result<u32, &str> = Ok(7);\nmatch x.iter_mut().next() {\n    Some(v) => *v = 40,\n    None => {},\n}\nassert_eq!(x, Ok(40));\n\nlet mut x: Result<u32, &str> = Err(\"nothing!\");\nassert_eq!(x.iter_mut().next(), None);
\n
1.4.0 · source

pub fn expect(self, msg: &str) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message including the\npassed message, and the content of the Err.

\n
Examples
\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.expect(\"Testing expect\"); // panics with `Testing expect: emergency failure`
\n
Recommended Message Style
\n

We recommend that expect messages are used to describe the reason you\nexpect the Result should be Ok.

\n\n
let path = std::env::var(\"IMPORTANT_PATH\")\n    .expect(\"env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`\");
\n

Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.

\n

For more detail on expect message styles and the reasoning behind our recommendation please\nrefer to the section on “Common Message\nStyles” in the\nstd::error module docs.

\n
1.0.0 · source

pub fn unwrap(self) -> T
where\n E: Debug,

Returns the contained Ok value, consuming the self value.

\n

Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the Err\ncase explicitly, or call unwrap_or, unwrap_or_else, or\nunwrap_or_default.

\n
Panics
\n

Panics if the value is an Err, with a panic message provided by the\nErr’s value.

\n
Examples
\n

Basic usage:

\n\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(x.unwrap(), 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nx.unwrap(); // panics with `emergency failure`
\n
1.16.0 · source

pub fn unwrap_or_default(self) -> T
where\n T: Default,

Returns the contained Ok value or a default

\n

Consumes the self argument then, if Ok, returns the contained\nvalue, otherwise if Err, returns the default value for that\ntype.

\n
Examples
\n

Converts a string to an integer, turning poorly-formed strings\ninto 0 (the default value for integers). parse converts\na string to any other type that implements FromStr, returning an\nErr on error.

\n\n
let good_year_from_input = \"1909\";\nlet bad_year_from_input = \"190blarg\";\nlet good_year = good_year_from_input.parse().unwrap_or_default();\nlet bad_year = bad_year_from_input.parse().unwrap_or_default();\n\nassert_eq!(1909, good_year);\nassert_eq!(0, bad_year);
\n
1.17.0 · source

pub fn expect_err(self, msg: &str) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a panic message including the\npassed message, and the content of the Ok.

\n
Examples
\n
let x: Result<u32, &str> = Ok(10);\nx.expect_err(\"Testing expect_err\"); // panics with `Testing expect_err: 10`
\n
1.0.0 · source

pub fn unwrap_err(self) -> E
where\n T: Debug,

Returns the contained Err value, consuming the self value.

\n
Panics
\n

Panics if the value is an Ok, with a custom panic message provided\nby the Ok’s value.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nx.unwrap_err(); // panics with `2`
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(x.unwrap_err(), \"emergency failure\");
\n
source

pub fn into_ok(self) -> T
where\n E: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Ok value, but never panics.

\n

Unlike unwrap, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap as a maintainability safeguard that will fail\nto compile if the error type of the Result is later changed\nto an error that can actually occur.

\n
Examples
\n
\nfn only_good_news() -> Result<String, !> {\n    Ok(\"this is fine\".into())\n}\n\nlet s: String = only_good_news().into_ok();\nprintln!(\"{s}\");
\n
source

pub fn into_err(self) -> E
where\n T: Into<!>,

🔬This is a nightly-only experimental API. (unwrap_infallible)

Returns the contained Err value, but never panics.

\n

Unlike unwrap_err, this method is known to never panic on the\nresult types it is implemented for. Therefore, it can be used\ninstead of unwrap_err as a maintainability safeguard that will fail\nto compile if the ok type of the Result is later changed\nto a type that can actually occur.

\n
Examples
\n
\nfn only_bad_news() -> Result<!, String> {\n    Err(\"Oops, it failed\".into())\n}\n\nlet error: String = only_bad_news().into_err();\nprintln!(\"{error}\");
\n
1.0.0 · source

pub fn and<U>(self, res: Result<U, E>) -> Result<U, E>

Returns res if the result is Ok, otherwise returns the Err value of self.

\n

Arguments passed to and are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<&str, &str> = Ok(\"foo\");\nassert_eq!(x.and(y), Err(\"early error\"));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<&str, &str> = Err(\"late error\");\nassert_eq!(x.and(y), Err(\"not a 2\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<&str, &str> = Ok(\"different result type\");\nassert_eq!(x.and(y), Ok(\"different result type\"));
\n
1.0.0 · source

pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where\n F: FnOnce(T) -> Result<U, E>,

Calls op if the result is Ok, otherwise returns the Err value of self.

\n

This function can be used for control flow based on Result values.

\n
Examples
\n
fn sq_then_to_string(x: u32) -> Result<String, &'static str> {\n    x.checked_mul(x).map(|sq| sq.to_string()).ok_or(\"overflowed\")\n}\n\nassert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));\nassert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err(\"overflowed\"));\nassert_eq!(Err(\"not a number\").and_then(sq_then_to_string), Err(\"not a number\"));
\n

Often used to chain fallible operations that may return Err.

\n\n
use std::{io::ErrorKind, path::Path};\n\n// Note: on Windows \"/\" maps to \"C:\\\"\nlet root_modified_time = Path::new(\"/\").metadata().and_then(|md| md.modified());\nassert!(root_modified_time.is_ok());\n\nlet should_fail = Path::new(\"/bad/path\").metadata().and_then(|md| md.modified());\nassert!(should_fail.is_err());\nassert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound);
\n
1.0.0 · source

pub fn or<F>(self, res: Result<T, F>) -> Result<T, F>

Returns res if the result is Err, otherwise returns the Ok value of self.

\n

Arguments passed to or are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else, which is\nlazily evaluated.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"early error\");\nlet y: Result<u32, &str> = Ok(2);\nassert_eq!(x.or(y), Ok(2));\n\nlet x: Result<u32, &str> = Err(\"not a 2\");\nlet y: Result<u32, &str> = Err(\"late error\");\nassert_eq!(x.or(y), Err(\"late error\"));\n\nlet x: Result<u32, &str> = Ok(2);\nlet y: Result<u32, &str> = Ok(100);\nassert_eq!(x.or(y), Ok(2));
\n
1.0.0 · source

pub fn or_else<F, O>(self, op: O) -> Result<T, F>
where\n O: FnOnce(E) -> Result<T, F>,

Calls op if the result is Err, otherwise returns the Ok value of self.

\n

This function can be used for control flow based on result values.

\n
Examples
\n
fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }\nfn err(x: u32) -> Result<u32, u32> { Err(x) }\n\nassert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));\nassert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));\nassert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));\nassert_eq!(Err(3).or_else(err).or_else(err), Err(3));
\n
1.0.0 · source

pub fn unwrap_or(self, default: T) -> T

Returns the contained Ok value or a provided default.

\n

Arguments passed to unwrap_or are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else,\nwhich is lazily evaluated.

\n
Examples
\n
let default = 2;\nlet x: Result<u32, &str> = Ok(9);\nassert_eq!(x.unwrap_or(default), 9);\n\nlet x: Result<u32, &str> = Err(\"error\");\nassert_eq!(x.unwrap_or(default), default);
\n
1.0.0 · source

pub fn unwrap_or_else<F>(self, op: F) -> T
where\n F: FnOnce(E) -> T,

Returns the contained Ok value or computes it from a closure.

\n
Examples
\n
fn count(x: &str) -> usize { x.len() }\n\nassert_eq!(Ok(2).unwrap_or_else(count), 2);\nassert_eq!(Err(\"foo\").unwrap_or_else(count), 3);
\n
1.58.0 · source

pub unsafe fn unwrap_unchecked(self) -> T

Returns the contained Ok value, consuming the self value,\nwithout checking that the value is not an Err.

\n
Safety
\n

Calling this method on an Err is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nassert_eq!(unsafe { x.unwrap_unchecked() }, 2);
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nunsafe { x.unwrap_unchecked(); } // Undefined behavior!
\n
1.58.0 · source

pub unsafe fn unwrap_err_unchecked(self) -> E

Returns the contained Err value, consuming the self value,\nwithout checking that the value is not an Ok.

\n
Safety
\n

Calling this method on an Ok is undefined behavior.

\n
Examples
\n
let x: Result<u32, &str> = Ok(2);\nunsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
\n\n
let x: Result<u32, &str> = Err(\"emergency failure\");\nassert_eq!(unsafe { x.unwrap_err_unchecked() }, \"emergency failure\");
\n
",0,"karyon_p2p::error::Result"],["
source§

impl<T, E> Result<&T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let val = 12;\nlet x: Result<&i32, i32> = Ok(&val);\nassert_eq!(x, Ok(&12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_p2p::error::Result"],["
source§

impl<T, E> Result<&mut T, E>

1.59.0 · source

pub fn copied(self) -> Result<T, E>
where\n T: Copy,

Maps a Result<&mut T, E> to a Result<T, E> by copying the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet copied = x.copied();\nassert_eq!(copied, Ok(12));
\n
1.59.0 · source

pub fn cloned(self) -> Result<T, E>
where\n T: Clone,

Maps a Result<&mut T, E> to a Result<T, E> by cloning the contents of the\nOk part.

\n
Examples
\n
let mut val = 12;\nlet x: Result<&mut i32, i32> = Ok(&mut val);\nassert_eq!(x, Ok(&mut 12));\nlet cloned = x.cloned();\nassert_eq!(cloned, Ok(12));
\n
",0,"karyon_p2p::error::Result"],["
source§

impl<T, E> Result<Option<T>, E>

1.33.0 (const: unstable) · source

pub fn transpose(self) -> Option<Result<T, E>>

Transposes a Result of an Option into an Option of a Result.

\n

Ok(None) will be mapped to None.\nOk(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

\n
Examples
\n
#[derive(Debug, Eq, PartialEq)]\nstruct SomeErr;\n\nlet x: Result<Option<i32>, SomeErr> = Ok(Some(5));\nlet y: Option<Result<i32, SomeErr>> = Some(Ok(5));\nassert_eq!(x.transpose(), y);
\n
",0,"karyon_p2p::error::Result"],["
source§

impl<T, E> Result<Result<T, E>, E>

source

pub fn flatten(self) -> Result<T, E>

🔬This is a nightly-only experimental API. (result_flattening)

Converts from Result<Result<T, E>, E> to Result<T, E>

\n
Examples
\n
#![feature(result_flattening)]\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Ok(\"hello\"));\nassert_eq!(Ok(\"hello\"), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));\nassert_eq!(Err(6), x.flatten());\n\nlet x: Result<Result<&'static str, u32>, u32> = Err(6);\nassert_eq!(Err(6), x.flatten());
\n

Flattening only removes one level of nesting at a time:

\n\n
#![feature(result_flattening)]\nlet x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok(\"hello\")));\nassert_eq!(Ok(Ok(\"hello\")), x.flatten());\nassert_eq!(Ok(\"hello\"), x.flatten().flatten());
\n
",0,"karyon_p2p::error::Result"],["
1.61.0 · source§

impl<T, E> Termination for Result<T, E>
where\n T: Termination,\n E: Debug,

source§

fn report(self) -> ExitCode

Is called to get the representation of the value as status code.\nThis status code is returned to the operating system.
","Termination","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> PartialOrd for Result<T, E>
where\n T: PartialOrd,\n E: PartialOrd,

source§

fn partial_cmp(&self, other: &Result<T, E>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <=\noperator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >=\noperator. Read more
","PartialOrd","karyon_p2p::error::Result"],["
1.16.0 · source§

impl<T, U, E> Product<Result<U, E>> for Result<T, E>
where\n T: Product<U>,

source§

fn product<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the product of all elements is returned.

\n
Examples
\n

This multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns Err:

\n\n
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert_eq!(total, Ok(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product();\nassert!(total.is_err());
\n
","Product>","karyon_p2p::error::Result"],["
source§

impl<T, E, F> FromResidual<Result<Infallible, E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(residual: Result<Infallible, E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_p2p::error::Result"],["
source§

impl<T, E, F> FromResidual<Yeet<E>> for Result<T, F>
where\n F: From<E>,

source§

fn from_residual(_: Yeet<E>) -> Result<T, F>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
","FromResidual>","karyon_p2p::error::Result"],["
source§

impl<T, E> Try for Result<T, E>

§

type Output = T

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value produced by ? when not short-circuiting.
§

type Residual = Result<Infallible, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
The type of the value passed to FromResidual::from_residual\nas part of ? when short-circuiting. Read more
source§

fn from_output(output: <Result<T, E> as Try>::Output) -> Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from its Output type. Read more
source§

fn branch(\n self\n) -> ControlFlow<<Result<T, E> as Try>::Residual, <Result<T, E> as Try>::Output>

🔬This is a nightly-only experimental API. (try_trait_v2)
Used in ? to decide whether the operator should produce a value\n(because this returned ControlFlow::Continue)\nor propagate a value back to the caller\n(because this returned ControlFlow::Break). Read more
","Try","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Clone for Result<T, E>
where\n T: Clone,\n E: Clone,

source§

fn clone(&self) -> Result<T, E>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Result<T, E>)

Performs copy-assignment from source. Read more
","Clone","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>
where\n V: FromIterator<A>,

source§

fn from_iter<I>(iter: I) -> Result<V, E>
where\n I: IntoIterator<Item = Result<A, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err occur, a\ncontainer with the values of each Result is returned.

\n

Here is an example which increments every integer in a vector,\nchecking for overflow:

\n\n
let v = vec![1, 2];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_add(1).ok_or(\"Overflow!\")\n).collect();\nassert_eq!(res, Ok(vec![2, 3]));
\n

Here is another example that tries to subtract one from another list\nof integers, this time checking for underflow:

\n\n
let v = vec![1, 2, 0];\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|\n    x.checked_sub(1).ok_or(\"Underflow!\")\n).collect();\nassert_eq!(res, Err(\"Underflow!\"));
\n

Here is a variation on the previous example, showing that no\nfurther elements are taken from iter after the first Err.

\n\n
let v = vec![3, 2, 1, 10];\nlet mut shared = 0;\nlet res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {\n    shared += x;\n    x.checked_sub(2).ok_or(\"Underflow!\")\n}).collect();\nassert_eq!(res, Err(\"Underflow!\"));\nassert_eq!(shared, 6);
\n

Since the third element caused an underflow, no further elements were taken,\nso the final value of shared is 6 (= 3 + 2 + 1), not 16.

\n
","FromIterator>","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralEq for Result<T, E>

","StructuralEq","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Eq for Result<T, E>
where\n T: Eq,\n E: Eq,

","Eq","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Hash for Result<T, E>
where\n T: Hash,\n E: Hash,

source§

fn hash<__H>(&self, state: &mut __H)
where\n __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where\n H: Hasher,\n Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
","Hash","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Ord for Result<T, E>
where\n T: Ord,\n E: Ord,

source§

fn cmp(&self, other: &Result<T, E>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where\n Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where\n Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
","Ord","karyon_p2p::error::Result"],["
source§

impl<T, E> Residual<T> for Result<Infallible, E>

§

type TryType = Result<T, E>

🔬This is a nightly-only experimental API. (try_trait_v2_residual)
The “return” type of this meta-function.
","Residual","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> PartialEq for Result<T, E>
where\n T: PartialEq,\n E: PartialEq,

source§

fn eq(&self, other: &Result<T, E>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> IntoIterator for Result<T, E>

source§

fn into_iter(self) -> IntoIter<T>

Returns a consuming iterator over the possibly contained value.

\n

The iterator yields one value if the result is Result::Ok, otherwise none.

\n
Examples
\n
let x: Result<u32, &str> = Ok(5);\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, [5]);\n\nlet x: Result<u32, &str> = Err(\"nothing!\");\nlet v: Vec<u32> = x.into_iter().collect();\nassert_eq!(v, []);
\n
§

type Item = T

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
","IntoIterator","karyon_p2p::error::Result"],["
1.16.0 · source§

impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
where\n T: Sum<U>,

source§

fn sum<I>(iter: I) -> Result<T, E>
where\n I: Iterator<Item = Result<U, E>>,

Takes each element in the Iterator: if it is an Err, no further\nelements are taken, and the Err is returned. Should no Err\noccur, the sum of all elements is returned.

\n
Examples
\n

This sums up every integer in a vector, rejecting the sum if a negative\nelement is encountered:

\n\n
let f = |&x: &i32| if x < 0 { Err(\"Negative element found\") } else { Ok(x) };\nlet v = vec![1, 2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Ok(3));\nlet v = vec![1, -2];\nlet res: Result<i32, _> = v.iter().map(f).sum();\nassert_eq!(res, Err(\"Negative element found\"));
\n
","Sum>","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> StructuralPartialEq for Result<T, E>

","StructuralPartialEq","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Debug for Result<T, E>
where\n T: Debug,\n E: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_p2p::error::Result"],["
1.0.0 · source§

impl<T, E> Copy for Result<T, E>
where\n T: Copy,\n E: Copy,

","Copy","karyon_p2p::error::Result"],["
source§

impl<T, U> Encode for Result<T, U>
where\n T: Encode,\n U: Encode,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_p2p::error::Result"],["
source§

impl<'de, T, U> BorrowDecode<'de> for Result<T, U>
where\n T: BorrowDecode<'de>,\n U: BorrowDecode<'de>,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_p2p::error::Result"],["
source§

impl<T, U> Decode for Result<T, U>
where\n T: Decode,\n U: Decode,

source§

fn decode<D>(decoder: &mut D) -> Result<Result<T, U>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_p2p::error::Result"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/std/collections/hash/map/struct.HashMap.js b/type.impl/std/collections/hash/map/struct.HashMap.js new file mode 100644 index 00000000..132f618f --- /dev/null +++ b/type.impl/std/collections/hash/map/struct.HashMap.js @@ -0,0 +1,3 @@ +(function() {var type_impls = { +"karyon_core":[["
source§

impl<K, V> HashMap<K, V>

1.0.0 · source

pub fn new() -> HashMap<K, V>

Creates an empty HashMap.

\n

The hash map is initially created with a capacity of 0, so it will not allocate until it\nis first inserted into.

\n
Examples
\n
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();
\n
1.0.0 · source

pub fn with_capacity(capacity: usize) -> HashMap<K, V>

Creates an empty HashMap with at least the specified capacity.

\n

The hash map will be able to hold at least capacity elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity. If capacity is 0, the hash map will not allocate.

\n
Examples
\n
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
\n
",0,"karyon_core::event::Listeners"],["
source§

impl<K, V, S> HashMap<K, V, S>

1.7.0 (const: unstable) · source

pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S>

Creates an empty HashMap which will use the given hash builder to hash\nkeys.

\n

The created map has the default initial capacity.

\n

Warning: hash_builder is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.

\n

The hash_builder passed should implement the BuildHasher trait for\nthe HashMap to be useful, see its documentation for details.

\n
Examples
\n
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_hasher(s);\nmap.insert(1, 2);
\n
1.7.0 · source

pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashMap<K, V, S>

Creates an empty HashMap with at least the specified capacity, using\nhasher to hash the keys.

\n

The hash map will be able to hold at least capacity elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity. If capacity is 0, the hash map will not allocate.

\n

Warning: hasher is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.

\n

The hasher passed should implement the BuildHasher trait for\nthe HashMap to be useful, see its documentation for details.

\n
Examples
\n
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_capacity_and_hasher(10, s);\nmap.insert(1, 2);
\n
1.0.0 · source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

\n

This number is a lower bound; the HashMap<K, V> might be able to hold\nmore, but is guaranteed to be able to hold at least this many.

\n
Examples
\n
use std::collections::HashMap;\nlet map: HashMap<i32, i32> = HashMap::with_capacity(100);\nassert!(map.capacity() >= 100);
\n
1.0.0 · source

pub fn keys(&self) -> Keys<'_, K, V>

An iterator visiting all keys in arbitrary order.\nThe iterator element type is &'a K.

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nfor key in map.keys() {\n    println!(\"{key}\");\n}
\n
Performance
\n

In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.54.0 · source

pub fn into_keys(self) -> IntoKeys<K, V>

Creates a consuming iterator visiting all the keys in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is K.

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nlet mut vec: Vec<&str> = map.into_keys().collect();\n// The `IntoKeys` iterator produces keys in arbitrary order, so the\n// keys must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [\"a\", \"b\", \"c\"]);
\n
Performance
\n

In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.0.0 · source

pub fn values(&self) -> Values<'_, K, V>

An iterator visiting all values in arbitrary order.\nThe iterator element type is &'a V.

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nfor val in map.values() {\n    println!(\"{val}\");\n}
\n
Performance
\n

In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.10.0 · source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>

An iterator visiting all values mutably in arbitrary order.\nThe iterator element type is &'a mut V.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nfor val in map.values_mut() {\n    *val = *val + 10;\n}\n\nfor val in map.values() {\n    println!(\"{val}\");\n}
\n
Performance
\n

In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.54.0 · source

pub fn into_values(self) -> IntoValues<K, V>

Creates a consuming iterator visiting all the values in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is V.

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nlet mut vec: Vec<i32> = map.into_values().collect();\n// The `IntoValues` iterator produces values in arbitrary order, so\n// the values must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [1, 2, 3]);
\n
Performance
\n

In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.0.0 · source

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order.\nThe iterator element type is (&'a K, &'a V).

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\nfor (key, val) in map.iter() {\n    println!(\"key: {key} val: {val}\");\n}
\n
Performance
\n

In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.0.0 · source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order,\nwith mutable references to the values.\nThe iterator element type is (&'a K, &'a mut V).

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\n// Update all values\nfor (_, val) in map.iter_mut() {\n    *val *= 2;\n}\n\nfor (key, val) in &map {\n    println!(\"key: {key} val: {val}\");\n}
\n
Performance
\n

In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.0.0 · source

pub fn len(&self) -> usize

Returns the number of elements in the map.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert_eq!(a.len(), 0);\na.insert(1, \"a\");\nassert_eq!(a.len(), 1);
\n
1.0.0 · source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert!(a.is_empty());\na.insert(1, \"a\");\nassert!(!a.is_empty());
\n
1.6.0 · source

pub fn drain(&mut self) -> Drain<'_, K, V>

Clears the map, returning all key-value pairs as an iterator. Keeps the\nallocated memory for reuse.

\n

If the returned iterator is dropped before being fully consumed, it\ndrops the remaining key-value pairs. The returned iterator keeps a\nmutable borrow on the map to optimize its implementation.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.insert(2, \"b\");\n\nfor (k, v) in a.drain().take(1) {\n    assert!(k == 1 || k == 2);\n    assert!(v == \"a\" || v == \"b\");\n}\n\nassert!(a.is_empty());
\n
source

pub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, K, V, F>
where\n F: FnMut(&K, &mut V) -> bool,

🔬This is a nightly-only experimental API. (hash_extract_if)

Creates an iterator which uses a closure to determine if an element should be removed.

\n

If the closure returns true, the element is removed from the map and yielded.\nIf the closure returns false, or panics, the element remains in the map and will not be\nyielded.

\n

Note that extract_if lets you mutate every value in the filter closure, regardless of\nwhether you choose to keep or remove it.

\n

If the returned ExtractIf is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain with a negated predicate if you do not need the returned iterator.

\n
Examples
\n

Splitting a map into even and odd keys, reusing the original map:

\n\n
#![feature(hash_extract_if)]\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();\nlet extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();\n\nlet mut evens = extracted.keys().copied().collect::<Vec<_>>();\nlet mut odds = map.keys().copied().collect::<Vec<_>>();\nevens.sort();\nodds.sort();\n\nassert_eq!(evens, vec![0, 2, 4, 6]);\nassert_eq!(odds, vec![1, 3, 5, 7]);
\n
1.18.0 · source

pub fn retain<F>(&mut self, f: F)
where\n F: FnMut(&K, &mut V) -> bool,

Retains only the elements specified by the predicate.

\n

In other words, remove all pairs (k, v) for which f(&k, &mut v) returns false.\nThe elements are visited in unsorted (and unspecified) order.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();\nmap.retain(|&k, _| k % 2 == 0);\nassert_eq!(map.len(), 4);
\n
Performance
\n

In the current implementation, this operation takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.

\n
1.0.0 · source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs. Keeps the allocated memory\nfor reuse.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.clear();\nassert!(a.is_empty());
\n
1.9.0 · source

pub fn hasher(&self) -> &S

Returns a reference to the map’s BuildHasher.

\n
Examples
\n
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet hasher = RandomState::new();\nlet map: HashMap<i32, i32> = HashMap::with_hasher(hasher);\nlet hasher: &RandomState = map.hasher();
\n
",0,"karyon_core::event::Listeners"],["
source§

impl<K, V, S> HashMap<K, V, S>
where\n K: Eq + Hash,\n S: BuildHasher,

1.0.0 · source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted\nin the HashMap. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling reserve,\ncapacity will be greater than or equal to self.len() + additional.\nDoes nothing if capacity is already sufficient.

\n
Panics
\n

Panics if the new allocation size overflows usize.

\n
Examples
\n
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();\nmap.reserve(10);
\n
1.57.0 · source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional more elements to be inserted\nin the HashMap. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling try_reserve,\ncapacity will be greater than or equal to self.len() + additional if\nit returns Ok(()).\nDoes nothing if capacity is already sufficient.

\n
Errors
\n

If the capacity overflows, or the allocator reports a failure, then an error\nis returned.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map: HashMap<&str, isize> = HashMap::new();\nmap.try_reserve(10).expect(\"why is the test harness OOMing on a handful of bytes?\");
\n
1.0.0 · source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the map as much as possible. It will drop\ndown as much as possible while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to_fit();\nassert!(map.capacity() >= 2);
\n
1.56.0 · source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of the map with a lower limit. It will drop\ndown no lower than the supplied limit while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.

\n

If the current capacity is less than the lower limit, this is a no-op.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to(10);\nassert!(map.capacity() >= 10);\nmap.shrink_to(0);\nassert!(map.capacity() >= 2);
\n
1.0.0 · source

pub fn entry(&mut self, key: K) -> Entry<'_, K, V>

Gets the given key’s corresponding entry in the map for in-place manipulation.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut letters = HashMap::new();\n\nfor ch in \"a short treatise on fungi\".chars() {\n    letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);\n}\n\nassert_eq!(letters[&'s'], 2);\nassert_eq!(letters[&'t'], 3);\nassert_eq!(letters[&'u'], 1);\nassert_eq!(letters.get(&'y'), None);
\n
1.0.0 · source

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Returns a reference to the value corresponding to the key.

\n

The key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get(&1), Some(&\"a\"));\nassert_eq!(map.get(&2), None);
\n
1.40.0 · source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Returns the key-value pair corresponding to the supplied key.

\n

The supplied key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get_key_value(&1), Some((&1, &\"a\")));\nassert_eq!(map.get_key_value(&2), None);
\n
source

pub fn get_many_mut<Q, const N: usize>(\n &mut self,\n ks: [&Q; N]\n) -> Option<[&mut V; N]>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

🔬This is a nightly-only experimental API. (map_many_mut)

Attempts to get mutable references to N values in the map at once.

\n

Returns an array of length N with the results of each query. For soundness, at most one\nmutable reference will be returned to any value. None will be returned if any of the\nkeys are duplicates or missing.

\n
Examples
\n
#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n    \"Athenæum\",\n    \"Library of Congress\",\n]);\nassert_eq!(\n    got,\n    Some([\n        &mut 1807,\n        &mut 1800,\n    ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n    \"Athenæum\",\n    \"New York Public Library\",\n]);\nassert_eq!(got, None);\n\n// Duplicate keys result in None\nlet got = libraries.get_many_mut([\n    \"Athenæum\",\n    \"Athenæum\",\n]);\nassert_eq!(got, None);
\n
source

pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(\n &mut self,\n ks: [&Q; N]\n) -> Option<[&mut V; N]>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

🔬This is a nightly-only experimental API. (map_many_mut)

Attempts to get mutable references to N values in the map at once, without validating that\nthe values are unique.

\n

Returns an array of length N with the results of each query. None will be returned if\nany of the keys are missing.

\n

For a safe alternative see get_many_mut.

\n
Safety
\n

Calling this method with overlapping keys is undefined behavior even if the resulting\nreferences are not used.

\n
Examples
\n
#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n    \"Athenæum\",\n    \"Library of Congress\",\n]);\nassert_eq!(\n    got,\n    Some([\n        &mut 1807,\n        &mut 1800,\n    ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n    \"Athenæum\",\n    \"New York Public Library\",\n]);\nassert_eq!(got, None);
\n
1.0.0 · source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Returns true if the map contains a value for the specified key.

\n

The key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.contains_key(&1), true);\nassert_eq!(map.contains_key(&2), false);
\n
1.0.0 · source

pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Returns a mutable reference to the value corresponding to the key.

\n

The key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nif let Some(x) = map.get_mut(&1) {\n    *x = \"b\";\n}\nassert_eq!(map[&1], \"b\");
\n
1.0.0 · source

pub fn insert(&mut self, k: K, v: V) -> Option<V>

Inserts a key-value pair into the map.

\n

If the map did not have this key present, None is returned.

\n

If the map did have this key present, the value is updated, and the old\nvalue is returned. The key is not updated, though; this matters for\ntypes that can be == without being identical. See the module-level\ndocumentation for more.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.insert(37, \"a\"), None);\nassert_eq!(map.is_empty(), false);\n\nmap.insert(37, \"b\");\nassert_eq!(map.insert(37, \"c\"), Some(\"b\"));\nassert_eq!(map[&37], \"c\");
\n
source

pub fn try_insert(\n &mut self,\n key: K,\n value: V\n) -> Result<&mut V, OccupiedError<'_, K, V>>

🔬This is a nightly-only experimental API. (map_try_insert)

Tries to insert a key-value pair into the map, and returns\na mutable reference to the value in the entry.

\n

If the map already had this key present, nothing is updated, and\nan error containing the occupied entry and the value is returned.

\n
Examples
\n

Basic usage:

\n\n
#![feature(map_try_insert)]\n\nuse std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.try_insert(37, \"a\").unwrap(), &\"a\");\n\nlet err = map.try_insert(37, \"b\").unwrap_err();\nassert_eq!(err.entry.key(), &37);\nassert_eq!(err.entry.get(), &\"a\");\nassert_eq!(err.value, \"b\");
\n
1.0.0 · source

pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Removes a key from the map, returning the value at the key if the key\nwas previously in the map.

\n

The key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove(&1), Some(\"a\"));\nassert_eq!(map.remove(&1), None);
\n
1.27.0 · source

pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
where\n K: Borrow<Q>,\n Q: Hash + Eq + ?Sized,

Removes a key from the map, returning the stored key and value if the\nkey was previously in the map.

\n

The key may be any borrowed form of the map’s key type, but\nHash and Eq on the borrowed form must match those for\nthe key type.

\n
Examples
\n
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove_entry(&1), Some((1, \"a\")));\nassert_eq!(map.remove(&1), None);
\n
",0,"karyon_core::event::Listeners"],["
source§

impl<K, V, S> HashMap<K, V, S>
where\n S: BuildHasher,

source

pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S>

🔬This is a nightly-only experimental API. (hash_raw_entry)

Creates a raw entry builder for the HashMap.

\n

Raw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched. After this, insertions into a vacant entry\nstill require an owned key to be provided.

\n

Raw entries are useful for such exotic situations as:

\n
    \n
  • Hash memoization
  • \n
  • Deferring the creation of an owned key until it is known to be required
  • \n
  • Using a search key that doesn’t work with the Borrow trait
  • \n
  • Using custom comparison logic without newtype wrappers
  • \n
\n

Because raw entries provide much more low-level control, it’s much easier\nto put the HashMap into an inconsistent state which, while memory-safe,\nwill cause the map to produce seemingly random results. Higher-level and\nmore foolproof APIs like entry should be preferred when possible.

\n

In particular, the hash used to initialized the raw entry must still be\nconsistent with the hash of the key that is ultimately stored in the entry.\nThis is because implementations of HashMap may need to recompute hashes\nwhen resizing, at which point only the keys are available.

\n

Raw entries give mutable access to the keys. This must not be used\nto modify how the key would compare or hash, as the map will not re-evaluate\nwhere the key should go, meaning the keys may become “lost” if their\nlocation does not reflect their state. For instance, if you change a key\nso that the map now contains keys which compare equal, search may start\nacting erratically, with two keys randomly masking each other. Implementations\nare free to assume this doesn’t happen (within the limits of memory-safety).

\n
source

pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>

🔬This is a nightly-only experimental API. (hash_raw_entry)

Creates a raw immutable entry builder for the HashMap.

\n

Raw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched.

\n

This is useful for

\n
    \n
  • Hash memoization
  • \n
  • Using a search key that doesn’t work with the Borrow trait
  • \n
  • Using custom comparison logic without newtype wrappers
  • \n
\n

Unless you are in such a situation, higher-level and more foolproof APIs like\nget should be preferred.

\n

Immutable raw entries have very limited use; you might instead want raw_entry_mut.

\n
",0,"karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> IntoIterator for HashMap<K, V, S>

source§

fn into_iter(self) -> IntoIter<K, V>

Creates a consuming iterator, that is, one that moves each key-value\npair out of the map in arbitrary order. The map cannot be used after\ncalling this.

\n
Examples
\n
use std::collections::HashMap;\n\nlet map = HashMap::from([\n    (\"a\", 1),\n    (\"b\", 2),\n    (\"c\", 3),\n]);\n\n// Not possible with .iter()\nlet vec: Vec<(&str, i32)> = map.into_iter().collect();
\n
§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?
","IntoIterator","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, Q, V, S> Index<&Q> for HashMap<K, V, S>
where\n K: Eq + Hash + Borrow<Q>,\n Q: Eq + Hash + ?Sized,\n S: BuildHasher,

source§

fn index(&self, key: &Q) -> &V

Returns a reference to the value corresponding to the supplied key.

\n
Panics
\n

Panics if the key is not present in the HashMap.

\n
§

type Output = V

The returned type after indexing.
","Index<&Q>","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where\n K: Eq + Hash,\n S: BuildHasher + Default,

source§

fn from_iter<T>(iter: T) -> HashMap<K, V, S>
where\n T: IntoIterator<Item = (K, V)>,

Creates a value from an iterator. Read more
","FromIterator<(K, V)>","karyon_core::event::Listeners"],["
1.56.0 · source§

impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V>
where\n K: Eq + Hash,

source§

fn from(arr: [(K, V); N]) -> HashMap<K, V>

Examples
\n
use std::collections::HashMap;\n\nlet map1 = HashMap::from([(1, 2), (3, 4)]);\nlet map2: HashMap<_, _> = [(1, 2), (3, 4)].into();\nassert_eq!(map1, map2);
\n
","From<[(K, V); N]>","karyon_core::event::Listeners"],["
1.36.0 · source§

impl<K, V, S> UnwindSafe for HashMap<K, V, S>
where\n K: UnwindSafe,\n V: UnwindSafe,\n S: UnwindSafe,

","UnwindSafe","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> Clone for HashMap<K, V, S>
where\n K: Clone,\n V: Clone,\n S: Clone,

source§

fn clone(&self) -> HashMap<K, V, S>

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, other: &HashMap<K, V, S>)

Performs copy-assignment from source. Read more
","Clone","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
where\n K: Eq + Hash,\n S: BuildHasher,

Inserts all new key-values from the iterator and replaces values with existing\nkeys with new values returned from the iterator.

\n
source§

fn extend<T>(&mut self, iter: T)
where\n T: IntoIterator<Item = (K, V)>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, _: (K, V))

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend<(K, V)>","karyon_core::event::Listeners"],["
1.4.0 · source§

impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
where\n K: Eq + Hash + Copy,\n V: Copy,\n S: BuildHasher,

source§

fn extend<T>(&mut self, iter: T)
where\n T: IntoIterator<Item = (&'a K, &'a V)>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, _: (&'a K, &'a V))

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
","Extend<(&'a K, &'a V)>","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> Eq for HashMap<K, V, S>
where\n K: Eq + Hash,\n V: Eq,\n S: BuildHasher,

","Eq","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> Default for HashMap<K, V, S>
where\n S: Default,

source§

fn default() -> HashMap<K, V, S>

Creates an empty HashMap<K, V, S>, with the Default value for the hasher.

\n
","Default","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> Debug for HashMap<K, V, S>
where\n K: Debug,\n V: Debug,

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
","Debug","karyon_core::event::Listeners"],["
1.0.0 · source§

impl<K, V, S> PartialEq for HashMap<K, V, S>
where\n K: Eq + Hash,\n V: PartialEq,\n S: BuildHasher,

source§

fn eq(&self, other: &HashMap<K, V, S>) -> bool

This method tests for self and other values to be equal, and is used\nby ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always\nsufficient, and should not be overridden without very good reason.
","PartialEq","karyon_core::event::Listeners"],["
source§

impl<K, V, S> Encode for HashMap<K, V, S>
where\n K: Encode,\n V: Encode,

source§

fn encode<E>(&self, encoder: &mut E) -> Result<(), EncodeError>
where\n E: Encoder,

Encode a given type.
","Encode","karyon_core::event::Listeners"],["
source§

impl<'de, K, V, S> BorrowDecode<'de> for HashMap<K, V, S>
where\n K: BorrowDecode<'de> + Eq + Hash,\n V: BorrowDecode<'de>,\n S: BuildHasher + Default,

source§

fn borrow_decode<D>(decoder: &mut D) -> Result<HashMap<K, V, S>, DecodeError>
where\n D: BorrowDecoder<'de>,

Attempt to decode this type with the given BorrowDecode.
","BorrowDecode<'de>","karyon_core::event::Listeners"],["
source§

impl<K, V, S> Decode for HashMap<K, V, S>
where\n K: Decode + Eq + Hash,\n V: Decode,\n S: BuildHasher + Default,

source§

fn decode<D>(decoder: &mut D) -> Result<HashMap<K, V, S>, DecodeError>
where\n D: Decoder,

Attempt to decode this type with the given Decode.
","Decode","karyon_core::event::Listeners"]] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/std/primitive.array.js b/type.impl/std/primitive.array.js new file mode 100644 index 00000000..b9551e80 --- /dev/null +++ b/type.impl/std/primitive.array.js @@ -0,0 +1,3 @@ +(function() {var type_impls = { +"karyon_p2p":[] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file diff --git a/type.impl/std/primitive.u16.js b/type.impl/std/primitive.u16.js new file mode 100644 index 00000000..a3208395 --- /dev/null +++ b/type.impl/std/primitive.u16.js @@ -0,0 +1,5 @@ +(function() {var type_impls = { +"karyon_core":[], +"karyon_net":[], +"karyon_p2p":[] +};if (window.register_type_impls) {window.register_type_impls(type_impls);} else {window.pending_type_impls = type_impls;}})() \ No newline at end of file