use std::ptr;
use std::net::SocketAddr;
use std::io::Result as IOResult;
use std::ops::{Deref, DerefMut};
use std::cell::{Ref, RefMut, RefCell};
use std::sync::{Arc, atomic::{AtomicPtr, Ordering}};
use futures::future::{FutureExt, LocalBoxFuture};
use dashmap::DashMap;
use parking_lot::RwLock;
use crossbeam_channel::Sender;
use async_channel::Sender as AsyncSender;
use pi_hash::XHashMap;
use crate::{Socket, SocketHandle};
pub enum UdpMultiInterface {
V4(SocketAddr),
V6(u32),
}
#[derive(Debug)]
pub enum UdpSocketStatus {
SingleCast(Option<SocketAddr>), MultiCast(Arc<DashMap<SocketAddr, ()>>), BroadCast, }
impl Clone for UdpSocketStatus {
fn clone(&self) -> Self {
match self {
UdpSocketStatus::SingleCast(address) => UdpSocketStatus::SingleCast(address.clone()),
UdpSocketStatus::MultiCast(map) => UdpSocketStatus::MultiCast(map.clone()),
UdpSocketStatus::BroadCast => UdpSocketStatus::BroadCast,
}
}
}
impl UdpSocketStatus {
pub fn is_singlecast(&self) -> bool {
if let UdpSocketStatus::SingleCast(_) = self {
true
} else {
false
}
}
pub fn is_multicast(&self) -> bool {
if let UdpSocketStatus::MultiCast(_) = self {
true
} else {
false
}
}
pub fn is_broadcast(&self) -> bool {
if let UdpSocketStatus::BroadCast = self {
true
} else {
false
}
}
pub fn insert_multicast(&self, address: SocketAddr) {
if let UdpSocketStatus::MultiCast(map) = self {
map.insert(address, ());
}
}
pub fn remove_multicast(&self, address: &SocketAddr) -> usize {
if let UdpSocketStatus::MultiCast(map) = self {
let _ = map.remove(address);
return map.len();
}
0
}
}
pub struct SocketContext {
inner: AtomicPtr<()>, }
unsafe impl Send for SocketContext {}
impl SocketContext {
pub fn empty() -> Self {
SocketContext {
inner: AtomicPtr::new(ptr::null_mut()),
}
}
pub fn is_empty(&self) -> bool {
self
.inner
.load(Ordering::Acquire)
.is_null()
}
pub fn get<T>(&self) -> Option<ContextHandle<T>> {
if self.is_empty() {
return None;
}
Some(unsafe { ContextHandle(Some(Arc::from_raw(self.inner.load(Ordering::Acquire) as *const T))) })
}
pub fn set<T>(&self, context: T) -> bool {
if !self.is_empty() {
return false;
}
self.inner.store(Arc::into_raw(Arc::new(context)) as *mut T as *mut (),
Ordering::Release);
true
}
pub fn remove<T>(&self) -> Result<Option<T>, &str> {
if self.is_empty() {
return Ok(None);
}
let inner = unsafe { Arc::from_raw(self.inner.load(Ordering::Acquire) as *const T) };
if Arc::strong_count(&inner) > 1 {
Arc::into_raw(inner); Err("Remove context failed, reason: context shared exist")
} else {
match Arc::try_unwrap(inner) {
Err(inner) => {
Arc::into_raw(inner); Err("Remove context failed, reason: invalid shared")
},
Ok(context) => {
self.inner.store(ptr::null_mut(), Ordering::Release);
Ok(Some(context))
},
}
}
}
}
pub struct ContextHandle<T: 'static>(Option<Arc<T>>);
unsafe impl<T: 'static> Send for ContextHandle<T> {}
impl<T: 'static> Drop for ContextHandle<T> {
fn drop(&mut self) {
if let Some(shared) = self.0.take() {
Arc::into_raw(shared);
}
}
}
impl<T: 'static> ContextHandle<T> {
pub fn as_ref(&self) -> &T {
self.0.as_ref().unwrap().as_ref()
}
pub fn as_mut(&mut self) -> Option<&mut T> {
if let Some(shared) = self.0.as_mut() {
return Arc::get_mut(shared);
}
None
}
}
pub struct SharedSocket<S: Socket>(Arc<RefCell<S>>);
unsafe impl<S: Socket> Send for SharedSocket<S> {}
impl<S: Socket> Clone for SharedSocket<S> {
fn clone(&self) -> Self {
SharedSocket(self.0.clone())
}
}
impl<S: Socket> SharedSocket<S> {
pub fn new(s: S) -> Self {
SharedSocket(Arc::new(RefCell::new(s)))
}
pub fn with_inner(inner: &Arc<RefCell<S>>) -> Self {
SharedSocket(inner.clone())
}
pub fn inner_ref(&self) -> &Arc<RefCell<S>> {
&self.0
}
#[inline]
pub fn borrow<'a>(&'a self) -> SharedRef<'a, S> {
SharedRef(self.0.borrow())
}
#[inline]
pub fn borrow_mut<'a>(&'a self) -> SharedRefMut<'a, S> {
SharedRefMut(self.0.borrow_mut())
}
#[inline]
pub fn as_ptr(&self) -> *mut S {
self.0.as_ptr()
}
}
pub struct SharedRef<'a, S: Socket>(Ref<'a, S>);
unsafe impl<'a, S: Socket> Send for SharedRef<'a, S> {}
impl<'a, S: Socket> Deref for SharedRef<'a, S> {
type Target = S;
#[inline]
fn deref(&self) -> &Self::Target {
&*self.0
}
}
pub struct SharedRefMut<'a, S: Socket>(RefMut<'a, S>);
unsafe impl<'a, S: Socket> Send for SharedRefMut<'a, S> {}
impl<'a, S: Socket> Deref for SharedRefMut<'a, S> {
type Target = S;
#[inline]
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl<'a, S: Socket> DerefMut for SharedRefMut<'a, S> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.0
}
}