Browse Source

initial commit

master
Isabelle L. 5 years ago
commit
0af49f6a2e
6 changed files with 156 additions and 0 deletions
  1. +2
    -0
      .gitignore
  2. +14
    -0
      Cargo.toml
  3. +7
    -0
      LICENSE
  4. +2
    -0
      README.md
  5. +91
    -0
      src/lib.rs
  6. +40
    -0
      src/message.rs

+ 2
- 0
.gitignore View File

@@ -0,0 +1,2 @@
/target
Cargo.lock

+ 14
- 0
Cargo.toml View File

@@ -0,0 +1,14 @@
[package]
name = "ilmp"
version = "0.1.0"
authors = ["Isabelle L. <me@izzabelle.dev>"]
edition = "2018"

[dependencies]
orion = "0.15.1"
serde = { version = "1.0.110", features = ["derive"]}
serde_json = "1.0.53"
futures = "0.3.5"
futures-util = "0.3.5"
uuid = { version = "0.8.1", features = ["v4"] }
chrono = "0.4.11"

+ 7
- 0
LICENSE View File

@@ -0,0 +1,7 @@
Copyright 2020 Isabelle L.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CO

+ 2
- 0
README.md View File

@@ -0,0 +1,2 @@
# Isabelle's Lazy Message Protocol
idfk lol

+ 91
- 0
src/lib.rs View File

@@ -0,0 +1,91 @@
#![allow(dead_code)]

use futures_util::io::{AsyncReadExt, AsyncWriteExt};
use std::convert::TryInto;
use std::marker::Unpin;

mod message;
pub use message::Message;

/// lazy error
pub type Error = Box<dyn std::error::Error>;
/// lazy result
pub type Result<T> = std::result::Result<T, Error>;

struct NetworkPacket(Vec<u8>);

pub trait Sendable: Sized {
fn to_packet(self) -> Result<Packet>;
fn from_packet(packet: Packet) -> Result<Self>;
}

pub struct Packet {
kind: PacketKind,
contents: Vec<u8>,
}

impl Packet {
pub fn new(kind: PacketKind, contents: Vec<u8>) -> Packet {
Packet { kind, contents }
}

fn to_network_packet(self) -> NetworkPacket {
let mut contents: Vec<u8> = Vec::new();

// write packet kind byte
contents.push(self.kind as u8);
// write the packet length
let contents_length = self.contents.len() as u32;
contents.extend_from_slice(&contents_length.to_le_bytes());
// write contents
contents.extend_from_slice(&self.contents);

NetworkPacket(contents)
}
}

pub async fn read<S>(stream: &mut S) -> Result<Option<Packet>>
where
S: AsyncReadExt + Unpin,
{
let mut info_buf = [0u8; 5];
let check = stream.read(&mut info_buf).await?;
if check == 0 {
return Ok(None);
}

let packet_kind = PacketKind::from_u8(info_buf[0]).unwrap();
let length = u32::from_le_bytes(info_buf[1..5].try_into().unwrap()) as usize;

let mut contents: Vec<u8> = vec![0; length];
stream.read(&mut contents).await?;

let packet = Packet::new(packet_kind, contents);

Ok(Some(packet))
}

pub async fn write<S, P>(stream: &mut S, packet: P) -> Result<()>
where
S: AsyncWriteExt + Unpin,
P: Sendable,
{
let network_packet = packet.to_packet()?.to_network_packet();
stream.write(&network_packet.0).await?;
Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PacketKind {
Message = 0,
}

impl PacketKind {
pub fn from_u8(kind: u8) -> Option<PacketKind> {
match kind {
0 => Some(PacketKind::Message),
_ => None,
}
}
}

+ 40
- 0
src/message.rs View File

@@ -0,0 +1,40 @@
use crate::{Packet, PacketKind, Result};
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub timestamp: i64,
pub message_id: u128,
pub username: String,
pub contents: String,
}

impl Message {
pub fn new(username: String, contents: String) -> Message {
let timestamp = Utc::now().timestamp();
let message_id = Uuid::new_v4().as_u128();

Message {
username,
message_id,
timestamp,
contents,
}
}
}

impl crate::Sendable for Message {
fn to_packet(self) -> Result<Packet> {
let contents: Vec<u8> = serde_json::to_string(&self)?.into_bytes();
let kind = PacketKind::Message;

Ok(Packet { kind, contents })
}
fn from_packet(packet: Packet) -> Result<Self> {
let contents = &String::from_utf8(packet.contents)?;
let message: Message = serde_json::from_str(contents)?;
Ok(message)
}
}

Loading…
Cancel
Save