Skip to content

Instantly share code, notes, and snippets.

@thomaslee
Created January 17, 2014 07:34
Show Gist options
  • Save thomaslee/8469692 to your computer and use it in GitHub Desktop.
Save thomaslee/8469692 to your computer and use it in GitHub Desktop.
A crappy, unbounded, half-baked, broken connection pool in Rust
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