circe/src/lib.rs

84 lines
1.8 KiB
Rust

use lazy_static::lazy_static;
use regex::Regex;
use std::io::{Error, Read, Write};
use std::net::TcpStream;
use std::time::Duration;
lazy_static! {
static ref PING_RE: Regex = Regex::new(r"^PING\s*:").unwrap();
}
pub struct Client {
stream: TcpStream,
config: Config,
}
pub struct Config {
username: String,
nickname: String,
mode: String,
}
pub enum Command {
PING(String),
}
impl Command {
fn from_str(s: &str) -> Option<Self> {
let new = s.trim();
if new.contains("PING") {
let command = String::from(PING_RE.replace_all(new, ""));
return Some(Self::PING(command));
}
None
}
}
impl Client {
pub fn new(host: &str, port: u16, config: Config) -> Result<Self, Error> {
let stream = TcpStream::connect(format!("{}:{}", host, port))?;
Ok(Self { stream, config })
}
// temporarily pub, change this later
pub fn read_string(&mut self) -> Option<String> {
let mut buffer = [0u8; 512];
match self.stream.read(&mut buffer) {
Ok(_) => {}
Err(_) => return None,
};
Some(String::from_utf8_lossy(&buffer).into())
}
pub fn read(&mut self) -> Option<Command> {
if let Some(string) = self.read_string() {
return Command::from_str(&string);
}
None // if it's none, there's no new messages
}
pub fn write(&mut self, data: &str) -> Result<(), Error> {
self.stream.write_all(data.as_bytes())?;
// self.stream.flush()?;
Ok(())
}
}
impl Config {
pub fn new(username: &str, nickname: Option<&str>, mode: Option<&str>) -> Self {
Self {
username: username.into(),
nickname: nickname.unwrap_or(username).into(),
mode: mode.unwrap_or("").into(),
}
}
}