initial commit

old-dual
Avril 4 years ago
commit d418cf876b
Signed by: flanchan
GPG Key ID: 284488987C31F630

2
.gitignore vendored

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

@ -0,0 +1,10 @@
[package]
name = "encrypted-network"
version = "0.1.0"
authors = ["Avril <flanchan@cumallover.me>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
chacha20stream = {version = "1.0", features=["async"]}

@ -0,0 +1,119 @@
//! Container for switching between un/encrypted stream
use super::*;
use std::mem::{self, MaybeUninit, ManuallyDrop};
use std::ops::{Drop, Deref, DerefMut};
use std::ptr;
use std::fmt;
use chacha20stream::AsyncSink;
#[derive(Debug)]
pub enum DualStreamKind<S>
{
Encrypted(AsyncSink<S>),
Plain(S),
}
pub struct DualStream<S>(MaybeUninit<Box<DualStreamKind<S>>>);
impl<S: fmt::Debug> fmt::Debug for DualStream<S>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
fmt::Debug::fmt(self.as_ref(), f)
}
}
impl<S> DualStream<S>
{
fn as_mut_ref(&mut self) -> &mut Box<DualStreamKind<S>>
{
// SAFETY: It is always initialised except exactly within the swap function
unsafe {
&mut *self.0.as_mut_ptr()
}
}
fn as_ref(&self) -> &Box<DualStreamKind<S>>
{
// SAFETY: It is always initialised except exactly within the swap function
unsafe {
&*self.0.as_ptr()
}
}
pub fn
/// Create explicit
pub fn new(k: DualStreamKind<S>) -> Self
{
Self(MaybeUninit::new(Box::new(k)))
}
/// Consume into explicit (non-swappable) dual stream
pub fn into_inner(self) -> Box<DualStreamKind<S>>
{
let mut md = ManuallyDrop::new(self);
unsafe {
// We could just `read()` the pointer, but this is more semantiacally equivalent to moving the value, I think. Idk if it's more or less efficient or whatever.
mem::replace(&mut md.0, MaybeUninit::uninit()).assume_init()
}
}
}
impl<S> Deref for DualStream<S>
{
type Target = DualStreamKind<S>;
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl<S> DerefMut for DualStream<S>
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut_ref()
}
}
impl<S> From<Box<DualStreamKind<S>>> for DualStream<S>
{
fn from(from: Box<DualStreamKind<S>>) -> Self
{
Self(MaybeUninit::new(from))
}
}
impl<S> From<DualStreamKind<S>> for DualStream<S>
{
fn from(from: DualStreamKind<S>) -> Self
{
Self::new(from)
}
}
impl<S> From<DualStream<S>> for Box<DualStreamKind<S>>
{
fn from(from: DualStream<S>) -> Self
{
from.into_inner()
}
}
impl<S> From<DualStream<S>> for DualStreamKind<S>
{
fn from(from: DualStream<S>) -> Self
{
*from.into_inner()
}
}
impl<S> Drop for DualStream<S>
{
fn drop(&mut self) {
// SAFETY: Value is always initialised except exactly within swap function
unsafe {
ptr::drop_in_place(self.0.as_mut_ptr())
}
}
}

@ -0,0 +1,4 @@
#![allow(dead_code)]
mod dual;
Loading…
Cancel
Save