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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! BLPAPI request building
use std::ffi::CString;
use crate::element::Element;
use crate::errors::{BlpError, Result};
use crate::name::Name;
/// Request object for sending to BLPAPI services.
///
/// Requests are created by calling `Service::create_request()` and then
/// populated with data before being sent via `Session::send_request()`. The
/// BLPAPI SDK models requests as mutable single-use handles; this wrapper is
/// intentionally neither `Send` nor `Sync`.
///
/// # Examples
///
/// ```ignore
/// // Pre-intern names at setup (do once)
/// let securities = Name::get_or_intern("securities");
/// let fields = Name::get_or_intern("fields");
///
/// let mut req = svc.create_request("ReferenceDataRequest")?;
///
/// // Add securities
/// req.append_string(&securities, "IBM US Equity")?;
/// req.append_string(&securities, "AAPL US Equity")?;
///
/// // Add fields
/// req.append_string(&fields, "PX_LAST")?;
/// req.append_string(&fields, "SECURITY_NAME")?;
///
/// // Send request
/// session.send_request(&req, None, None)?;
/// ```
pub struct Request {
ptr: *mut crate::ffi::blpapi_Request_t,
}
impl Request {
/// Create a Request from a raw pointer (internal use only)
pub(crate) fn from_raw(ptr: *mut crate::ffi::blpapi_Request_t) -> Result<Self> {
if ptr.is_null() {
return Err(BlpError::Internal {
detail: "null request pointer".into(),
});
}
Ok(Self { ptr })
}
/// Get the raw pointer (internal use only)
pub(crate) fn as_ptr(&self) -> *mut crate::ffi::blpapi_Request_t {
self.ptr
}
/// Get the root element of this request for manipulation.
///
/// This provides low-level access to the request structure.
/// For most use cases, the convenience methods like `append_string()` are preferred.
pub fn elements(&self) -> Element<'_> {
// SAFETY: We're calling the BLPAPI C API with a valid pointer
// The returned element is valid for the lifetime of the Request
unsafe {
let elem_ptr = crate::ffi::blpapi_Request_elements(self.ptr);
Element::new(elem_ptr)
}
}
/// Get a child element by name
///
/// This is a convenience method that calls `elements().get(name)`.
pub fn get(&self, name: &Name) -> Option<Element<'_>> {
self.elements().get(name)
}
/// Append a string value to an array element.
///
/// This is commonly used for adding securities or fields to a request.
/// The array element must exist in the request schema.
///
/// # Example
/// ```ignore
/// let securities = Name::get_or_intern("securities");
/// let fields = Name::get_or_intern("fields");
/// req.append_string(&securities, "IBM US Equity")?;
/// req.append_string(&securities, "AAPL US Equity")?;
/// req.append_string(&fields, "PX_LAST")?;
/// ```
pub fn append_string(&mut self, array_name: &Name, value: &str) -> Result<()> {
let root = self.elements();
let array_elem = root
.get(array_name)
.ok_or_else(|| BlpError::InvalidArgument {
detail: format!("element '{}' not found", array_name.as_str()),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid string value: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
// - array_elem.as_ptr() is valid for the lifetime of the element
// - c_value is a valid C string
// - BLPAPI_ELEMENT_INDEX_END indicates append operation
let rc = unsafe {
crate::ffi::blpapi_Element_setValueString(
array_elem.as_ptr(),
c_value.as_ptr(),
crate::ffi::BLPAPI_ELEMENT_INDEX_END as usize,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setValueString failed with rc={}", rc),
});
}
Ok(())
}
/// Append a string value to an array element by string name.
///
/// Convenience method that takes a string name instead of a Name reference.
/// Slightly slower than `append_string()` but more convenient for simple use cases.
///
/// # Example
/// ```ignore
/// req.append_str("securities", "IBM US Equity")?;
/// req.append_str("securities", "AAPL US Equity")?;
/// req.append_str("fields", "PX_LAST")?;
/// ```
pub fn append_str(&mut self, array_name: &str, value: &str) -> Result<()> {
let root = self.elements();
let array_elem = root
.get_by_str(array_name)
.ok_or_else(|| BlpError::InvalidArgument {
detail: format!("element '{}' not found", array_name),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid string value: {}", e),
})?;
// SAFETY: array_elem.as_ptr() is valid, c_value is a valid C string.
// BLPAPI_ELEMENT_INDEX_END indicates append operation.
let rc = unsafe {
crate::ffi::blpapi_Element_setValueString(
array_elem.as_ptr(),
c_value.as_ptr(),
crate::ffi::BLPAPI_ELEMENT_INDEX_END as usize,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setValueString failed with rc={}", rc),
});
}
Ok(())
}
/// Set a string value on an element
pub fn set_string(&mut self, name: &Name, value: &str) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name.as_str()).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid string value: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementString(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
c_value.as_ptr(),
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setElementString failed with rc={}", rc),
});
}
Ok(())
}
/// Set a string value on a scalar element by string name.
///
/// Use this for scalar elements like "startDate", "endDate", "currency".
/// For array elements like "securities", "fields", use `append_str()` instead.
///
/// # Example
/// ```ignore
/// req.set_str("startDate", "20240115")?;
/// req.set_str("endDate", "20240120")?;
/// req.set_str("currency", "USD")?;
/// ```
pub fn set_str(&mut self, name: &str, value: &str) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid string value: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementString(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
c_value.as_ptr(),
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_str('{}') failed with rc={}", name, rc),
});
}
Ok(())
}
/// Set an i32 value on an element
pub fn set_i32(&mut self, name: &Name, value: i32) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name.as_str()).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementInt32(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
value,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setElementInt32 failed with rc={}", rc),
});
}
Ok(())
}
/// Set an i64 value on an element by name.
///
/// Gets the child element by name, then sets its value.
pub fn set_i64(&mut self, name: &Name, value: i64) -> Result<()> {
let root = self.elements();
let child = root.get(name).ok_or_else(|| BlpError::InvalidArgument {
detail: format!("element '{}' not found", name.as_str()),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setValueInt64(
child.as_ptr(),
value,
0, // index 0 for non-array elements
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setValueInt64 failed with rc={}", rc),
});
}
Ok(())
}
/// Set an f64 value on an element
pub fn set_f64(&mut self, name: &Name, value: f64) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name.as_str()).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementFloat64(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
value,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_setElementFloat64 failed with rc={}", rc),
});
}
Ok(())
}
/// Set a bool value on an element.
///
/// Uses `blpapi_Element_setElementString` with `"true"` / `"false"` because
/// Bool-typed BLPAPI elements don't accept Int32 values via
/// `blpapi_Element_setElementInt32` (fails with rc=262156 type mismatch).
pub fn set_bool(&mut self, name: &Name, value: bool) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name.as_str()).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
let bool_str = if value { "true" } else { "false" };
let c_value = CString::new(bool_str).unwrap();
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementString(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
c_value.as_ptr(),
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!(
"set_bool('{}', {}) failed with rc={}",
name.as_str(),
value,
rc
),
});
}
Ok(())
}
/// Set a datetime value on a scalar element by string name.
///
/// Parses an ISO-8601 datetime string (e.g., "2024-01-15T09:30:00") and sets
/// it as a BLPAPI Datetime. Supports formats:
/// - "2024-01-15T09:30:00" (full datetime)
/// - "2024-01-15T09:30" (no seconds)
/// - "2024-01-15" (date only)
///
/// # Example
/// ```ignore
/// req.set_datetime("startDateTime", "2024-01-15T09:30:00")?;
/// req.set_datetime("endDateTime", "2024-01-15T16:00:00")?;
/// ```
pub fn set_datetime(&mut self, name: &str, value: &str) -> Result<()> {
let dt = parse_datetime(value)?;
let root = self.elements();
let c_name = CString::new(name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementDatetime(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
&dt,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_datetime('{}') failed with rc={}", name, rc),
});
}
Ok(())
}
/// Set an integer value on a scalar element by string name.
///
/// Use this for integer elements like "interval".
///
/// # Example
/// ```ignore
/// req.set_int("interval", 5)?; // 5-minute bars
/// ```
pub fn set_int(&mut self, name: &str, value: i32) -> Result<()> {
let root = self.elements();
let c_name = CString::new(name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
// SAFETY: We're calling the BLPAPI C API with valid pointers
let rc = unsafe {
crate::ffi::blpapi_Element_setElementInt32(
root.as_ptr(),
c_name.as_ptr(),
std::ptr::null(),
value,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_int('{}') failed with rc={}", name, rc),
});
}
Ok(())
}
/// Append a new element to a sequence/array element and return a mutable handle.
///
/// This is used for Bloomberg override arrays where each entry is a sub-element
/// with "fieldId" and "value" children.
///
/// # Safety
///
/// `array_element` must be a valid, non-null pointer to a Bloomberg element
/// obtained from [`get_or_create_element`] or a prior call to this method.
///
/// # Example
/// ```ignore
/// // Get the overrides array
/// let overrides_ptr = req.get_or_create_element("overrides")?;
/// // Append a new override entry
/// let entry_ptr = unsafe { req.append_element(overrides_ptr)? };
/// // Set fieldId and value on the entry
/// unsafe { req.set_element_string(entry_ptr, "fieldId", "BEST_FPERIOD_OVERRIDE")? };
/// unsafe { req.set_element_string(entry_ptr, "value", "1FY")? };
/// ```
pub unsafe fn append_element(
&mut self,
array_element: *mut crate::ffi::blpapi_Element_t,
) -> Result<*mut crate::ffi::blpapi_Element_t> {
let mut appended = std::mem::MaybeUninit::uninit();
let rc = unsafe {
crate::ffi::blpapi_Element_appendElement(array_element, appended.as_mut_ptr())
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("blpapi_Element_appendElement failed with rc={}", rc),
});
}
Ok(unsafe { appended.assume_init() })
}
/// Set a string value on an element pointer by name.
///
/// This is the low-level version that operates on a raw element pointer
/// rather than the request root. Used for setting fields on sub-elements
/// returned by `append_element()`.
///
/// # Safety
///
/// `element` must be a valid, non-null pointer to a Bloomberg element
/// obtained from [`get_or_create_element`] or [`append_element`].
pub unsafe fn set_element_string(
&mut self,
element: *mut crate::ffi::blpapi_Element_t,
name: &str,
value: &str,
) -> Result<()> {
let c_name = CString::new(name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid value: {}", e),
})?;
// SAFETY: element is a valid pointer from get_or_create_element/append_element
let rc = unsafe {
crate::ffi::blpapi_Element_setElementString(
element,
c_name.as_ptr(),
std::ptr::null(),
c_value.as_ptr(),
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_element_string('{}') failed with rc={}", name, rc),
});
}
Ok(())
}
/// Get or create a child element by name.
///
/// For sequence/choice elements, this will create the sub-element if it doesn't exist.
/// Returns the element pointer for further manipulation.
///
/// # Example
/// ```ignore
/// let price_source = req.get_or_create_element("priceSource")?;
/// ```
pub fn get_or_create_element(
&mut self,
name: &str,
) -> Result<*mut crate::ffi::blpapi_Element_t> {
let root = self.elements();
let mut out = std::mem::MaybeUninit::uninit();
let c_name = CString::new(name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name: {}", e),
})?;
// blpapi_Element_getElement creates the sub-element for sequences/choices if it doesn't exist
let rc = unsafe {
crate::ffi::blpapi_Element_getElement(
root.as_ptr(),
out.as_mut_ptr(),
c_name.as_ptr(),
std::ptr::null(),
)
};
if rc != 0 {
return Err(BlpError::InvalidArgument {
detail: format!("get_or_create_element('{}') failed with rc={}", name, rc),
});
}
Ok(unsafe { out.assume_init() })
}
/// Set a string value on a nested element using a dotted path.
///
/// Navigates through the element tree using the path segments, creating
/// intermediate elements as needed, then sets the value on the leaf element.
///
/// # Example
/// ```ignore
/// // Sets priceSource -> securityName = "AAPL US Equity"
/// req.set_nested_str("priceSource.securityName", "AAPL US Equity")?;
///
/// // Sets priceSource -> dataRange -> historical -> startDate = "20240101"
/// req.set_nested_str("priceSource.dataRange.historical.startDate", "20240101")?;
/// ```
pub fn set_nested_str(&mut self, path: &str, value: &str) -> Result<()> {
let segments: Vec<&str> = path.split('.').collect();
if segments.is_empty() {
return Err(BlpError::InvalidArgument {
detail: "empty path".into(),
});
}
// Navigate to parent element (all but last segment)
let mut current = self.elements().as_ptr();
for segment in &segments[..segments.len() - 1] {
let c_name = CString::new(*segment).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid segment '{}': {}", segment, e),
})?;
let mut next = std::mem::MaybeUninit::uninit();
let rc = unsafe {
crate::ffi::blpapi_Element_getElement(
current,
next.as_mut_ptr(),
c_name.as_ptr(),
std::ptr::null(),
)
};
if rc != 0 {
return Err(BlpError::InvalidArgument {
detail: format!("failed to navigate to '{}' in path '{}'", segment, path),
});
}
current = unsafe { next.assume_init() };
}
// Set value on the leaf element
let leaf_name = segments.last().unwrap();
let c_name = CString::new(*leaf_name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name '{}': {}", leaf_name, e),
})?;
let c_value = CString::new(value).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid value: {}", e),
})?;
let rc = unsafe {
crate::ffi::blpapi_Element_setElementString(
current,
c_name.as_ptr(),
std::ptr::null(),
c_value.as_ptr(),
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_nested_str('{}') failed with rc={}", path, rc),
});
}
Ok(())
}
/// Set an integer value on a nested element using a dotted path.
///
/// # Example
/// ```ignore
/// req.set_nested_int("studyAttributes.smavgStudyAttributes.period", 20)?;
/// ```
pub fn set_nested_int(&mut self, path: &str, value: i32) -> Result<()> {
let segments: Vec<&str> = path.split('.').collect();
if segments.is_empty() {
return Err(BlpError::InvalidArgument {
detail: "empty path".into(),
});
}
// Navigate to parent element (all but last segment)
let mut current = self.elements().as_ptr();
for segment in &segments[..segments.len() - 1] {
let c_name = CString::new(*segment).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid segment '{}': {}", segment, e),
})?;
let mut next = std::mem::MaybeUninit::uninit();
let rc = unsafe {
crate::ffi::blpapi_Element_getElement(
current,
next.as_mut_ptr(),
c_name.as_ptr(),
std::ptr::null(),
)
};
if rc != 0 {
return Err(BlpError::InvalidArgument {
detail: format!("failed to navigate to '{}' in path '{}'", segment, path),
});
}
current = unsafe { next.assume_init() };
}
// Set value on the leaf element
let leaf_name = segments.last().unwrap();
let c_name = CString::new(*leaf_name).map_err(|e| BlpError::InvalidArgument {
detail: format!("invalid name '{}': {}", leaf_name, e),
})?;
let rc = unsafe {
crate::ffi::blpapi_Element_setElementInt32(
current,
c_name.as_ptr(),
std::ptr::null(),
value,
)
};
if rc != 0 {
return Err(BlpError::Internal {
detail: format!("set_nested_int('{}') failed with rc={}", path, rc),
});
}
Ok(())
}
}
/// Parse an ISO-8601 datetime string into a Bloomberg Datetime struct.
///
/// Supports formats:
/// - "2024-01-15T09:30:00" (full datetime)
/// - "2024-01-15T09:30" (no seconds)
/// - "2024-01-15" (date only)
fn split_datetime_offset(time_str: &str) -> Result<(&str, Option<i16>)> {
if let Some(stripped) = time_str
.strip_suffix('Z')
.or_else(|| time_str.strip_suffix('z'))
{
return Ok((stripped, Some(0)));
}
if let Some((idx, sign)) = time_str
.char_indices()
.rev()
.find(|(idx, ch)| *idx > 0 && (*ch == '+' || *ch == '-'))
{
let offset = parse_datetime_offset(sign, &time_str[idx + 1..])?;
return Ok((&time_str[..idx], Some(offset)));
}
Ok((time_str, None))
}
fn parse_datetime_offset(sign: char, offset: &str) -> Result<i16> {
let (hours_raw, minutes_raw) = if let Some((hours, minutes)) = offset.split_once(':') {
(hours, minutes)
} else if offset.len() == 4 {
offset.split_at(2)
} else {
(offset, "0")
};
let hours: i16 = hours_raw.parse().map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid timezone offset hours: {}", hours_raw),
})?;
let minutes: i16 = minutes_raw.parse().map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid timezone offset minutes: {}", minutes_raw),
})?;
if hours > 23 || minutes > 59 {
return Err(BlpError::InvalidArgument {
detail: format!("invalid timezone offset: {}{}", sign, offset),
});
}
let offset_minutes = hours * 60 + minutes;
Ok(if sign == '-' {
-offset_minutes
} else {
offset_minutes
})
}
fn parse_datetime(s: &str) -> Result<crate::ffi::blpapi_Datetime_t> {
use crate::ffi::{
blpapi_Datetime_t, BLPAPI_DATETIME_DATE_PART, BLPAPI_DATETIME_HOURS_PART,
BLPAPI_DATETIME_MINUTES_PART, BLPAPI_DATETIME_OFFSET_PART, BLPAPI_DATETIME_SECONDS_PART,
};
let mut dt = blpapi_Datetime_t::default();
// Split date and time parts
let (date_part, time_part) = if let Some(idx) = s.find('T') {
(&s[..idx], Some(&s[idx + 1..]))
} else {
(s, None)
};
// Parse date: "2024-01-15"
let date_parts: Vec<&str> = date_part.split('-').collect();
if date_parts.len() != 3 {
return Err(BlpError::InvalidArgument {
detail: format!("invalid date format: {}", date_part),
});
}
dt.year = date_parts[0]
.parse()
.map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid year: {}", date_parts[0]),
})?;
dt.month = date_parts[1]
.parse()
.map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid month: {}", date_parts[1]),
})?;
dt.day = date_parts[2]
.parse()
.map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid day: {}", date_parts[2]),
})?;
dt.parts = BLPAPI_DATETIME_DATE_PART;
// Parse time if present: "09:30:00", "09:30", or with an ISO timezone suffix.
if let Some(raw_time_str) = time_part {
let (time_str, offset_minutes) = split_datetime_offset(raw_time_str)?;
let time_parts: Vec<&str> = time_str.split(':').collect();
if time_parts.len() >= 2 {
dt.hours = time_parts[0]
.parse()
.map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid hours: {}", time_parts[0]),
})?;
dt.minutes = time_parts[1]
.parse()
.map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid minutes: {}", time_parts[1]),
})?;
dt.parts |= BLPAPI_DATETIME_HOURS_PART | BLPAPI_DATETIME_MINUTES_PART;
if time_parts.len() >= 3 {
// Handle seconds, possibly with fractional part.
let sec_str = time_parts[2].split('.').next().unwrap_or("0");
dt.seconds = sec_str.parse().map_err(|_| BlpError::InvalidArgument {
detail: format!("invalid seconds: {}", sec_str),
})?;
dt.parts |= BLPAPI_DATETIME_SECONDS_PART;
}
if let Some(offset) = offset_minutes {
dt.offset = offset;
dt.parts |= BLPAPI_DATETIME_OFFSET_PART;
}
}
}
Ok(dt)
}
impl Drop for Request {
fn drop(&mut self) {
if !self.ptr.is_null() {
// SAFETY: We own this pointer and it's valid.
// blpapi_Request_destroy releases the request resources.
unsafe {
crate::ffi::blpapi_Request_destroy(self.ptr);
}
self.ptr = std::ptr::null_mut();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_datetime_accepts_zero_offset_suffix() {
let dt = parse_datetime("2026-04-24T14:30:00+00:00").unwrap();
assert_eq!(dt.hours, 14);
assert_eq!(dt.minutes, 30);
assert_eq!(dt.seconds, 0);
assert_eq!(dt.offset, 0);
assert!(dt.parts & crate::ffi::BLPAPI_DATETIME_OFFSET_PART != 0);
}
#[test]
fn parse_datetime_accepts_nonzero_offset_suffix() {
let dt = parse_datetime("2026-04-24T14:30:03+02:00").unwrap();
assert_eq!(dt.seconds, 3);
assert_eq!(dt.offset, 120);
assert!(dt.parts & crate::ffi::BLPAPI_DATETIME_OFFSET_PART != 0);
}
#[test]
fn parse_datetime_accepts_z_suffix() {
let dt = parse_datetime("2026-04-24T14:30:03Z").unwrap();
assert_eq!(dt.seconds, 3);
assert_eq!(dt.offset, 0);
assert!(dt.parts & crate::ffi::BLPAPI_DATETIME_OFFSET_PART != 0);
}
}