use crate::constant::Exchange;
use std::fmt;
use std::str::FromStr;
pub fn vt_symbol(symbol: &str, exchange: Exchange) -> String {
let mut buf = String::with_capacity(exchange.as_str().len() + 1 + symbol.len());
write_vt_symbol(&mut buf, symbol, exchange);
buf
}
pub fn write_vt_symbol(buf: &mut String, symbol: &str, exchange: Exchange) {
buf.push_str(exchange.as_str());
buf.push('.');
buf.push_str(symbol);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SymbolError {
Malformed,
UnknownExchange(String),
}
impl fmt::Display for SymbolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed => f.write_str("malformed vt_symbol, expect `<exchange>.<symbol>`"),
Self::UnknownExchange(s) => write!(f, "unknown exchange: {s}"),
}
}
}
impl std::error::Error for SymbolError {}
pub fn parse_vt_symbol(vt: &str) -> Result<(String, Exchange), SymbolError> {
let Some((head, tail)) = vt.split_once('.') else {
return Err(SymbolError::Malformed);
};
if head.is_empty() {
return Err(SymbolError::Malformed);
}
Exchange::from_str(head)
.map(|ex| (tail.to_string(), ex))
.map_err(|_| SymbolError::UnknownExchange(head.to_string()))
}