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::try_from(value)
63 }
64}
65
66impl TryFrom<&str> for Thscode {
67 type Error = ValidationError;
68
69 fn try_from(value: &str) -> Result<Self, Self::Error> {
70 Self::new(value)
71 }
72}
73
74impl TryFrom<String> for Thscode {
75 type Error = ValidationError;
76
77 fn try_from(value: String) -> Result<Self, Self::Error> {
78 Self::new(value)
79 }
80}
81
82impl TryFrom<&String> for Thscode {
83 type Error = ValidationError;
84
85 fn try_from(value: &String) -> Result<Self, Self::Error> {
86 Self::new(value)
87 }
88}
89
90impl From<&Thscode> for Thscode {
91 fn from(value: &Thscode) -> Self {
92 value.clone()
93 }
94}
95
96impl AsRef<str> for Thscode {
97 fn as_ref(&self) -> &str {
98 self.as_str()
99 }
100}
101
102impl<'de> Deserialize<'de> for Thscode {
103 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
104 let value = String::deserialize(deserializer)?;
105 Self::new(value).map_err(serde::de::Error::custom)
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, derive_more::Display)]
111#[serde(transparent)]
112pub struct AShareCode(Thscode);
113
114impl AShareCode {
115 pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
116 let code = Thscode::new(value)?;
117 Self::try_from(code)
118 }
119
120 #[must_use]
121 pub fn as_str(&self) -> &str {
122 self.0.as_str()
123 }
124
125 pub(crate) fn into_string(self) -> String {
126 self.0.into_string()
127 }
128}
129
130impl TryFrom<Thscode> for AShareCode {
131 type Error = ValidationError;
132
133 fn try_from(code: Thscode) -> Result<Self, Self::Error> {
134 let (ticker, suffix) = code.ticker_and_suffix();
135 if ticker.len() != 6
136 || !ticker.bytes().all(|byte| byte.is_ascii_digit())
137 || !matches!(suffix, "SH" | "SZ" | "BJ")
138 {
139 return Err(ValidationError::new(
140 "thscode",
141 "must be a six-digit A-share code ending in SH, SZ, or BJ",
142 ));
143 }
144 Ok(Self(code))
145 }
146}
147
148impl FromStr for AShareCode {
149 type Err = ValidationError;
150
151 fn from_str(value: &str) -> Result<Self, Self::Err> {
152 Self::try_from(value)
153 }
154}
155
156impl TryFrom<&str> for AShareCode {
157 type Error = ValidationError;
158
159 fn try_from(value: &str) -> Result<Self, Self::Error> {
160 Self::new(value)
161 }
162}
163
164impl TryFrom<String> for AShareCode {
165 type Error = ValidationError;
166
167 fn try_from(value: String) -> Result<Self, Self::Error> {
168 Self::new(value)
169 }
170}
171
172impl TryFrom<&String> for AShareCode {
173 type Error = ValidationError;
174
175 fn try_from(value: &String) -> Result<Self, Self::Error> {
176 Self::new(value)
177 }
178}
179
180impl From<&AShareCode> for AShareCode {
181 fn from(value: &AShareCode) -> Self {
182 value.clone()
183 }
184}
185
186impl TryFrom<&Thscode> for AShareCode {
187 type Error = ValidationError;
188
189 fn try_from(value: &Thscode) -> Result<Self, Self::Error> {
190 Self::try_from(value.clone())
191 }
192}
193
194impl AsRef<str> for AShareCode {
195 fn as_ref(&self) -> &str {
196 self.as_str()
197 }
198}
199
200impl<'de> Deserialize<'de> for AShareCode {
201 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
202 let value = String::deserialize(deserializer)?;
203 Self::new(value).map_err(serde::de::Error::custom)
204 }
205}
206
207impl From<AShareCode> for Thscode {
208 fn from(value: AShareCode) -> Self {
209 value.0
210 }
211}
212
213impl From<&AShareCode> for Thscode {
214 fn from(value: &AShareCode) -> Self {
215 value.0.clone()
216 }
217}
218
219wire_enum! {
220 pub enum Exchange {
222 Shanghai => "SH",
223 Shenzhen => "SZ",
224 Beijing => "BJ",
225 }
226}
227
228wire_enum! {
229 pub enum AssetType {
231 AShare => "a-share",
232 AShareIndex => "a-share-index",
233 FundOtc => "fund-otc",
234 FundEtf => "fund-etf",
235 FundLof => "fund-lof",
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::{AShareCode, Thscode};
242
243 #[test]
244 fn complete_target_code_is_normalized_and_rejects_tickers() {
245 let code = Thscode::new(" 600519.sh ").unwrap();
246 assert_eq!(code.as_str(), "600519.SH");
247 let error = Thscode::new("600519").unwrap_err();
248 assert_eq!(error.field(), "thscode");
249 assert_eq!(error.problem(), "must include a market suffix");
250 }
251
252 #[test]
253 fn a_share_code_rejects_non_a_share_suffixes() {
254 assert!(AShareCode::new("600519.SH").is_ok());
255 assert!(AShareCode::new("510300.OF").is_err());
256 assert!(AShareCode::new("886042.TI").is_err());
257 }
258
259 #[test]
260 fn target_values_use_standard_fallible_conversions() {
261 let text = "600519.sh".to_owned();
262 let a_share = AShareCode::try_from(&text).unwrap();
263 let target = Thscode::try_from(text).unwrap();
264
265 assert_eq!(target, Thscode::from(a_share));
266 assert!(AShareCode::try_from("510300.OF").is_err());
267 }
268}