1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! Traits for Tushare API data conversion
//!
//! This module contains traits that define how to convert Tushare API response data
//! into Rust structs. The main trait is `FromTushareData` which can be implemented
//! manually or automatically using the derive macro from `tushare-derive`.
use crateTushareError;
use crate;
use Value;
/// Trait for converting individual JSON values to custom types
///
/// This trait allows users to define how to convert a single JSON value
/// from Tushare API responses into their custom types. It's designed to
/// work with the procedural macro system for automatic field conversion.
///
/// # Example
///
/// ```rust
/// use tushare_api::{FromTushareValue, TushareError};
/// use serde_json::Value;
///
/// // Custom type example
/// #[derive(Debug, Clone, PartialEq)]
/// struct CustomDecimal(f64);
///
/// impl std::str::FromStr for CustomDecimal {
/// type Err = std::num::ParseFloatError;
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// s.parse::<f64>().map(CustomDecimal)
/// }
/// }
///
/// impl FromTushareValue for CustomDecimal {
/// fn from_tushare_value(value: &Value) -> Result<Self, TushareError> {
/// match value {
/// Value::String(s) => s.parse().map_err(|e| {
/// TushareError::ParseError(format!("Failed to parse decimal: {}", e))
/// }),
/// Value::Number(n) => {
/// if let Some(f) = n.as_f64() {
/// Ok(CustomDecimal(f))
/// } else {
/// Err(TushareError::ParseError("Invalid number format".to_string()))
/// }
/// }
/// _ => Err(TushareError::ParseError("Value is not a valid decimal".to_string()))
/// }
/// }
/// }
/// ```
// Note: Basic Rust type implementations have been moved to src/basic_types.rs
// This includes implementations for: String, f64, f32, i64, i32, i16, i8, u64, u32, u16, u8, usize, isize, bool
/// Trait for converting optional JSON values to custom types
///
/// This trait handles the conversion of potentially null or missing JSON values
/// to optional custom types. It's designed to work with the procedural macro
/// system for automatic optional field conversion.
///
/// # Example
///
/// ```rust
/// use tushare_api::{FromTushareValue, FromOptionalTushareValue, TushareError};
/// use serde_json::Value;
///
/// // Custom type example (same as above)
/// #[derive(Debug, Clone, PartialEq)]
/// struct CustomDecimal(f64);
///
/// impl std::str::FromStr for CustomDecimal {
/// type Err = std::num::ParseFloatError;
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// s.parse::<f64>().map(CustomDecimal)
/// }
/// }
///
/// impl FromTushareValue for CustomDecimal {
/// fn from_tushare_value(value: &Value) -> Result<Self, TushareError> {
/// match value {
/// Value::String(s) => s.parse().map_err(|e| {
/// TushareError::ParseError(format!("Failed to parse decimal: {}", e))
/// }),
/// Value::Number(n) => {
/// if let Some(f) = n.as_f64() {
/// Ok(CustomDecimal(f))
/// } else {
/// Err(TushareError::ParseError("Invalid number format".to_string()))
/// }
/// }
/// _ => Err(TushareError::ParseError("Value is not a valid decimal".to_string()))
/// }
/// }
/// }
///
/// impl FromOptionalTushareValue for CustomDecimal {
/// fn from_optional_tushare_value(value: &Value) -> Result<Option<Self>, TushareError> {
/// if value.is_null() {
/// Ok(None)
/// } else {
/// match value {
/// Value::String(s) if s.is_empty() => Ok(None),
/// _ => CustomDecimal::from_tushare_value(value).map(Some)
/// }
/// }
/// }
/// }
/// ```
// Note: Basic Rust type implementations for FromOptionalTushareValue have been moved to src/basic_types.rs
/// Trait for converting Tushare API response data into Rust structs
///
/// This trait defines how to convert a single row of data from a Tushare API response
/// into a Rust struct. It can be implemented manually or automatically using the
/// `#[derive(FromTushareData)]` macro from the `tushare-derive` crate.
///
/// # Example
///
/// ```rust
/// use tushare_api::traits::FromTushareData;
/// use tushare_api::error::TushareError;
/// use serde_json::Value;
///
/// struct Stock {
/// ts_code: String,
/// name: String,
/// }
///
/// impl FromTushareData for Stock {
/// fn from_row(fields: &[String], values: &[Value]) -> Result<Self, TushareError> {
/// // Manual implementation
/// let ts_code_idx = fields.iter().position(|f| f == "ts_code")
/// .ok_or_else(|| TushareError::ParseError("Missing ts_code field".to_string()))?;
/// let name_idx = fields.iter().position(|f| f == "name")
/// .ok_or_else(|| TushareError::ParseError("Missing name field".to_string()))?;
///
/// Ok(Stock {
/// ts_code: values[ts_code_idx].as_str()
/// .ok_or_else(|| TushareError::ParseError("Invalid ts_code".to_string()))?
/// .to_string(),
/// name: values[name_idx].as_str()
/// .ok_or_else(|| TushareError::ParseError("Invalid name".to_string()))?
/// .to_string(),
/// })
/// }
/// }
/// ```
///
/// # Using the derive macro
///
/// For most use cases, you can use the derive macro instead of manual implementation:
///
/// ```rust
/// use tushare_api::DeriveFromTushareData;
///
/// #[derive(Debug, Clone, DeriveFromTushareData)]
/// pub struct Stock {
/// ts_code: String,
/// name: String,
/// area: Option<String>,
/// }
/// ```
/// Implementation of `TryFrom<TushareResponse>` for `TushareEntityList<T>`
///
/// This allows automatic conversion from API responses to typed entity lists.
/// It extracts pagination metadata and converts each data row to the target type T.
/// Helper function for parsing values with custom date format (non-optional types)
///
/// This function is used by the procedural macro when a `date_format` attribute is specified.
/// It attempts to parse the value using the custom format for supported chrono types.
///
/// # Arguments
///
/// * `value` - The JSON value to parse
/// * `format` - The custom date format string (e.g., "%d/%m/%Y")
///
/// # Returns
///
/// Returns the parsed value of type T or an error if parsing fails.
/// Helper function for parsing optional values with custom date format
///
/// This function is used by the procedural macro when a `date_format` attribute is specified
/// for optional fields. It handles null/empty values gracefully.
///
/// # Arguments
///
/// * `value` - The JSON value to parse (may be null)
/// * `format` - The custom date format string (e.g., "%d/%m/%Y")
///
/// # Returns
///
/// Returns Some(parsed_value) for valid values, None for null/empty, or an error for invalid formats.
/// Trait for types that support custom date format parsing
///
/// This trait is implemented for chrono date/time types to enable
/// custom format parsing through the `#[tushare(date_format = "...")]` attribute.