ServerId

Struct ServerId 

Source
pub struct ServerId<T>
where T: Into<String> + Send,
{ /* private fields */ }
Expand description

Cross-platform representation of an IPC connection path.

Calling IntoIpcPath::into_ipc_path on this struct will generate a platform-specific IPC path.

Windows: \\.\pipe\{serverId}

Mac: $TMPDIR/{serverId}.sock

Linux: $XDG_RUNTIME_DIR/{serverId}.sock (defaults to $TMPDIR if it doesn’t exist)

The value for serverId can contain forward slashes, which will be interpreted as part of the path. On Windows, these will be converted to backslashes.

§Example

use std::env;

use tipsy::{IntoIpcPath, ServerId};

// Forcing these environment variables to ensure consistent results.
// You probably don't want to do this in your application.
unsafe {
    env::set_var("XDG_RUNTIME_DIR", "/tmp");
    env::set_var("TMPDIR", "/tmp");
}

let server_id = ServerId::new("some/id");
let path = server_id.into_ipc_path().unwrap();
let path = path.to_string_lossy();

if cfg!(windows) {
    assert_eq!(r"\\.\pipe\some\id", path);
} else {
    assert_eq!("/tmp/some/id.sock", path);
}

Implementations§

Source§

impl<T> ServerId<T>
where T: Into<String> + Send,

Source

pub fn new(id: T) -> Self

Creates a new ServerId.

Examples found in repository?
examples/client.rs (line 10)
5async fn main() {
6    let path = std::env::args()
7        .nth(1)
8        .expect("Run it with server path to connect as argument");
9
10    let mut client = Endpoint::connect(ServerId::new(path))
11        .await
12        .expect("Failed to connect client.");
13
14    loop {
15        let mut buf = [0u8; 4];
16        println!("SEND: PING");
17        client
18            .write_all(b"ping")
19            .await
20            .expect("Unable to write message to client");
21        client
22            .read_exact(&mut buf[..])
23            .await
24            .expect("Unable to read buffer");
25        if let Ok("pong") = std::str::from_utf8(&buf[..]) {
26            println!("RECEIVED: PONG");
27        } else {
28            break;
29        }
30
31        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
32    }
33}
More examples
Hide additional examples
examples/server.rs (line 6)
5async fn run_server(path: String) {
6    let endpoint = Endpoint::new(ServerId::new(path), OnConflict::Overwrite).unwrap();
7
8    let incoming = endpoint.incoming().expect("failed to open new socket");
9    futures_util::pin_mut!(incoming);
10
11    while let Some(result) = incoming.next().await {
12        match result {
13            Ok(stream) => {
14                let (mut reader, mut writer) = split(stream);
15
16                tokio::spawn(async move {
17                    loop {
18                        let mut buf = [0u8; 4];
19
20                        if reader.read_exact(&mut buf).await.is_err() {
21                            println!("Closing socket");
22                            break;
23                        }
24                        if let Ok("ping") = std::str::from_utf8(&buf[..]) {
25                            println!("RECEIVED: PING");
26                            writer
27                                .write_all(b"pong")
28                                .await
29                                .expect("unable to write to socket");
30                            println!("SEND: PONG");
31                        }
32                    }
33                });
34            }
35            _ => unreachable!("ideally"),
36        }
37    }
38}
Source

pub fn parent_folder<P>(self, folder: P) -> Self
where P: Into<PathBuf>,

Explicitly sets the parent folder for the socket instead of relying on the default OS-specific behavior. This only has an effect on Unix systems.

§Example
use tipsy::{IntoIpcPath, ServerId};

let server_id = ServerId::new("myid").parent_folder("/home");
let path = server_id.into_ipc_path().unwrap();
let path = path.to_string_lossy();

if cfg!(windows) {
    assert_eq!(r"\\.\pipe\myid", path);
} else {
    assert_eq!("/home/myid.sock", path);
}

Trait Implementations§

Source§

impl<T> Clone for ServerId<T>
where T: Into<String> + Send + Clone,

Source§

fn clone(&self) -> ServerId<T>

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<T> Debug for ServerId<T>
where T: Into<String> + Send + Debug,

Source§

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

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

impl<T> IntoIpcPath for ServerId<T>
where T: Into<String> + Send,

Source§

fn into_ipc_path(self) -> Result<PathBuf>

Converts the object into an IPC path.
Source§

impl<T> PartialEq for ServerId<T>
where T: Into<String> + Send + PartialEq,

Source§

fn eq(&self, other: &ServerId<T>) -> 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<T> Eq for ServerId<T>
where T: Into<String> + Send + Eq,

Source§

impl<T> StructuralPartialEq for ServerId<T>
where T: Into<String> + Send,

Auto Trait Implementations§

§

impl<T> Freeze for ServerId<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for ServerId<T>
where T: RefUnwindSafe,

§

impl<T> Send for ServerId<T>

§

impl<T> Sync for ServerId<T>
where T: Sync,

§

impl<T> Unpin for ServerId<T>
where T: Unpin,

§

impl<T> UnwindSafe for ServerId<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> 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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> 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<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more