mycelium_command 0.1.1

Library for Mycelium DDM
Documentation
use chrono::prelude::*;
use serde::Serialize;

use std::cmp::Ordering;
use std::mem::size_of_val;
use uuid::Uuid;

///
/// # Node
/// Container used within Mycelium to store/transport packets of data.
///
/// key: StewId of this item.
///
/// value: Byte[] of original data associated with [u8; 16].
///
/// size: Estimated size of node.
///
/// timestamp: When this version of this node was created.
///
#[derive(Clone, Debug, Deserialize, Serialize)]
#[repr(C)]
pub struct Node {
    key: [u8; 16],
    value: Vec<u8>,
    item_modified: DateTime<Utc>,
    item_revision: usize,
    originator: [u8; 16],
    size: usize,
}

impl Node {
    pub fn new(originator: [u8; 16], item: &[u8]) -> Node {
        let id = Uuid::new_v4();

        let node = Node {
            key: *id.as_bytes(),
            value: item.to_vec(),
            item_modified: Utc::now(),
            item_revision: 0,
            originator,
            size: 0,
        };

        let size = size_of_val(&node);
        node.set_size(size)
    }

    pub fn create_update_node(&self, update_item: &[u8]) -> Node {
        let mut new = Node {
            key: self.key,
            value: update_item.to_vec(),
            item_modified: Utc::now(),
            item_revision: self.item_revision + 1,
            originator: self.originator,
            size: 0,
        };

        let size = size_of_val(&new);
        new = new.set_size(size);
        new
    }

    pub fn get_id(&self) -> [u8; 16] {
        self.key
    }

    pub fn get_item(&self) -> Vec<u8> {
        self.value.clone()
    }

    pub fn get_revision(&self) -> usize {
        self.item_revision
    }

    pub fn get_size(&self) -> usize {
        self.size
    }

    fn set_size(mut self, size: usize) -> Self {
        self.size = size;
        self
    }

    #[allow(clippy::clone_on_copy)]
    pub fn get_timestamp(&self) -> DateTime<Utc> {
        self.item_modified.clone()
    }
}

impl Default for Node {
    fn default() -> Node {
        Node {
            key: *Uuid::new_v4().as_bytes(),
            value: vec![],
            item_modified: Utc::now(),
            item_revision: 0,
            originator: [0; 16],
            size: 0,
        }
    }
}

impl Eq for Node {}

impl PartialEq for Node {
    fn eq(&self, other: &Node) -> bool {
        self.key == other.key && self.item_modified == other.item_modified
    }
}

impl PartialOrd for Node {
    fn partial_cmp(&self, other: &Node) -> Option<Ordering> {
        self.item_modified.partial_cmp(&other.item_modified)
    }
}

impl Ord for Node {
    fn cmp(&self, other: &Self) -> Ordering {
        self.key.cmp(&other.key)
    }
}