financial_api/types/
target.rs1use std::str::FromStr;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use super::wire::wire_enum;
6use crate::ValidationError;
7
8#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
10#[serde(transparent)]
11pub struct Thscode(String);
12
13impl Thscode {
14 pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
15 let value = value.as_ref().trim().to_ascii_uppercase();
16 if value.contains(',') {
17 return Err(ValidationError::new(
18 "thscode",
19 "must contain exactly one target",
20 ));
21 }
22 let Some((ticker, suffix)) = value.split_once('.') else {
23 return Err(ValidationError::new(
24 "thscode",
25 "must include a market suffix",
26 ));
27 };
28 if ticker.is_empty()
29 || suffix.is_empty()
30 || suffix.contains('.')
31 || !ticker.bytes().all(|byte| byte.is_ascii_alphanumeric())
32 || !suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
33 {
34 return Err(ValidationError::new(
35 "thscode",
36 "must use TICKER.SUFFIX with ASCII letters or digits",
37 ));
38 }
39 Ok(Self(value))
40 }
41
42 #[must_use]
43 pub fn as_str(&self) -> &str {
44 &self.0
45 }
46
47 pub(crate) fn into_string(self) -> String {
48 self.0
49 }
50
51 pub(crate) fn ticker_and_suffix(&self) -> (&str, &str) {
52 self.0
53 .split_once('.')
54 .expect("validated thscode always contains a market suffix")
55 }
56}
57
58impl FromStr for Thscode {
59 type Err = ValidationError;
60
61 fn from_str(value: &str) -> Result<Self, Self::Err> {
62 Self::new(value)
63 }
64}
65
66impl AsRef<str> for Thscode {
67 fn as_ref(&self) -> &str {
68 self.as_str()
69 }
70}
71
72impl<'de> Deserialize<'de> for Thscode {
73 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
74 let value = String::deserialize(deserializer)?;
75 Self::new(value).map_err(serde::de::Error::custom)
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
81#[serde(transparent)]
82pub struct AShareCode(Thscode);
83
84impl AShareCode {
85 pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
86 let code = Thscode::new(value)?;
87 let (ticker, suffix) = code.ticker_and_suffix();
88 if ticker.len() != 6
89 || !ticker.bytes().all(|byte| byte.is_ascii_digit())
90 || !matches!(suffix, "SH" | "SZ" | "BJ")
91 {
92 return Err(ValidationError::new(
93 "thscode",
94 "must be a six-digit A-share code ending in SH, SZ, or BJ",
95 ));
96 }
97 Ok(Self(code))
98 }
99
100 #[must_use]
101 pub fn as_str(&self) -> &str {
102 self.0.as_str()
103 }
104
105 pub(crate) fn into_string(self) -> String {
106 self.0.into_string()
107 }
108}
109
110impl FromStr for AShareCode {
111 type Err = ValidationError;
112
113 fn from_str(value: &str) -> Result<Self, Self::Err> {
114 Self::new(value)
115 }
116}
117
118impl AsRef<str> for AShareCode {
119 fn as_ref(&self) -> &str {
120 self.as_str()
121 }
122}
123
124impl<'de> Deserialize<'de> for AShareCode {
125 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
126 let value = String::deserialize(deserializer)?;
127 Self::new(value).map_err(serde::de::Error::custom)
128 }
129}
130
131impl From<AShareCode> for Thscode {
132 fn from(value: AShareCode) -> Self {
133 value.0
134 }
135}
136
137wire_enum! {
138 pub enum Exchange {
140 Shanghai => "SH",
141 Shenzhen => "SZ",
142 Beijing => "BJ",
143 }
144}
145
146wire_enum! {
147 pub enum AssetType {
149 AShare => "a-share",
150 AShareIndex => "a-share-index",
151 FundOtc => "fund-otc",
152 FundEtf => "fund-etf",
153 FundLof => "fund-lof",
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::{AShareCode, Thscode};
160
161 #[test]
162 fn complete_target_code_is_normalized_and_rejects_tickers() {
163 let code = Thscode::new(" 600519.sh ").unwrap();
164 assert_eq!(code.as_str(), "600519.SH");
165 let error = Thscode::new("600519").unwrap_err();
166 assert_eq!(error.field(), "thscode");
167 assert_eq!(error.problem(), "must include a market suffix");
168 }
169
170 #[test]
171 fn a_share_code_rejects_non_a_share_suffixes() {
172 assert!(AShareCode::new("600519.SH").is_ok());
173 assert!(AShareCode::new("510300.OF").is_err());
174 assert!(AShareCode::new("886042.TI").is_err());
175 }
176
177 #[test]
178 fn target_values_use_standard_fallible_conversions() {
179 let target: Thscode = "600519.sh".parse().unwrap();
180 let a_share: AShareCode = "600519.sh".parse().unwrap();
181
182 assert_eq!(target, a_share.into());
183 assert!("510300.OF".parse::<AShareCode>().is_err());
184 }
185}