Struct Message

Source
pub struct Message {
    pub transaction_id: Vec<u8>,
    pub version: Option<Vec<u8>>,
    pub requester_ip: Option<SocketAddr>,
    pub message_type: MessageType,
    pub read_only: Option<bool>,
}
Expand description

All packets sent and received via DHT are a serialized version of this struct.

It can be used to represent DHT messages throughout a program and has methods to serialize and deserialize DHT messages.

§Building

The easiest way to build Message structs is to use MessageBuilder.

But if you need more control/flexibility than provided by MessageBuilder, you can build Message structs directly:

use rustydht_lib::common::Id;
use rustydht_lib::packets::{Message, MessageType, RequestSpecific, FindNodeRequestArguments};

// This constructs a find_node request. It would be easier with MessageBuilder.
let msg = Message {
    transaction_id: vec![1, 2, 3],
    version: Some(vec![0x62, 0x61, 0x72, 0x66]),
    requester_ip: None,
    read_only: None,
    message_type: MessageType::Request(RequestSpecific::FindNodeRequest(
        FindNodeRequestArguments {
            target: Id::from_hex("1234123412341234123412341234123412341234").unwrap(),
            requester_id: Id::from_hex("5678567856785678567856785678567856785678").unwrap(),
        },
    )),
};

§Deserializing

use rustydht_lib::packets::Message;

// Imagine that this vector contains bytes from reading from a socket
let bytes: Vec<u8> = Vec::new();
match Message::from_bytes(&bytes) {
    Ok(msg) => {
        // Success! do something with the Message you just parsed
    }
    Err(e) => {
        eprintln!("Oh no! I hit an error while parsing a Message: {}", e);
    }
}

§Serializing

use rustydht_lib::common::Id;
use rustydht_lib::packets::{Message, MessageBuilder};

let our_id = Id::from_hex("0000000000000000000000000000000000000001").unwrap();
let target = Id::from_hex("ff00000000000000000000000000000000000002").unwrap();
let msg = MessageBuilder::new_find_node_request()
    .sender_id(our_id)
    .target(target)
    .build()
    .unwrap();
match msg.to_bytes() {
    Ok(bytes) => {
        // Success! You have a Vec<u8> that can be sent over a socket or whatever
    }
    Err(e) => {
        eprintln!("Oh no! Couldn't serialize: {}", e);
    }
}

Fields§

§transaction_id: Vec<u8>§version: Option<Vec<u8>>

The version of the requester or responder.

§requester_ip: Option<SocketAddr>

The IP address and port (“SocketAddr”) of the requester as seen from the responder’s point of view. This should be set only on response, but is defined at this level with the other common fields to avoid defining yet another layer on the response objects.

§message_type: MessageType§read_only: Option<bool>

For bep0043. When set true on a request, indicates that the requester can’t reply to requests and that responders should not add requester to their routing tables. Should only be set on requests - undefined behavior when set on a response.

Implementations§

Source§

impl Message

Source

pub fn to_bytes(self) -> Result<Vec<u8>, RustyDHTError>

Source

pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Message, RustyDHTError>

Source

pub fn get_author_id(&self) -> Option<Id>

Return the Id of the sender of the Message

This is less straightforward than it seems because not all messages are sent with an Id (all are except Error messages). This is reflected in the structure of DHT Messages, and makes it a bit annoying to learn the sender’s Id without unraveling the entire message. This method is a convenience method to extract the sender (or “author”) Id from the guts of any Message.

Trait Implementations§

Source§

impl Clone for Message

Source§

fn clone(&self) -> Message

Returns a duplicate 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 Message

Source§

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

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

impl PartialEq for Message

Source§

fn eq(&self, other: &Message) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for 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
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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> ToOwned for T
where T: Clone,

Source§

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>,

Source§

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>,

Source§

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.
Source§

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

Source§

fn vzip(self) -> V