You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
120 lines
2.4 KiB
120 lines
2.4 KiB
//! 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())
|
|
}
|
|
}
|
|
}
|
|
|