Created
August 19, 2019 00:13
-
-
Save cfsamson/3439f5af201d2c25b4253e67b871277d to your computer and use it in GitHub Desktop.
Ide on how to handle IOCP <-> kqueue abstraction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
use std::sync::{Arc, Mutex}; | |
fn main() { | |
let mut stream = TcpStream::new(1); | |
let mut poll = Poll::new(); | |
poll.register(&stream); | |
thread::spawn(move || { | |
poll.poll(); | |
}); | |
println!("{:?}", stream); | |
} | |
struct Poll { | |
registry: Registry, | |
buffers: Arena<usize, Arc<Mutex<Vec<u8>>>>, | |
} | |
struct Registry { | |
selector: Selector, | |
} | |
struct Selector { | |
} | |
#[derive(Debug)] | |
struct TcpStream { | |
id: usize, | |
buffer: Arc<Mutex<Vec<u8>>>, | |
} | |
impl Poll { | |
fn new() -> Self { | |
Poll { | |
registry: Registry::new(), | |
buffers: Arena::new(64), | |
} | |
} | |
fn register(&mut self, stream: &TcpStream) { | |
self.buffers.push(stream.id, stream.buffer.clone()); | |
} | |
fn poll(&mut self) { | |
let b = &self.buffers.steal(1).unwrap(); | |
let mut b = b.lock().unwrap(); | |
for i in 1..=10 { | |
b.push(i); | |
} | |
} | |
} | |
impl Registry { | |
fn new() -> Self { | |
Registry { | |
selector: Selector::new(), | |
} | |
} | |
} | |
impl Selector { | |
fn new() -> Self { | |
Selector {} | |
} | |
} | |
impl TcpStream { | |
fn new(id: usize) -> TcpStream { | |
TcpStream { | |
buffer: Arc::new(Mutex::new(Vec::with_capacity(64))), | |
id, | |
} | |
} | |
} | |
#[derive(Debug)] | |
struct Arena<T, U> { | |
inner: Vec<Option<(T, U)>>, | |
cap: usize, | |
} | |
impl<T, U> Arena<T, U> { | |
fn new(cap: usize) -> Self { | |
Arena { | |
inner: (0..cap).map(|_| None).collect(), | |
cap, | |
} | |
} | |
fn push(&mut self, id: T, val: U) { | |
let avail = self.inner.iter_mut().find(|i| i.is_none()).expect("Arena full"); | |
*avail = Some((id, val)); | |
} | |
fn steal(&mut self, id: T) -> Option<U> | |
where T: PartialEq | |
{ | |
for i in &mut self.inner { | |
if let Some((found_id, _)) = i { | |
if *found_id == id { | |
let (_, item) = i.take().unwrap(); | |
return Some(item) | |
} | |
} | |
} | |
None | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment