Created
January 17, 2014 07:34
-
-
Save thomaslee/8469692 to your computer and use it in GitHub Desktop.
A crappy, unbounded, half-baked, broken connection pool in Rust
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::clone::Clone; | |
use std::option::{Option, None, Some}; | |
use std::io::net::ip::{SocketAddr, IpAddr}; | |
use std::io::net::tcp::TcpStream; | |
use std::io::net::addrinfo::get_host_addresses; | |
use std::rc::Rc; | |
pub struct Connection { | |
addr: SocketAddr, | |
conn: Rc<TcpStream> | |
} | |
impl Clone for Connection { | |
fn clone(&self) -> Connection { | |
Connection { addr: self.addr, conn: self.conn.clone() } | |
} | |
} | |
pub struct ConnectionPool { | |
idle: ~[Connection], | |
} | |
impl ConnectionPool { | |
pub fn new() -> ConnectionPool { | |
ConnectionPool { idle: ~[] } | |
} | |
pub fn acquire(&mut self, host: &str, port: u16) -> Option<Connection> { | |
if self.idle.len() > 0 { | |
Some(self.idle.pop()) | |
} | |
else { | |
match get_host_addresses(host) { | |
Some(addrs) => self.connect_any(addrs, port), | |
None => None | |
} | |
} | |
} | |
pub fn release(&mut self, conn: Connection) { | |
self.idle.push(conn) | |
} | |
fn connect_any(&mut self, addrs: &[IpAddr], port: u16) -> Option<Connection> { | |
for ip in addrs.iter() { | |
let sock_addr = SocketAddr { | |
ip: *ip, | |
port: port | |
}; | |
match TcpStream::connect(sock_addr) { | |
Some(conn) => | |
return Some(Connection { | |
addr: sock_addr, | |
conn: Rc::new(conn) | |
}), | |
_ => continue | |
} | |
} | |
return None | |
} | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn test_connect() { | |
let mut pool = ConnectionPool::new(); | |
let opt_conn = pool.acquire("tomlee.co", 80); | |
match opt_conn { | |
Some(conn) => pool.release(conn), | |
None => fail!("failed to connect") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment