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