naia_client_socket/backends/native/
identity_receiver.rs

1use std::sync::{Arc, Mutex};
2
3use tokio::sync::oneshot;
4
5use crate::{identity_receiver::IdentityReceiver, IdentityReceiverResult};
6
7/// Handles receiving an IdentityToken from the Server through a given Client Socket
8#[derive(Clone)]
9pub struct IdentityReceiverImpl {
10    receiver_channel: Arc<Mutex<oneshot::Receiver<Result<String, u16>>>>,
11}
12
13impl IdentityReceiverImpl {
14    /// Create a new IdentityReceiver, if supplied with the Server's address & a
15    /// reference back to the parent Socket
16    pub fn new(receiver_channel: oneshot::Receiver<Result<String, u16>>) -> Self {
17        Self {
18            receiver_channel: Arc::new(Mutex::new(receiver_channel)),
19        }
20    }
21}
22
23impl IdentityReceiver for IdentityReceiverImpl {
24    fn receive(&mut self) -> IdentityReceiverResult {
25        if let Ok(mut receiver) = self.receiver_channel.lock() {
26            if let Ok(recv_result) = receiver.try_recv() {
27                match recv_result {
28                    Ok(identity_token) => IdentityReceiverResult::Success(identity_token),
29                    Err(error_code) => IdentityReceiverResult::ErrorResponseCode(error_code),
30                }
31            } else {
32                IdentityReceiverResult::Waiting
33            }
34        } else {
35            IdentityReceiverResult::Waiting
36        }
37    }
38}