collab-common 0.0.7

Code shared by collab's client and server
Documentation
use serde::{Deserialize, Serialize};

use crate::encode::ShouldCompress;
use crate::{
    CursorMoved,
    Deletion,
    FileCreated,
    FileDeleted,
    FileMoved,
    Insertion,
    PeerId,
    PeerLeft,
    SessionResponse,
};

/// TODO: docs
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ClientMessage {
    /// A peer moved their cursor.
    CursorMoved(CursorMoved),

    /// TODO: docs
    Deletion(Deletion),

    /// TODO: docs
    FileCreated(FileCreated),

    /// TODO: docs
    FileDeleted(FileDeleted),

    /// TODO: docs
    FileMoved(FileMoved),

    /// TODO: docs
    Insertion(Insertion),

    /// TODO: docs
    PeerLeft(PeerLeft),

    /// TODO: docs
    SessionResponse(SessionResponse),

    /// TODO: docs
    #[cfg(feature = "__tests")]
    Ping(PeerId),
}

impl ClientMessage {
    /// Returns the [`PeerId`] of the peer that sent this message.
    #[inline]
    pub fn sent_by(&self) -> PeerId {
        match self {
            Self::CursorMoved(cursor_moved) => cursor_moved.cursor().owner(),
            Self::Deletion(deletion) => deletion.deleted_by(),
            Self::FileCreated(file_created) => file_created.created_by(),
            Self::FileDeleted(file_deleted) => file_deleted.deleted_by(),
            Self::FileMoved(file_moved) => file_moved.moved_by(),
            Self::Insertion(insertion) => insertion.inserted_by(),
            Self::PeerLeft(peer_left) => peer_left.peer_id(),
            Self::SessionResponse(response) => response.sent_by(),
            #[cfg(feature = "__tests")]
            Self::Ping(sent_by) => *sent_by,
        }
    }
}

impl ShouldCompress for ClientMessage {
    #[inline]
    fn should_compress(&self) -> bool {
        match self {
            Self::SessionResponse(response) => response.should_compress(),
            Self::Insertion(insertion) => insertion.should_compress(),
            _ => false,
        }
    }
}

impl From<PeerLeft> for ClientMessage {
    #[inline]
    fn from(peer_left: PeerLeft) -> Self {
        Self::PeerLeft(peer_left)
    }
}

impl AsRef<ClientMessage> for ClientMessage {
    #[inline]
    fn as_ref(&self) -> &Self {
        self
    }
}