use crate::io;
use crate::pool::SharedPool;
use crate::raw::RawConnection;
use anyhow::bail;
use async_std::sync::Arc;
pub struct Connection {
pub(crate) raw: Option<RawConnection>,
pub(crate) pool: Option<Arc<SharedPool>>,
}
impl Connection {
pub async fn open(url: &str) -> crate::Result<Self> {
Ok(Self {
raw: Some(RawConnection::open(url).await?),
pool: None,
})
}
pub async fn get(&mut self, key: &str) -> crate::Result<Option<String>> {
if let Some(raw) = &mut self.raw {
raw.send(&["GET", key]).await?;
let buf = raw.receive().await?;
Ok(io::read_str(&*buf)?)
} else {
bail!("closed connection")
}
}
}
impl Drop for Connection {
fn drop(&mut self) {
if let Some(pool) = &self.pool {
if let Some(raw) = self.raw.take() {
pool.release(raw);
}
}
}
}