1use crate::constant::Exchange;
8use std::fmt;
9use std::str::FromStr;
10
11pub fn vt_symbol(symbol: &str, exchange: Exchange) -> String {
13 let mut buf = String::with_capacity(exchange.as_str().len() + 1 + symbol.len());
14 write_vt_symbol(&mut buf, symbol, exchange);
15 buf
16}
17
18pub fn write_vt_symbol(buf: &mut String, symbol: &str, exchange: Exchange) {
20 buf.push_str(exchange.as_str());
21 buf.push('.');
22 buf.push_str(symbol);
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum SymbolError {
28 Malformed,
30 UnknownExchange(String),
32}
33
34impl fmt::Display for SymbolError {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 match self {
37 Self::Malformed => f.write_str("malformed vt_symbol, expect `<exchange>.<symbol>`"),
38 Self::UnknownExchange(s) => write!(f, "unknown exchange: {s}"),
39 }
40 }
41}
42
43impl std::error::Error for SymbolError {}
44
45pub fn parse_vt_symbol(vt: &str) -> Result<(String, Exchange), SymbolError> {
49 let Some((head, tail)) = vt.split_once('.') else {
50 return Err(SymbolError::Malformed);
51 };
52 if head.is_empty() {
53 return Err(SymbolError::Malformed);
54 }
55 Exchange::from_str(head)
56 .map(|ex| (tail.to_string(), ex))
57 .map_err(|_| SymbolError::UnknownExchange(head.to_string()))
58}