kdbplus/ipc/mod.rs
1//! This `ipc` module provides an interface to interact with q/kdb+ via IPC. The expected usage is to send a (text) query to q/kdb+ process
2//! from Rust client and receive its response. Query to kdb+ is supported in two ways:
3//!
4//! - text query
5//! - functional query which is represented by a compound list of kdb+ ([See detail of IPC](https://code.kx.com/q4m3/11_IO/#116-interprocess-communication)).
6//!
7//! Compression/decompression of messages is also implemented following [kdb+ implementation](https://code.kx.com/q/basics/ipc/#compression).
8//!
9//! As for connect method, usually client interfaces of q/kdb+ do not provide a listener due to its protocol. However, sometimes Rust process is
10//! connecting to upstream and q/kdb+ starts afterward or is restarted more frequently. Then providing a listener method is a natural direction
11//! and it was achieved here. Following ways are supported to connect to kdb+:
12//!
13//! - TCP
14//! - TLS
15//! - Unix domain socket
16//!
17//! Furthermore, in order to improve inter-operatability some casting, getter and setter methods are provided.
18//!
19//! ## Environmentl Variables
20//!
21//! This crate uses q-native or crate-specific environmental variables.
22//!
23//! - `KDBPLUS_ACCOUNT_FILE`: A file path to a credential file which an acceptor loads in order to manage access from a q client. This file contains
24//! a user name and SHA-1 hashed password in each line which are delimited by `':'` without any space. For example, a file containing two credentials
25//! `"mattew:oracle"` and `"reluctant:slowday"` looks like this:
26//!
27//! ```bash
28//! mattew:431364b6450fc47ccdbf6a2205dfdb1baeb79412
29//! reluctant:d03f5cc1cdb11a77410ee34e26ca1102e67a893c
30//! ```
31//!
32//! The hashed password can be generated with q using a function `.Q.sha1`:
33//!
34//! ```q
35//! q).Q.sha1 "slowday"
36//! 0xd03f5cc1cdb11a77410ee34e26ca1102e67a893c
37//! ```
38//!
39//! - `KDBPLUS_TLS_KEY_FILE` and `KDBPLUS_TLS_KEY_FILE_SECRET`: The pkcs12 file and its password which TLS acceptor uses.
40//! - `QUDSPATH` (optional): q-native environmental variable to define an astract namespace. This environmental variable is used by UDS acceptor too.
41//! The abstract nameapace will be `@${QUDSPATH}/kx.[server process port]` if this environmental variable is defined. Otherwise it will be `@/tmp/kx.[server process port]`.
42//!
43//! *Notes:*
44//!
45//! - Messages will be sent with OS native endian.
46//! - When using this crate for a TLS client you need to set two environmental variables `KX_SSL_CERT_FILE` and `KX_SSL_KEY_FILE` on q side to make q/kdb+
47//! to work as a TLS server. For details, see [the KX website](https://code.kx.com/q/kb/ssl/).
48//!
49//! ## Type Mapping
50//!
51//! All types are expressed as `K` struct which is quite similar to the `K` struct of `api` module but its structure is optimized for IPC
52//! usage and for convenience to interact with. The table below shows the input types of each q type which is used to construct `K` object.
53//! Note that the input type can be different from the inner type. For example, timestamp has an input type of `chrono::DateTime<Utc>` but
54//! the inner type is `i64` denoting an elapsed time in nanoseconds since `2000.01.01D00:00:00`.
55//!
56//! | q | Rust |
57//! |------------------|---------------------------------------------------|
58//! | `bool` | `bool` |
59//! | `GUID` | `[u8; 16]` |
60//! | `byte` | `u8` |
61//! | `short` | `i16` |
62//! | `int` | `i32` |
63//! | `long` | `i64` |
64//! | `real` | `f32` |
65//! | `float` | `f64` |
66//! | `char` | `char` |
67//! | `symbol` | `String` |
68//! | `timestamp` | `chrono::DateTime<Utc>` |
69//! | `month` | `chrono::NaiveDate` |
70//! | `date` | `chrono::NaiveDate` |
71//! | `datetime` | `chrono::DateTime<Utc>` |
72//! | `timespan` | `chrono::Duration` |
73//! | `minute` | `chrono::Duration` |
74//! | `second` | `chrono::Duration` |
75//! | `time` | `chrono::Duration` |
76//! | `list` | `Vec<Item>` (`Item` is a corrsponding type above) |
77//! | `compound list` | `Vec<K>` |
78//! | `table` | `Vec<K>` |
79//! | `dictionary` | `Vec<K>` |
80//! | `null` | `()` |
81//!
82//! ## Examples
83//!
84//! ### Client
85//!
86//! ```rust
87//! use kdbplus::qattribute;
88//! use kdbplus::ipc::*;
89//!
90//! #[tokio::main(flavor = "multi_thread", worker_threads = 2)]
91//! async fn main() -> Result<()> {
92//! // Connect to qprocess running on localhost:5000 via UDS
93//! let mut socket = QStream::connect(ConnectionMethod::UDS, "", 5000_u16, "ideal:person").await?;
94//! println!("Connection type: {}", socket.get_connection_type());
95//!
96//! // Set remote function with an asynchronous text form message
97//! socket.send_async_message(&"collatz:{[n] seq:enlist n; while[not n = 1; seq,: n:$[n mod 2; 1 + 3 * n; `long$n % 2]]; seq}").await?;
98//!
99//! // Send a text form emessage synchronously
100//! let mut result = socket.send_sync_message(&"collatz[12]").await?;
101//! println!("collatz[12]: {}", result);
102//!
103//! result = socket.send_sync_message(&"collatz[`a]").await?;
104//! println!("collatz[`a]: {}", result);
105//!
106//! // Send a functional form message synchronously.
107//! let mut message = K::new_compound_list(vec![
108//! K::new_symbol(String::from("collatz")),
109//! K::new_long(100),
110//! ]);
111//! result = socket.send_sync_message(&message).await?;
112//! println!("collatz[100]: {}", result);
113//!
114//! // Modify the message to (`collatz; 20)
115//! message.pop().unwrap();
116//! message.push(&K::new_long(20)).unwrap();
117//! result = socket.send_sync_message(&message).await?;
118//! println!("collatz[20]: {}", result);
119//!
120//! // Send a functional form message asynchronous query.
121//! message = K::new_compound_list(vec![
122//! K::new_string(String::from("show"), qattribute::NONE),
123//! K::new_symbol(String::from("goodbye")),
124//! ]);
125//! socket.send_async_message(&message).await?;
126//!
127//! socket.shutdown().await?;
128//!
129//! Ok(())
130//! }
131//!```
132//! ### Listener
133//!
134//! ```no_run
135//! use std::io;
136//! use kdbplus::ipc::*;
137//!
138//! #[tokio::main]
139//! async fn main() -> Result<()> {
140//! // Start listenening over TCP at the port 7000 with authentication enabled.
141//! let mut socket_tcp = QStream::accept(ConnectionMethod::TCP, "127.0.0.1", 7000).await?;
142//!
143//! // Send a query with the socket.
144//! let greeting = socket_tcp.send_sync_message(&"string `Hello").await?;
145//! println!("Greeting: {}", greeting);
146//!
147//! socket_tcp.shutdown().await?;
148//!
149//! Ok(())
150//! }
151//! ```
152//!
153//! Then q client can connect to this acceptor with the acceptor's host, port and the credential configured in `KDBPLUS_ACCOUNT_FILE`:
154//!
155//! ```q
156//! q)h:hopen `::7000:reluctant:slowday
157//! ```
158
159//++++++++++++++++++++++++++++++++++++++++++++++++++//
160// >> Settings
161//++++++++++++++++++++++++++++++++++++++++++++++++++//
162
163#![allow(non_upper_case_globals)]
164#![allow(non_camel_case_types)]
165#![allow(non_snake_case)]
166
167//++++++++++++++++++++++++++++++++++++++++++++++++++//
168// >> Load Libraries
169//++++++++++++++++++++++++++++++++++++++++++++++++++//
170
171pub mod error;
172
173use super::{qattribute, qinf_base, qninf_base, qnull_base, qtype};
174use chrono::prelude::*;
175use chrono::Duration;
176use error::Error;
177use std::any::Any;
178use std::fmt;
179use std::result::Result as StdResult;
180
181//++++++++++++++++++++++++++++++++++++++++++++++++++//
182// >> Structs
183//++++++++++++++++++++++++++++++++++++++++++++++++++//
184
185pub type Result<T> = StdResult<T, Error>;
186
187//++++++++++++++++++++++++++++++++++++++++++++++++++//
188// >> Global Variables
189//++++++++++++++++++++++++++++++++++++++++++++++++++//
190
191//%% kdb+ Offset %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
192
193/// 1 day in nano second.
194pub const ONE_DAY_NANOS: i64 = 86400000000000;
195
196/// 1 day in milli second.
197pub const ONE_DAY_MILLIS: i64 = 86400000;
198
199/// 2000.01.01 (kdb+ epoch) - 1970.01.01 in month.
200pub const KDB_MONTH_OFFSET: i32 = 360;
201
202/// 2000.01.01 (kdb+ epoch) - 1970.01.01 in day.
203pub const KDB_DAY_OFFSET: i32 = 10957;
204
205/// 2000.01.01 (kdb+ epoch) - 1970.01.01 in nanosecond.
206pub const KDB_TIMESTAMP_OFFSET: i64 = 946684800000000000;
207
208//%% Null & Infinity %%vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
209
210pub mod qnull {
211 //! This module provides a list of q null values set on Rust process and used for IPC. The motivation
212 //! to contain them in a module is to tie them up as related items rather than scattered values.
213 //! Hence user should use these indicators with `qnull::` prefix, e.g., `qnull::FLOAT`.
214
215 use super::qnull_base;
216 use chrono::prelude::*;
217 use chrono::Duration;
218 use once_cell::sync::Lazy;
219
220 /// Null value of GUID (`0Ng`).
221 /// # Example
222 /// ```
223 /// use kdbplus::ipc::*;
224 ///
225 /// fn main() {
226 /// let q_guid_null = K::new_guid(qnull::GUID);
227 /// assert_eq!(
228 /// format!("{}", q_guid_null),
229 /// String::from("00000000-0000-0000-0000-000000000000")
230 /// );
231 /// }
232 /// ```
233 pub const GUID: [u8; 16] = [0_u8; 16];
234
235 /// Null value of short (`0Nh`).
236 /// # Example
237 /// ```
238 /// use kdbplus::ipc::*;
239 ///
240 /// fn main() {
241 /// let q_short_null = K::new_short(qnull::SHORT);
242 /// assert_eq!(format!("{}", q_short_null), String::from("0Nh"));
243 /// }
244 /// ```
245 pub const SHORT: i16 = qnull_base::H;
246
247 /// Null value of int (`0Ni`).
248 /// # Example
249 /// ```
250 /// use kdbplus::ipc::*;
251 ///
252 /// fn main() {
253 /// let q_int_null = K::new_int(qnull::INT);
254 /// assert_eq!(format!("{}", q_int_null), String::from("0Ni"));
255 /// }
256 /// ```
257 pub const INT: i32 = qnull_base::I;
258
259 /// Null value of long (`0N`).
260 /// # Example
261 /// ```
262 /// use kdbplus::ipc::*;
263 ///
264 /// fn main() {
265 /// let q_long_null = K::new_long(qnull::LONG);
266 /// assert_eq!(format!("{}", q_long_null), String::from("0N"));
267 /// }
268 /// ```
269 pub const LONG: i64 = qnull_base::J;
270
271 /// Null value of real (`0Ne`).
272 /// # Example
273 /// ```
274 /// use kdbplus::ipc::*;
275 ///
276 /// fn main() {
277 /// let q_real_null = K::new_real(qnull::REAL);
278 /// assert_eq!(format!("{}", q_real_null), String::from("0Ne"));
279 /// }
280 /// ```
281 pub const REAL: f32 = qnull_base::E;
282
283 /// Null value of float (`0n`).
284 /// # Example
285 /// ```
286 /// use kdbplus::ipc::*;
287 ///
288 /// fn main() {
289 /// let q_float_null = K::new_float(qnull::FLOAT);
290 /// assert_eq!(format!("{}", q_float_null), String::from("0n"));
291 /// }
292 /// ```
293 pub const FLOAT: f64 = qnull_base::F;
294
295 /// Null value of char (`" "`).
296 /// # Example
297 /// ```
298 /// use kdbplus::ipc::*;
299 ///
300 /// fn main() {
301 /// let q_char_null = K::new_char(qnull::CHAR);
302 /// assert_eq!(format!("{}", q_char_null), String::from("\" \""));
303 /// }
304 /// ```
305 pub const CHAR: char = qnull_base::C;
306
307 /// Null value of symbol (<code>`</code>).
308 /// # Example
309 /// ```
310 /// use kdbplus::ipc::*;
311 ///
312 /// fn main() {
313 /// let q_symbol_null = K::new_symbol(qnull::SYMBOL);
314 /// assert_eq!(format!("{}", q_symbol_null), String::from("`"));
315 /// }
316 /// ```
317 pub const SYMBOL: String = String::new();
318
319 /// Null value of timestamp (`0Np`).
320 /// # Example
321 /// ```
322 /// use kdbplus::ipc::*;
323 ///
324 /// fn main() {
325 /// let q_timestamp_null = K::new_timestamp(*qnull::TIMESTAMP);
326 /// assert_eq!(format!("{}", q_timestamp_null), String::from("0Np"));
327 /// }
328 /// ```
329 /// # Note
330 /// The range of timestamp in Rust is wider than in q.
331 pub const TIMESTAMP: Lazy<DateTime<Utc>> = Lazy::new(|| {
332 NaiveDate::from_ymd_opt(1707, 9, 22)
333 .unwrap()
334 .and_hms_nano_opt(0, 12, 43, 145224192)
335 .unwrap()
336 .and_local_timezone(Utc)
337 .unwrap()
338 });
339
340 /// Null value of month (`0Nm`).
341 /// # Example
342 /// ```
343 /// use kdbplus::ipc::*;
344 ///
345 /// fn main() {
346 /// let q_month_null = K::new_month(qnull::MONTH);
347 /// assert_eq!(format!("{}", q_month_null), String::from("0Nm"));
348 /// }
349 /// ```
350 /// # Note
351 /// The range of month in Rust is narrower than in q.
352 pub const MONTH: NaiveDate = NaiveDate::MIN;
353
354 /// Null valueo of date (`0Nd`).
355 /// # Example
356 /// ```
357 /// use kdbplus::ipc::*;
358 ///
359 /// fn main() {
360 /// let q_date_null = K::new_date(qnull::DATE);
361 /// assert_eq!(format!("{}", q_date_null), String::from("0Nd"));
362 /// }
363 /// ```
364 /// # Note
365 /// The range of date in Rust is narrower than in q.
366 pub const DATE: NaiveDate = NaiveDate::MIN;
367
368 /// Null value of datetime (`0Nz`).
369 /// # Example
370 /// ```
371 /// use kdbplus::ipc::*;
372 ///
373 /// fn main() {
374 /// let q_datetime_null = K::new_datetime(qnull::DATETIME);
375 /// assert_eq!(format!("{}", q_datetime_null), String::from("0Nz"));
376 /// }
377 /// ```
378 /// # Note
379 /// The range of datetime in Rust is narrower than in q.
380 pub const DATETIME: DateTime<Utc> = DateTime::<Utc>::MIN_UTC;
381
382 /// Null value of timespan (`0Nn`).
383 /// # Example
384 /// ```
385 /// use kdbplus::ipc::*;
386 ///
387 /// fn main() {
388 /// let q_timespan_null = K::new_timespan(*qnull::TIMESPAN);
389 /// assert_eq!(format!("{}", q_timespan_null), String::from("0Nn"));
390 /// }
391 /// ```
392 pub const TIMESPAN: Lazy<Duration> = Lazy::new(|| Duration::nanoseconds(qnull_base::J));
393
394 /// Null value of minute (`0Nu`).
395 /// # Example
396 /// ```
397 /// use kdbplus::ipc::*;
398 ///
399 /// fn main() {
400 /// let q_minute_null = K::new_minute(*qnull::MINUTE);
401 /// assert_eq!(format!("{}", q_minute_null), String::from("0Nu"));
402 /// }
403 /// ```
404 pub const MINUTE: Lazy<Duration> = Lazy::new(|| Duration::minutes(qnull_base::I as i64));
405
406 /// Null value of second (`0Nv`).
407 /// # Example
408 /// ```
409 /// use kdbplus::ipc::*;
410 ///
411 /// fn main() {
412 /// let q_second_null = K::new_second(*qnull::SECOND);
413 /// assert_eq!(format!("{}", q_second_null), String::from("0Nv"));
414 /// }
415 /// ```
416 pub const SECOND: Lazy<Duration> = Lazy::new(|| Duration::seconds(qnull_base::I as i64));
417
418 /// Null value of time (`0Nt`).
419 /// # Example
420 /// ```
421 /// use kdbplus::ipc::*;
422 ///
423 /// fn main() {
424 /// let q_time_null = K::new_time(*qnull::TIME);
425 /// assert_eq!(format!("{}", q_time_null), String::from("0Nt"));
426 /// }
427 /// ```
428 pub const TIME: Lazy<Duration> = Lazy::new(|| Duration::milliseconds(qnull_base::I as i64));
429}
430
431pub mod qinf {
432 //! This module provides a list of q infinite values set on Rust process and used for IPC.
433 //! The motivation to contain them in a module is to tie them up as related items rather
434 //! than scattered values. Hence user should use these indicators with `qnull::` prefix, e.g., `qnull::FLOAT`.
435
436 use super::qinf_base;
437 use chrono::prelude::*;
438 use chrono::Duration;
439 use once_cell::sync::Lazy;
440
441 /// Infinity value of short (`0Wh`).
442 /// # Example
443 /// ```
444 /// use kdbplus::ipc::*;
445 ///
446 /// fn main() {
447 /// let q_short_inf = K::new_short(qinf::SHORT);
448 /// assert_eq!(format!("{}", q_short_inf), String::from("0Wh"));
449 /// }
450 /// ```
451 pub const SHORT: i16 = qinf_base::H;
452
453 /// Infinity value of int (`0Wi`).
454 /// # Example
455 /// ```
456 /// use kdbplus::ipc::*;
457 ///
458 /// fn main() {
459 /// let q_int_inf = K::new_int(qinf::INT);
460 /// assert_eq!(format!("{}", q_int_inf), String::from("0Wi"));
461 /// }
462 /// ```
463 pub const INT: i32 = qinf_base::I;
464
465 /// Infinity value of long (`0W`).
466 /// # Example
467 /// ```
468 /// use kdbplus::ipc::*;
469 ///
470 /// fn main() {
471 /// let q_long = K::new_long(86400000000000);
472 /// assert_eq!(format!("{}", q_long), String::from("86400000000000"));
473 /// }
474 /// ```
475 pub const LONG: i64 = qinf_base::J;
476
477 /// Infinity value of real (`0We`).
478 /// # Example
479 /// ```
480 /// use kdbplus::ipc::*;
481 ///
482 /// fn main() {
483 /// let q_real_null = K::new_real(qnull::REAL);
484 /// assert_eq!(format!("{}", q_real_null), String::from("0Ne"));
485 /// }
486 /// ```
487 pub const REAL: f32 = qinf_base::E;
488
489 /// Infinity value of float (`0w`).
490 /// # Example
491 /// ```
492 /// use kdbplus::ipc::*;
493 ///
494 /// fn main() {
495 /// let q_float_inf = K::new_float(qinf::FLOAT);
496 /// assert_eq!(format!("{}", q_float_inf), String::from("0w"));
497 /// }
498 /// ```
499 pub const FLOAT: f64 = qinf_base::F;
500
501 /// Infinity value of timestamp (`0Wp`).
502 /// # Example
503 /// ```
504 /// use kdbplus::ipc::*;
505 ///
506 /// fn main() {
507 /// let q_timestamp_inf = K::new_timestamp(*qinf::TIMESTAMP);
508 /// assert_eq!(format!("{}", q_timestamp_inf), String::from("0Wp"));
509 /// }
510 /// ```
511 /// # Note
512 /// The range of timestamp in Rust is wider than in q.
513 pub const TIMESTAMP: Lazy<DateTime<Utc>> = Lazy::new(|| {
514 NaiveDate::from_ymd_opt(2292, 4, 10)
515 .unwrap()
516 .and_hms_nano_opt(23, 47, 16, 854775807)
517 .unwrap()
518 .and_local_timezone(Utc)
519 .unwrap()
520 });
521
522 /// Infinity value of month (`0Wm`).
523 /// # Example
524 /// ```
525 /// use kdbplus::ipc::*;
526 ///
527 /// fn main() {
528 /// let q_month_inf = K::new_month(*qinf::MONTH);
529 /// assert_eq!(format!("{}", q_month_inf), String::from("0Wm"));
530 /// }
531 /// ```
532 /// # Note
533 /// The range of month in Rust is narrower than in q.
534 pub const MONTH: Lazy<NaiveDate> = Lazy::new(|| NaiveDate::MAX - Duration::days(30));
535
536 /// Infinity valueo of date (`0Wd`).
537 /// # Example
538 /// ```
539 /// use kdbplus::ipc::*;
540 ///
541 /// fn main() {
542 /// let q_date_inf = K::new_date(qinf::DATE);
543 /// assert_eq!(format!("{}", q_date_inf), String::from("0Wd"));
544 /// }
545 /// ```
546 /// # Note
547 /// The range of date in Rust is narrower than in q.
548 pub const DATE: NaiveDate = NaiveDate::MAX;
549
550 /// Infinity value of datetime (`0Wz`).
551 /// # Example
552 /// ```
553 /// use kdbplus::ipc::*;
554 ///
555 /// fn main() {
556 /// let q_datetime_inf = K::new_datetime(*qinf::DATETIME);
557 /// assert_eq!(format!("{}", q_datetime_inf), String::from("0Wz"));
558 /// }
559 /// ```
560 /// # Note
561 /// The range of datetime in Rust is narrower than in q.
562 pub const DATETIME: Lazy<DateTime<Utc>> =
563 Lazy::new(|| DateTime::<Utc>::MAX_UTC - Duration::nanoseconds(999999));
564
565 /// Infinity value of timespan (`0Wn`).
566 /// # Example
567 /// ```
568 /// use kdbplus::ipc::*;
569 ///
570 /// fn main() {
571 /// let q_timespan_inf = K::new_timespan(*qinf::TIMESPAN);
572 /// assert_eq!(format!("{}", q_timespan_inf), String::from("0Wn"));
573 /// }
574 /// ```
575 pub const TIMESPAN: Lazy<Duration> = Lazy::new(|| Duration::nanoseconds(qinf_base::J));
576
577 /// Infinity value of minute (`0Wu`).
578 /// # Example
579 /// ```
580 /// use kdbplus::ipc::*;
581 ///
582 /// fn main() {
583 /// let q_minute_inf = K::new_minute(*qinf::MINUTE);
584 /// assert_eq!(format!("{}", q_minute_inf), String::from("0Wu"));
585 /// }
586 /// ```
587 pub const MINUTE: Lazy<Duration> = Lazy::new(|| Duration::minutes(qinf_base::I as i64));
588
589 /// Infinity value of second (`0Wv`).
590 /// # Example
591 /// ```
592 /// use kdbplus::ipc::*;
593 ///
594 /// fn main() {
595 /// let q_second_inf = K::new_second(*qinf::SECOND);
596 /// assert_eq!(format!("{}", q_second_inf), String::from("0Wv"));
597 /// }
598 /// ```
599 pub const SECOND: Lazy<Duration> = Lazy::new(|| Duration::seconds(qinf_base::I as i64));
600
601 /// Infinity value of time (`0Wt`).
602 /// # Example
603 /// ```
604 /// use kdbplus::ipc::*;
605 ///
606 /// fn main() {
607 /// let q_time_inf = K::new_time(*qinf::TIME);
608 /// assert_eq!(format!("{}", q_time_inf), String::from("0Wt"));
609 /// }
610 /// ```
611 pub const TIME: Lazy<Duration> = Lazy::new(|| Duration::milliseconds(qinf_base::I as i64));
612}
613
614pub mod qninf {
615 //! This module provides a list of q negative infinite values set on Rust process and used for IPC.
616 //! The motivation to contain them in a module is to tie them up as related items rather than
617 //! scattered values. Hence user should use these indicators with `qnull::` prefix, e.g., `qnull::FLOAT`.
618
619 use super::qninf_base;
620 use chrono::prelude::*;
621 use chrono::Duration;
622 use once_cell::sync::Lazy;
623
624 /// Infinity value of short (`-0Wh`).
625 /// # Example
626 /// ```
627 /// use kdbplus::ipc::*;
628 ///
629 /// fn main() {
630 /// let q_short_ninf = K::new_short(qninf::SHORT);
631 /// assert_eq!(format!("{}", q_short_ninf), String::from("-0Wh"));
632 /// }
633 /// ```
634 pub const SHORT: i16 = qninf_base::H;
635
636 /// Infinity value of int (`-0Wi`).
637 /// # Example
638 /// ```
639 /// use kdbplus::ipc::*;
640 ///
641 /// fn main() {
642 /// let q_int_ninf = K::new_int(qninf::INT);
643 /// assert_eq!(format!("{}", q_int_ninf), String::from("-0Wi"));
644 /// }
645 /// ```
646 pub const INT: i32 = qninf_base::I;
647
648 /// Infinity value of long (-`0W`).
649 /// # Example
650 /// ```
651 /// use kdbplus::ipc::*;
652 ///
653 /// fn main() {
654 /// let q_long_ninf = K::new_long(qninf::LONG);
655 /// assert_eq!(format!("{}", q_long_ninf), String::from("-0W"));
656 /// }
657 /// ```
658 pub const LONG: i64 = qninf_base::J;
659
660 /// Infinity value of real (`-0We`).
661 /// # Example
662 /// ```
663 /// use kdbplus::ipc::*;
664 ///
665 /// fn main() {
666 /// let q_real_ninf: K = K::new_real(qninf::REAL);
667 /// assert_eq!(format!("{}", q_real_ninf), String::from("-0We"));
668 /// }
669 /// ```
670 pub const REAL: f32 = qninf_base::E;
671
672 /// Infinity value of float (`-0w`).
673 /// # Example
674 /// ```
675 /// use kdbplus::ipc::*;
676 ///
677 /// fn main() {
678 /// let q_float_ninf = K::new_float(qninf::FLOAT);
679 /// assert_eq!(format!("{}", q_float_ninf), String::from("-0w"));
680 /// }
681 /// ```
682 pub const FLOAT: f64 = qninf_base::F;
683
684 /// Infinity value of timestamp (`-0Wp`).
685 /// # Example
686 /// ```
687 /// use kdbplus::ipc::*;
688 ///
689 /// fn main() {
690 /// let q_timestamp_ninf = K::new_timestamp(*qninf::TIMESTAMP);
691 /// assert_eq!(format!("{}", q_timestamp_ninf), String::from("-0Wp"));
692 /// }
693 /// ```
694 /// # Note
695 /// The range of timestamp in Rust is wider than in q.
696 pub const TIMESTAMP: Lazy<DateTime<Utc>> = Lazy::new(|| {
697 NaiveDate::from_ymd_opt(1707, 9, 22)
698 .unwrap()
699 .and_hms_nano_opt(0, 12, 43, 145224193)
700 .unwrap()
701 .and_local_timezone(Utc)
702 .unwrap()
703 });
704
705 /// Infinity value of month (`-0Wm`).
706 /// # Example
707 /// ```
708 /// use kdbplus::ipc::*;
709 ///
710 /// fn main() {
711 /// let q_month_ninf = K::new_month(*qninf::MONTH);
712 /// assert_eq!(format!("{}", q_month_ninf), String::from("-0Wm"));
713 /// }
714 /// ```
715 /// # Note
716 /// The range of month in Rust is narrower than in q.
717 pub const MONTH: Lazy<NaiveDate> = Lazy::new(|| NaiveDate::MIN + Duration::days(31));
718
719 /// Infinity valueo of date (`-0Wd`).
720 /// # Example
721 /// ```
722 /// use kdbplus::ipc::*;
723 ///
724 /// fn main() {
725 /// let q_date_ninf = K::new_date(*qninf::DATE);
726 /// assert_eq!(format!("{}", q_date_ninf), String::from("-0Wd"));
727 /// }
728 /// ```
729 /// # Note
730 /// The range of date in Rust is narrower than in q.
731 pub const DATE: Lazy<NaiveDate> = Lazy::new(|| NaiveDate::MIN + Duration::days(1));
732
733 /// Infinity value of datetime (`-0Wz`).
734 /// # Example
735 /// ```
736 /// use kdbplus::ipc::*;
737 ///
738 /// fn main() {
739 /// let q_datetime_ninf = K::new_datetime(*qninf::DATETIME);
740 /// assert_eq!(format!("{}", q_datetime_ninf), String::from("-0Wz"));
741 /// }
742 /// ```
743 /// # Note
744 /// The range of datetime in Rust is narrower than in q.
745 pub const DATETIME: Lazy<DateTime<Utc>> =
746 Lazy::new(|| DateTime::<Utc>::MIN_UTC + Duration::nanoseconds(1000000));
747
748 /// Infinity value of timespan (`-0Wn`).
749 /// # Example
750 /// ```
751 /// use kdbplus::ipc::*;
752 ///
753 /// fn main() {
754 /// let q_timespan_ninf = K::new_timespan(*qninf::TIMESPAN);
755 /// assert_eq!(format!("{}", q_timespan_ninf), String::from("-0Wn"));
756 /// }
757 /// ```
758 pub const TIMESPAN: Lazy<Duration> = Lazy::new(|| Duration::nanoseconds(qninf_base::J));
759
760 /// Infinity value of minute (`-0Wu`).
761 /// # Example
762 /// ```
763 /// use kdbplus::ipc::*;
764 ///
765 /// fn main() {
766 /// let q_minute_ninf = K::new_minute(*qninf::MINUTE);
767 /// assert_eq!(format!("{}", q_minute_ninf), String::from("-0Wu"));
768 /// }
769 /// ```
770 pub const MINUTE: Lazy<Duration> = Lazy::new(|| Duration::minutes(qninf_base::I as i64));
771
772 /// Infinity value of second (`-0Wv`).
773 /// # Example
774 /// ```
775 /// use kdbplus::ipc::*;
776 ///
777 /// fn main() {
778 /// let q_second_ninf = K::new_second(*qninf::SECOND);
779 /// assert_eq!(format!("{}", q_second_ninf), String::from("-0Wv"));
780 /// }
781 /// ```
782 pub const SECOND: Lazy<Duration> = Lazy::new(|| Duration::seconds(qninf_base::I as i64));
783
784 /// Infinity value of time (`-0Wt`).
785 /// # Example
786 /// ```
787 /// use kdbplus::ipc::*;
788 ///
789 /// fn main() {
790 /// let q_time_ninf = K::new_time(*qninf::TIME);
791 /// assert_eq!(format!("{}", q_time_ninf), String::from("-0Wt"));
792 /// }
793 /// ```
794 pub const TIME: Lazy<Duration> = Lazy::new(|| Duration::milliseconds(qninf_base::I as i64));
795}
796
797//++++++++++++++++++++++++++++++++++++++++++++++++++//
798// >> Structs
799//++++++++++++++++++++++++++++++++++++++++++++++++++//
800
801//%% Alias %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
802
803/// q type denoting symbol and string.
804pub type S = String;
805/// q type denoting char.
806pub type C = i8;
807/// q type denoting bool and byte.
808pub type G = u8;
809/// q type denoting short.
810pub type H = i16;
811/// q type denoting int and its compatible types (month, date, minute, second and time) of q.
812pub type I = i32;
813/// q type denoting long and its compatible types (timestamp and timespan) of q.
814pub type J = i64;
815/// q type denoting real.
816pub type E = f32;
817/// q type denoting float and datetime.
818pub type F = f64;
819/// q type denoting GUID.
820pub type U = [G; 16];
821
822//%% AsAny %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
823
824/// Feature of q list object to be cast to concrete type internally.
825pub(crate) trait AsAny {
826 /// Return as Any type.
827 fn as_any(&self) -> &dyn Any;
828 /// Return as mutable Any type.
829 fn as_any_mut(&mut self) -> &mut dyn Any;
830}
831
832//%% Klone %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
833
834/// Trait to clone `k0_list`.
835pub(crate) trait Klone {
836 fn clone_box(&self) -> Box<dyn k0_list_inner>;
837}
838
839//%% k0_list_inner %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
840
841/// Feature of q list.
842pub(crate) trait k0_list_inner: Klone + fmt::Debug + AsAny + Send + Sync + 'static {
843 /// Get a length of inner vector.
844 fn len(&self) -> usize;
845}
846
847//%% k0_list %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
848
849/// Underlying list value of q object.
850/// # Note
851/// Usually this struct does not need to be accessed this struct directly unless user wants to
852/// access via a raw pointer for non-trivial stuff.
853#[derive(Debug)]
854pub(crate) struct k0_list {
855 /// Length of the list.
856 n: J,
857 /// Pointer referring to the head of the list. This pointer will be interpreted
858 /// as various types when accessing `K` object to edit the list with
859 /// [`as_mut_slice`](trait.KUtility.html#tymethod.as_mut_slice).
860 G0: Box<dyn k0_list_inner>,
861}
862
863//%% k0_inner %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
864
865/// Underlying atom value of q object.
866/// # Note
867/// Usually this struct does not need to be accessed directly unless user wants to
868/// access via a raw pointer for non-trivial stuff.
869#[derive(Clone, Debug)]
870pub(crate) enum k0_inner {
871 /// Byte type holder.
872 byte(G),
873 /// GUID type holder.
874 guid(U),
875 /// Short type holder.
876 short(H),
877 /// Int type holder.
878 int(I),
879 /// Long type older.
880 long(J),
881 /// Real type holder.
882 real(E),
883 /// Float type holder.
884 float(F),
885 /// Symbol type holder.
886 /// # Note
887 /// String type is also stored here.
888 symbol(S),
889 /// Table type holder.
890 table(K),
891 /// List type holder.
892 list(k0_list),
893 /// Null type holder.
894 null(()),
895}
896
897//%% k0 %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
898
899/// Underlying struct of q object.
900#[derive(Clone, Debug)]
901pub(crate) struct k0 {
902 /// Type indicator.
903 qtype: i8,
904 /// Attribute of list.
905 attribute: i8,
906 /// Underlying value.
907 value: k0_inner,
908}
909
910//%% K %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
911
912/// Struct representing q object.
913#[derive(Clone, Debug)]
914pub struct K(pub(crate) Box<k0>);
915
916//++++++++++++++++++++++++++++++++++++++++++++++++++//
917// >> Implementation
918//++++++++++++++++++++++++++++++++++++++++++++++++++//
919
920//%% AsAny %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
921
922impl AsAny for Vec<G> {
923 fn as_any(&self) -> &dyn Any {
924 self
925 }
926 fn as_any_mut(&mut self) -> &mut dyn Any {
927 self
928 }
929}
930
931impl AsAny for Vec<U> {
932 fn as_any(&self) -> &dyn Any {
933 self
934 }
935 fn as_any_mut(&mut self) -> &mut dyn Any {
936 self
937 }
938}
939
940impl AsAny for Vec<H> {
941 fn as_any(&self) -> &dyn Any {
942 self
943 }
944 fn as_any_mut(&mut self) -> &mut dyn Any {
945 self
946 }
947}
948
949impl AsAny for Vec<I> {
950 fn as_any(&self) -> &dyn Any {
951 self
952 }
953 fn as_any_mut(&mut self) -> &mut dyn Any {
954 self
955 }
956}
957
958impl AsAny for Vec<J> {
959 fn as_any(&self) -> &dyn Any {
960 self
961 }
962 fn as_any_mut(&mut self) -> &mut dyn Any {
963 self
964 }
965}
966
967impl AsAny for Vec<E> {
968 fn as_any(&self) -> &dyn Any {
969 self
970 }
971 fn as_any_mut(&mut self) -> &mut dyn Any {
972 self
973 }
974}
975
976impl AsAny for Vec<F> {
977 fn as_any(&self) -> &dyn Any {
978 self
979 }
980 fn as_any_mut(&mut self) -> &mut dyn Any {
981 self
982 }
983}
984
985impl AsAny for String {
986 fn as_any(&self) -> &dyn Any {
987 self
988 }
989 fn as_any_mut(&mut self) -> &mut dyn Any {
990 self
991 }
992}
993
994impl AsAny for Vec<S> {
995 fn as_any(&self) -> &dyn Any {
996 self
997 }
998 fn as_any_mut(&mut self) -> &mut dyn Any {
999 self
1000 }
1001}
1002
1003impl AsAny for Vec<K> {
1004 fn as_any(&self) -> &dyn Any {
1005 self
1006 }
1007 fn as_any_mut(&mut self) -> &mut dyn Any {
1008 self
1009 }
1010}
1011
1012//%% Klone %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
1013
1014impl<T> Klone for T
1015where
1016 T: k0_list_inner + Clone,
1017{
1018 fn clone_box(&self) -> Box<dyn k0_list_inner> {
1019 Box::new(self.clone())
1020 }
1021}
1022
1023//%% k0_list_inner %%vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
1024
1025impl k0_list_inner for Vec<G> {
1026 fn len(&self) -> usize {
1027 self.len()
1028 }
1029}
1030
1031impl k0_list_inner for Vec<U> {
1032 fn len(&self) -> usize {
1033 self.len()
1034 }
1035}
1036
1037impl k0_list_inner for Vec<H> {
1038 fn len(&self) -> usize {
1039 self.len()
1040 }
1041}
1042
1043impl k0_list_inner for Vec<I> {
1044 fn len(&self) -> usize {
1045 self.len()
1046 }
1047}
1048
1049impl k0_list_inner for Vec<J> {
1050 fn len(&self) -> usize {
1051 self.len()
1052 }
1053}
1054
1055impl k0_list_inner for Vec<E> {
1056 fn len(&self) -> usize {
1057 self.len()
1058 }
1059}
1060
1061impl k0_list_inner for Vec<F> {
1062 fn len(&self) -> usize {
1063 self.len()
1064 }
1065}
1066
1067impl k0_list_inner for String {
1068 fn len(&self) -> usize {
1069 self.len()
1070 }
1071}
1072
1073impl k0_list_inner for Vec<S> {
1074 fn len(&self) -> usize {
1075 self.len()
1076 }
1077}
1078
1079impl k0_list_inner for Vec<K> {
1080 fn len(&self) -> usize {
1081 self.len()
1082 }
1083}
1084
1085//%% k0_list %%vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
1086
1087impl k0_list {
1088 pub(crate) fn new<T>(array: T) -> Self
1089 where
1090 T: k0_list_inner,
1091 {
1092 k0_list {
1093 n: array.len() as J,
1094 G0: Box::new(array),
1095 }
1096 }
1097}
1098
1099impl Clone for k0_list {
1100 fn clone(&self) -> Self {
1101 // Deref happens here
1102 k0_list {
1103 n: self.n,
1104 G0: self.G0.clone_box(),
1105 }
1106 }
1107}
1108
1109//%% K %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
1110
1111impl K {
1112 // Constructor //----------------------------/
1113
1114 /// Base constructor of `K`.
1115 pub(crate) fn new(qtype: i8, attribute: i8, inner: k0_inner) -> Self {
1116 K(Box::new(k0 {
1117 qtype: qtype,
1118 attribute: attribute,
1119 value: inner,
1120 }))
1121 }
1122
1123 /// Construct q bool from `bool`.
1124 /// # Example
1125 /// ```
1126 /// use kdbplus::ipc::*;
1127 ///
1128 /// fn main() {
1129 /// let q_bool_false = K::new_bool(false);
1130 /// assert_eq!(format!("{}", q_bool_false), String::from("0b"));
1131 /// }
1132 /// ```
1133 pub fn new_bool(boolean: bool) -> Self {
1134 K::new(
1135 qtype::BOOL_ATOM,
1136 qattribute::NONE,
1137 k0_inner::byte(boolean as u8),
1138 )
1139 }
1140
1141 /// Construct q GUID from `[u8; 16]`.
1142 /// # Example
1143 /// ```
1144 /// use kdbplus::ipc::*;
1145 ///
1146 /// fn main() {
1147 /// let q_guid = K::new_guid([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
1148 /// assert_eq!(
1149 /// format!("{}", q_guid),
1150 /// String::from("01020304-0506-0708-090a-0b0c0d0e0f10")
1151 /// );
1152 /// }
1153 /// ```
1154 pub fn new_guid(guid: [G; 16]) -> Self {
1155 K::new(qtype::GUID_ATOM, qattribute::NONE, k0_inner::guid(guid))
1156 }
1157
1158 /// Construct q byte from `u8`.
1159 /// # Example
1160 /// ```
1161 /// use kdbplus::ipc::*;
1162 ///
1163 /// fn main() {
1164 /// let q_byte = K::new_byte(0x9e);
1165 /// assert_eq!(format!("{}", q_byte), String::from("0x9e"));
1166 /// }
1167 /// ```
1168 pub fn new_byte(byte: u8) -> Self {
1169 K::new(qtype::BYTE_ATOM, qattribute::NONE, k0_inner::byte(byte))
1170 }
1171
1172 /// Construct q short from `i16`.
1173 /// # Example
1174 /// ```
1175 /// use kdbplus::ipc::*;
1176 ///
1177 /// fn main() {
1178 /// let q_short = K::new_short(17);
1179 /// assert_eq!(format!("{}", q_short), String::from("17h"));
1180 /// }
1181 /// ```
1182 pub fn new_short(short: i16) -> Self {
1183 K::new(qtype::SHORT_ATOM, qattribute::NONE, k0_inner::short(short))
1184 }
1185
1186 /// Construct q int from `i32`.
1187 /// # Example
1188 /// ```
1189 /// use kdbplus::ipc::*;
1190 ///
1191 /// fn main() {
1192 /// let q_int = K::new_int(-256);
1193 /// assert_eq!(format!("{}", q_int), String::from("-256i"));
1194 /// }
1195 /// ```
1196 pub fn new_int(int: i32) -> Self {
1197 K::new(qtype::INT_ATOM, qattribute::NONE, k0_inner::int(int))
1198 }
1199
1200 /// Construct q long from `i64`.
1201 /// # Example
1202 /// ```
1203 /// use kdbplus::ipc::*;
1204 ///
1205 /// fn main() {
1206 /// let q_long = K::new_long(86400000000000);
1207 /// assert_eq!(format!("{}", q_long), String::from("86400000000000"));
1208 /// }
1209 /// ```
1210 pub fn new_long(long: i64) -> Self {
1211 K::new(qtype::LONG_ATOM, qattribute::NONE, k0_inner::long(long))
1212 }
1213
1214 /// Construct q real from `f32`.
1215 /// # Example
1216 /// ```
1217 /// use kdbplus::ipc::*;
1218 ///
1219 /// fn main() {
1220 /// let q_real = K::new_real(0.25);
1221 /// assert_eq!(format!("{:.2}", q_real), String::from("0.25e"));
1222 /// }
1223 /// ```
1224 pub fn new_real(real: f32) -> Self {
1225 K::new(qtype::REAL_ATOM, qattribute::NONE, k0_inner::real(real))
1226 }
1227
1228 /// Construct q float from `f64`.
1229 /// # Example
1230 /// ```
1231 /// use kdbplus::ipc::*;
1232 ///
1233 /// fn main() {
1234 /// let q_float = K::new_float(113.0456);
1235 /// assert_eq!(format!("{:.7}", q_float), String::from("113.0456000"));
1236 /// }
1237 /// ```
1238 pub fn new_float(float: f64) -> Self {
1239 K::new(qtype::FLOAT_ATOM, qattribute::NONE, k0_inner::float(float))
1240 }
1241
1242 /// Construct q char from `char`.
1243 /// # Example
1244 /// ```
1245 /// use kdbplus::ipc::*;
1246 ///
1247 /// fn main() {
1248 /// let q_char = K::new_char('r');
1249 /// assert_eq!(format!("{}", q_char), String::from("\"r\""));
1250 /// }
1251 /// ```
1252 pub fn new_char(character: char) -> Self {
1253 K::new(
1254 qtype::CHAR,
1255 qattribute::NONE,
1256 k0_inner::byte(character as G),
1257 )
1258 }
1259
1260 /// Construct q symbol from `String`.
1261 /// # Example
1262 /// ```
1263 /// use kdbplus::ipc::*;
1264 ///
1265 /// fn main() {
1266 /// let q_symbol = K::new_symbol(String::from("Jordan"));
1267 /// assert_eq!(format!("{}", q_symbol), String::from("`Jordan"));
1268 /// }
1269 /// ```
1270 pub fn new_symbol(symbol: String) -> Self {
1271 K::new(
1272 qtype::SYMBOL_ATOM,
1273 qattribute::NONE,
1274 k0_inner::symbol(symbol),
1275 )
1276 }
1277
1278 /// Construct q timestamp from `DateTime<Utc>`. If the `DateTime` value is not between
1279 /// 1677-09-21T00:12:43.145224192 and 2262-04-11T23:47:16.854775807, it returns `0Np` in q/kdb+.
1280 /// # Note
1281 /// For the range of valid `DateTime`, see [`chrono`](https://docs.rs/chrono/latest/chrono/struct.DateTime.html#method.timestamp_nanos).
1282 /// # Example
1283 /// ```
1284 /// use kdbplus::ipc::*;
1285 /// use chrono::prelude::*;
1286 ///
1287 /// fn main() {
1288 /// let q_timestamp = K::new_timestamp(
1289 /// NaiveDate::from_ymd_opt(2019, 5, 9)
1290 /// .unwrap()
1291 /// .and_hms_nano_opt(0, 39, 2, 194756)
1292 /// .unwrap()
1293 /// .and_local_timezone(Utc)
1294 /// .unwrap(),
1295 /// );
1296 /// assert_eq!(
1297 /// format!("{}", q_timestamp),
1298 /// String::from("2019.05.09D00:39:02.000194756")
1299 /// );
1300 /// }
1301 /// ```
1302 pub fn new_timestamp(timestamp: DateTime<Utc>) -> Self {
1303 K::new(
1304 qtype::TIMESTAMP_ATOM,
1305 qattribute::NONE,
1306 k0_inner::long(datetime_to_q_timestamp(timestamp)),
1307 )
1308 }
1309
1310 /// Construct q month from `Date<Utc>`.
1311 /// # Example
1312 /// ```
1313 /// use kdbplus::ipc::*;
1314 /// use chrono::prelude::*;
1315 ///
1316 /// fn main() {
1317 /// let q_month = K::new_month(NaiveDate::from_ymd_opt(2019, 12, 15).unwrap());
1318 /// assert_eq!(format!("{}", q_month), String::from("2019.12m"));
1319 /// }
1320 /// ```
1321 pub fn new_month(month: NaiveDate) -> Self {
1322 K::new(
1323 qtype::MONTH_ATOM,
1324 qattribute::NONE,
1325 k0_inner::int(date_to_q_month(month)),
1326 )
1327 }
1328
1329 /// Construct q date from `Date<Utc>`.
1330 /// # Example
1331 /// ```
1332 /// use kdbplus::ipc::*;
1333 /// use chrono::prelude::*;
1334 ///
1335 /// fn main() {
1336 /// let q_date = K::new_date(NaiveDate::from_ymd_opt(2012, 3, 12).unwrap());
1337 /// assert_eq!(format!("{}", q_date), String::from("2012.03.12"));
1338 /// }
1339 /// ```
1340 pub fn new_date(date: NaiveDate) -> Self {
1341 K::new(
1342 qtype::DATE_ATOM,
1343 qattribute::NONE,
1344 k0_inner::int(date_to_q_date(date)),
1345 )
1346 }
1347
1348 /// Construct q datetime from `DateTime<Utc>`.
1349 /// # Example
1350 /// ```
1351 /// use kdbplus::ipc::*;
1352 /// use chrono::prelude::*;
1353 ///
1354 /// fn main() {
1355 /// let q_datetime = K::new_datetime(
1356 /// NaiveDate::from_ymd_opt(2013, 1, 10)
1357 /// .unwrap()
1358 /// .and_hms_milli_opt(0, 9, 50, 38)
1359 /// .unwrap()
1360 /// .and_local_timezone(Utc)
1361 /// .unwrap(),
1362 /// );
1363 /// assert_eq!(
1364 /// format!("{}", q_datetime),
1365 /// String::from("2013.01.10T00:09:50.038")
1366 /// );
1367 /// }
1368 /// ```
1369 pub fn new_datetime(datetime: DateTime<Utc>) -> Self {
1370 K::new(
1371 qtype::DATETIME_ATOM,
1372 qattribute::NONE,
1373 k0_inner::float(datetime_to_q_datetime(datetime)),
1374 )
1375 }
1376
1377 /// Construct q timespan from `Duration`.
1378 /// # Example
1379 /// ```
1380 /// use kdbplus::ipc::*;
1381 /// use chrono::Duration;
1382 ///
1383 /// fn main() {
1384 /// let q_timespan = K::new_timespan(Duration::nanoseconds(102899277539844));
1385 /// assert_eq!(
1386 /// format!("{}", q_timespan),
1387 /// String::from("1D04:34:59.277539844")
1388 /// );
1389 /// }
1390 /// ```
1391 pub fn new_timespan(duration: Duration) -> Self {
1392 K::new(
1393 qtype::TIMESPAN_ATOM,
1394 qattribute::NONE,
1395 k0_inner::long(duration.num_nanoseconds().expect("duration overflow")),
1396 )
1397 }
1398
1399 /// Construct q minute from `Duration`.
1400 /// # Example
1401 /// ```
1402 /// use kdbplus::ipc::*;
1403 /// use chrono::Duration;
1404 ///
1405 /// fn main() {
1406 /// let q_minute = K::new_minute(Duration::minutes(99));
1407 /// assert_eq!(format!("{}", q_minute), String::from("01:39"));
1408 /// }
1409 /// ```
1410 pub fn new_minute(minute: Duration) -> Self {
1411 K::new(
1412 qtype::MINUTE_ATOM,
1413 qattribute::NONE,
1414 k0_inner::int(minute.num_minutes() as i32),
1415 )
1416 }
1417
1418 /// Construct q second from `Duration`.
1419 /// # Example
1420 /// ```
1421 /// use kdbplus::ipc::*;
1422 /// use chrono::Duration;
1423 ///
1424 /// fn main() {
1425 /// let q_second = K::new_second(Duration::seconds(3702));
1426 /// assert_eq!(format!("{}", q_second), String::from("01:01:42"));
1427 /// }
1428 /// ```
1429 pub fn new_second(second: Duration) -> Self {
1430 K::new(
1431 qtype::SECOND_ATOM,
1432 qattribute::NONE,
1433 k0_inner::int(second.num_seconds() as i32),
1434 )
1435 }
1436
1437 /// Construct q time from `Duration`.
1438 /// # Example
1439 /// ```
1440 /// use kdbplus::ipc::*;
1441 /// use chrono::Duration;
1442 ///
1443 /// fn main() {
1444 /// let q_time = K::new_time(Duration::milliseconds(27843489));
1445 /// assert_eq!(format!("{}", q_time), String::from("07:44:03.489"));
1446 /// }
1447 /// ```
1448 pub fn new_time(time: Duration) -> Self {
1449 K::new(
1450 qtype::TIME_ATOM,
1451 qattribute::NONE,
1452 k0_inner::int(time.num_milliseconds() as i32),
1453 )
1454 }
1455
1456 /// Construct q bool list from `Vec<bool>`.
1457 /// # Example
1458 /// ```
1459 /// use kdbplus::qattribute;
1460 /// use kdbplus::ipc::*;
1461 ///
1462 /// fn main() {
1463 /// let q_bool_list = K::new_bool_list(vec![true, false, true], qattribute::NONE);
1464 /// assert_eq!(format!("{}", q_bool_list), String::from("101b"));
1465 /// }
1466 /// ```
1467 pub fn new_bool_list(list: Vec<bool>, attribute: i8) -> Self {
1468 let array = list
1469 .into_iter()
1470 .map(|element| match element {
1471 true => 1,
1472 false => 0,
1473 })
1474 .collect::<Vec<G>>();
1475
1476 K::new(
1477 qtype::BOOL_LIST,
1478 attribute,
1479 k0_inner::list(k0_list::new(array)),
1480 )
1481 }
1482
1483 /// Construct q GUID list from `Vec<U>`.
1484 /// # Example
1485 /// ```
1486 /// use kdbplus::qattribute;
1487 /// use kdbplus::ipc::*;
1488 ///
1489 /// fn main() {
1490 /// let q_guid_list = K::new_guid_list(
1491 /// vec![
1492 /// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
1493 /// [
1494 /// 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
1495 /// ],
1496 /// ],
1497 /// qattribute::NONE,
1498 /// );
1499 /// assert_eq!(
1500 /// format!("{}", q_guid_list),
1501 /// String::from(
1502 /// "00010203-0405-0607-0809-0a0b0c0d0e0f f0f1f2f3-f4f5-f6f7-f8f9-fafbfcfdfeff"
1503 /// )
1504 /// );
1505 /// }
1506 /// ```
1507 pub fn new_guid_list(list: Vec<[u8; 16]>, attribute: i8) -> Self {
1508 K::new(
1509 qtype::GUID_LIST,
1510 attribute,
1511 k0_inner::list(k0_list::new(list)),
1512 )
1513 }
1514
1515 /// Construct q byte list from `Vec<G>`.
1516 /// # Example
1517 /// ```
1518 /// use kdbplus::qattribute;
1519 /// use kdbplus::ipc::*;
1520 ///
1521 /// fn main() {
1522 /// let q_byte_list = K::new_byte_list(vec![7, 12, 21, 144], qattribute::NONE);
1523 /// assert_eq!(format!("{}", q_byte_list), String::from("0x070c1590"));
1524 /// }
1525 /// ```
1526 pub fn new_byte_list(list: Vec<u8>, attribute: i8) -> Self {
1527 K::new(
1528 qtype::BYTE_LIST,
1529 attribute,
1530 k0_inner::list(k0_list::new(list)),
1531 )
1532 }
1533
1534 /// Construct q short list from `Vec<H>`.
1535 /// # Example
1536 /// ```
1537 /// use kdbplus::qattribute;
1538 /// use kdbplus::ipc::*;
1539 ///
1540 /// fn main() {
1541 /// let q_short_list =
1542 /// K::new_short_list(vec![qnull::SHORT, -7, 12, 21, 144], qattribute::SORTED);
1543 /// assert_eq!(
1544 /// format!("{}", q_short_list),
1545 /// String::from("`s#0N -7 12 21 144h")
1546 /// );
1547 /// }
1548 /// ```
1549 pub fn new_short_list(list: Vec<i16>, attribute: i8) -> Self {
1550 K::new(
1551 qtype::SHORT_LIST,
1552 attribute,
1553 k0_inner::list(k0_list::new(list)),
1554 )
1555 }
1556
1557 /// Construct q int list from `Vec<I>`.
1558 /// # Example
1559 /// ```
1560 /// use kdbplus::qattribute;
1561 /// use kdbplus::ipc::*;
1562 ///
1563 /// fn main() {
1564 /// let q_int_list = K::new_int_list(
1565 /// vec![-10000, -10000, 21, 21, qinf::INT, 144000],
1566 /// qattribute::PARTED,
1567 /// );
1568 /// assert_eq!(
1569 /// format!("{}", q_int_list),
1570 /// String::from("`p#-10000 -10000 21 21 0W 144000i")
1571 /// );
1572 /// }
1573 /// ```
1574 pub fn new_int_list(list: Vec<i32>, attribute: i8) -> Self {
1575 K::new(
1576 qtype::INT_LIST,
1577 attribute,
1578 k0_inner::list(k0_list::new(list)),
1579 )
1580 }
1581
1582 /// Construct q long list from `Vec<J>`.
1583 /// # Example
1584 /// ```
1585 /// use kdbplus::qattribute;
1586 /// use kdbplus::ipc::*;
1587 ///
1588 /// fn main() {
1589 /// let q_long_list = K::new_long_list(vec![-86400000000000], qattribute::UNIQUE);
1590 /// assert_eq!(
1591 /// format!("{}", q_long_list),
1592 /// String::from("`u#,-86400000000000")
1593 /// );
1594 /// }
1595 /// ```
1596 pub fn new_long_list(list: Vec<i64>, attribute: i8) -> Self {
1597 K::new(
1598 qtype::LONG_LIST,
1599 attribute,
1600 k0_inner::list(k0_list::new(list)),
1601 )
1602 }
1603
1604 /// Construct q real list from `Vec<E>`.
1605 /// # Example
1606 /// ```
1607 /// use kdbplus::qattribute;
1608 /// use kdbplus::ipc::*;
1609 ///
1610 /// fn main() {
1611 /// let q_real_list = K::new_real_list(vec![30.2, 5.002], qattribute::NONE);
1612 /// assert_eq!(format!("{:.3}", q_real_list), String::from("30.200 5.002e"));
1613 /// }
1614 /// ```
1615 pub fn new_real_list(list: Vec<f32>, attribute: i8) -> Self {
1616 K::new(
1617 qtype::REAL_LIST,
1618 attribute,
1619 k0_inner::list(k0_list::new(list)),
1620 )
1621 }
1622
1623 /// Construct q float list from `Vec<F>`.
1624 /// # Example
1625 /// ```
1626 /// use kdbplus::qattribute;
1627 /// use kdbplus::ipc::*;
1628 ///
1629 /// fn main() {
1630 /// let q_float_list = K::new_float_list(
1631 /// vec![100.23, 0.4268, qnull::FLOAT, 15.882, qninf::FLOAT],
1632 /// qattribute::NONE,
1633 /// );
1634 /// assert_eq!(
1635 /// format!("{}", q_float_list),
1636 /// String::from("100.23 0.4268 0n 15.882 -0w")
1637 /// );
1638 /// }
1639 /// ```
1640 pub fn new_float_list(list: Vec<f64>, attribute: i8) -> Self {
1641 K::new(
1642 qtype::FLOAT_LIST,
1643 attribute,
1644 k0_inner::list(k0_list::new(list)),
1645 )
1646 }
1647
1648 /// Construct q string from `String`.
1649 /// # Example
1650 /// ```
1651 /// use kdbplus::qattribute;
1652 /// use kdbplus::ipc::*;
1653 ///
1654 /// fn main() {
1655 /// let q_string = K::new_string(String::from("super"), qattribute::UNIQUE);
1656 /// assert_eq!(format!("{}", q_string), String::from("`u#\"super\""));
1657 /// }
1658 /// ```
1659 /// # Note
1660 /// q string must be accessed with `as_string` or `as_mut_string`.
1661 pub fn new_string(string: String, attribute: i8) -> Self {
1662 K::new(qtype::STRING, attribute, k0_inner::symbol(string))
1663 }
1664
1665 /// Construct q symbol list from `Vec<String>`.
1666 /// # Example
1667 /// ```
1668 /// use kdbplus::qattribute;
1669 /// use kdbplus::ipc::*;
1670 ///
1671 /// fn main() {
1672 /// let q_symbol_list = K::new_symbol_list(
1673 /// vec![
1674 /// String::from("a"),
1675 /// String::from("b"),
1676 /// String::from("a"),
1677 /// String::from("c"),
1678 /// ],
1679 /// qattribute::GROUPED,
1680 /// );
1681 /// assert_eq!(format!("{}", q_symbol_list), String::from("`g#`a`b`a`c"));
1682 /// }
1683 /// ```
1684 pub fn new_symbol_list(list: Vec<String>, attribute: i8) -> Self {
1685 K::new(
1686 qtype::SYMBOL_LIST,
1687 attribute,
1688 k0_inner::list(k0_list::new(list)),
1689 )
1690 }
1691
1692 /// Construct q timestamp list from `Vec<DateTime<Utc>>`. If the `DateTime` value is not between
1693 /// 1677-09-21T00:12:43.145224192 and 2262-04-11T23:47:16.854775807, it returns `0Np` in q/kdb+.
1694 /// # Note
1695 /// For the range of valid `DateTime`, see [`chrono`](https://docs.rs/chrono/latest/chrono/struct.DateTime.html#method.timestamp_nanos).
1696 /// # Example
1697 /// ```
1698 /// use kdbplus::qattribute;
1699 /// use kdbplus::ipc::*;
1700 /// use chrono::prelude::*;
1701 ///
1702 /// fn main() {
1703 /// let q_timestamp_list = K::new_timestamp_list(
1704 /// vec![
1705 /// *qnull::TIMESTAMP,
1706 /// NaiveDate::from_ymd_opt(2000, 2, 6)
1707 /// .unwrap()
1708 /// .and_hms_nano_opt(5, 11, 28, 4032)
1709 /// .unwrap()
1710 /// .and_local_timezone(Utc)
1711 /// .unwrap(),
1712 /// *qinf::TIMESTAMP,
1713 /// ],
1714 /// qattribute::NONE,
1715 /// );
1716 /// assert_eq!(
1717 /// format!("{}", q_timestamp_list),
1718 /// String::from("0N 2000.02.06D05:11:28.000004032 0Wp")
1719 /// );
1720 /// }
1721 /// ```
1722 pub fn new_timestamp_list(list: Vec<DateTime<Utc>>, attribute: i8) -> Self {
1723 let array = list
1724 .into_iter()
1725 .map(|datetime| datetime_to_q_timestamp(datetime))
1726 .collect::<Vec<J>>();
1727 K::new(
1728 qtype::TIMESTAMP_LIST,
1729 attribute,
1730 k0_inner::list(k0_list::new(array)),
1731 )
1732 }
1733
1734 /// Construct q month list from `Vec<Date<Utc>>`.
1735 /// # Example
1736 /// ```
1737 /// use kdbplus::qattribute;
1738 /// use kdbplus::ipc::*;
1739 /// use chrono::prelude::*;
1740 ///
1741 /// fn main() {
1742 /// let q_month_list = K::new_month_list(
1743 /// vec![
1744 /// NaiveDate::from_ymd_opt(2006, 3, 9).unwrap(),
1745 /// NaiveDate::from_ymd_opt(1999, 5, 31).unwrap(),
1746 /// qnull::MONTH,
1747 /// ],
1748 /// qattribute::NONE,
1749 /// );
1750 /// assert_eq!(
1751 /// format!("{}", q_month_list),
1752 /// String::from("2006.03 1999.05 0Nm")
1753 /// );
1754 /// }
1755 /// ```
1756 pub fn new_month_list(list: Vec<NaiveDate>, attribute: i8) -> Self {
1757 let array = list
1758 .into_iter()
1759 .map(|date| date_to_q_month(date))
1760 .collect::<Vec<I>>();
1761 K::new(
1762 qtype::MONTH_LIST,
1763 attribute,
1764 k0_inner::list(k0_list::new(array)),
1765 )
1766 }
1767
1768 /// Construct q date list from `Vec<Date<Utc>>`.
1769 /// # Example
1770 /// ```
1771 /// use kdbplus::qattribute;
1772 /// use kdbplus::ipc::*;
1773 /// use chrono::prelude::*;
1774 ///
1775 /// fn main() {
1776 /// let q_date_list = K::new_date_list(
1777 /// vec![
1778 /// NaiveDate::from_ymd_opt(2001, 2, 18).unwrap(),
1779 /// NaiveDate::from_ymd_opt(2019, 12, 12).unwrap(),
1780 /// qinf::DATE,
1781 /// NaiveDate::from_ymd_opt(2003, 10, 16).unwrap(),
1782 /// ],
1783 /// qattribute::NONE,
1784 /// );
1785 /// assert_eq!(
1786 /// format!("{}", q_date_list),
1787 /// String::from("2001.02.18 2019.12.12 0W 2003.10.16")
1788 /// );
1789 /// }
1790 /// ```
1791 pub fn new_date_list(list: Vec<NaiveDate>, attribute: i8) -> Self {
1792 let array = list
1793 .into_iter()
1794 .map(|date| date_to_q_date(date))
1795 .collect::<Vec<I>>();
1796 K::new(
1797 qtype::DATE_LIST,
1798 attribute,
1799 k0_inner::list(k0_list::new(array)),
1800 )
1801 }
1802
1803 /// Construct q datetime list from `Vec<DateTime<Utc>>`.
1804 /// # Example
1805 /// ```
1806 /// use kdbplus::qattribute;
1807 /// use kdbplus::ipc::*;
1808 /// use chrono::prelude::*;
1809 ///
1810 /// fn main() {
1811 /// let q_datetime_list = K::new_datetime_list(
1812 /// vec![
1813 /// NaiveDate::from_ymd_opt(2002, 1, 26)
1814 /// .unwrap()
1815 /// .and_hms_nano_opt(9, 39, 2, 368376238)
1816 /// .unwrap()
1817 /// .and_local_timezone(Utc)
1818 /// .unwrap(),
1819 /// *qinf::DATETIME,
1820 /// ],
1821 /// qattribute::SORTED,
1822 /// );
1823 /// assert_eq!(
1824 /// format!("{}", q_datetime_list),
1825 /// String::from("`s#2002.01.26T09:39:02.368 0Wz")
1826 /// );
1827 /// }
1828 /// ```
1829 pub fn new_datetime_list(list: Vec<DateTime<Utc>>, attribute: i8) -> Self {
1830 let array = list
1831 .into_iter()
1832 .map(|datetime| datetime_to_q_datetime(datetime))
1833 .collect::<Vec<F>>();
1834 K::new(
1835 qtype::DATETIME_LIST,
1836 attribute,
1837 k0_inner::list(k0_list::new(array)),
1838 )
1839 }
1840
1841 /// Construct q timespan list from `Vec<Duration>`.
1842 /// # Example
1843 /// ```
1844 /// use kdbplus::qattribute;
1845 /// use kdbplus::ipc::*;
1846 /// use chrono::Duration;
1847 ///
1848 /// fn main() {
1849 /// let q_timespan_list = K::new_timespan_list(
1850 /// vec![
1851 /// *qinf::TIMESPAN,
1852 /// Duration::nanoseconds(7240514990625504),
1853 /// Duration::nanoseconds(-107695363440640000),
1854 /// ],
1855 /// qattribute::NONE,
1856 /// );
1857 /// assert_eq!(
1858 /// format!("{}", q_timespan_list),
1859 /// String::from("0W 83D19:15:14.990625504 -1246D11:22:43.440640000")
1860 /// );
1861 /// }
1862 /// ```
1863 pub fn new_timespan_list(list: Vec<Duration>, attribute: i8) -> Self {
1864 let array = list
1865 .into_iter()
1866 .map(|duration| duration.num_nanoseconds().expect("duration overflow"))
1867 .collect::<Vec<J>>();
1868 K::new(
1869 qtype::TIMESPAN_LIST,
1870 attribute,
1871 k0_inner::list(k0_list::new(array)),
1872 )
1873 }
1874
1875 /// Construct q minute list from `Vec<Duration>`.
1876 /// # Example
1877 /// ```
1878 /// use kdbplus::qattribute;
1879 /// use kdbplus::ipc::*;
1880 /// use chrono::Duration;
1881 ///
1882 /// fn main() {
1883 /// let q_minute_list = K::new_minute_list(
1884 /// vec![Duration::minutes(504), Duration::seconds(-100)],
1885 /// qattribute::NONE,
1886 /// );
1887 /// assert_eq!(format!("{}", q_minute_list), String::from("08:24 -00:01"));
1888 /// }
1889 /// ```
1890 pub fn new_minute_list(list: Vec<Duration>, attribute: i8) -> Self {
1891 let array = list
1892 .into_iter()
1893 .map(|duration| duration.num_minutes() as i32)
1894 .collect::<Vec<I>>();
1895 K::new(
1896 qtype::MINUTE_LIST,
1897 attribute,
1898 k0_inner::list(k0_list::new(array)),
1899 )
1900 }
1901
1902 /// Construct q second list from `Vec<Duration>`.
1903 /// # Example
1904 /// ```
1905 /// use kdbplus::qattribute;
1906 /// use kdbplus::ipc::*;
1907 /// use chrono::Duration;
1908 ///
1909 /// fn main() {
1910 /// let q_second_list = K::new_second_list(
1911 /// vec![
1912 /// Duration::seconds(-3554),
1913 /// *qinf::SECOND,
1914 /// Duration::seconds(13744),
1915 /// *qninf::SECOND,
1916 /// *qnull::SECOND,
1917 /// ],
1918 /// qattribute::NONE,
1919 /// );
1920 /// assert_eq!(
1921 /// format!("{}", q_second_list),
1922 /// String::from("-00:59:14 0W 03:49:04 -0W 0Nv")
1923 /// );
1924 /// }
1925 /// ```
1926 pub fn new_second_list(list: Vec<Duration>, attribute: i8) -> Self {
1927 let array = list
1928 .into_iter()
1929 .map(|duration| duration.num_seconds() as i32)
1930 .collect::<Vec<I>>();
1931 K::new(
1932 qtype::SECOND_LIST,
1933 attribute,
1934 k0_inner::list(k0_list::new(array)),
1935 )
1936 }
1937
1938 /// Construct q time list from `Vec<Duration>`.
1939 /// # Example
1940 /// ```
1941 /// use kdbplus::qattribute;
1942 /// use kdbplus::ipc::*;
1943 /// use chrono::Duration;
1944 ///
1945 /// fn main() {
1946 /// let q_time_list = K::new_time_list(
1947 /// vec![
1948 /// Duration::milliseconds(642982),
1949 /// Duration::milliseconds(789848),
1950 /// *qninf::TIME,
1951 /// Duration::milliseconds(58725553),
1952 /// ],
1953 /// qattribute::NONE,
1954 /// );
1955 /// assert_eq!(
1956 /// format!("{}", q_time_list),
1957 /// String::from("00:10:42.982 00:13:09.848 -0W 16:18:45.553")
1958 /// );
1959 /// }
1960 /// ```
1961 pub fn new_time_list(list: Vec<Duration>, attribute: i8) -> Self {
1962 let array = list
1963 .into_iter()
1964 .map(|duration| duration.num_milliseconds() as i32)
1965 .collect::<Vec<I>>();
1966 K::new(
1967 qtype::TIME_LIST,
1968 attribute,
1969 k0_inner::list(k0_list::new(array)),
1970 )
1971 }
1972
1973 /// Construct q compound list from `Vec<K>`.
1974 /// # Example
1975 /// ```
1976 /// use kdbplus::qattribute;
1977 /// use kdbplus::ipc::*;
1978 /// use chrono::prelude::*;
1979 ///
1980 /// fn main() {
1981 /// let q_compound_list = K::new_compound_list(vec![
1982 /// K::new_symbol_list(
1983 /// vec![
1984 /// String::from("Ruby"),
1985 /// String::from("Diamond"),
1986 /// String::from("Sapphire"),
1987 /// ],
1988 /// qattribute::UNIQUE,
1989 /// ),
1990 /// K::new_timestamp(*qnull::TIMESTAMP),
1991 /// K::new_long_list(vec![0, 1, 2, qninf::LONG], qattribute::NONE),
1992 /// K::new_month_list(
1993 /// vec![NaiveDate::from_ymd_opt(2004, 2, 7).unwrap()],
1994 /// qattribute::NONE,
1995 /// ),
1996 /// ]);
1997 /// assert_eq!(
1998 /// format!("{}", q_compound_list),
1999 /// String::from("(`u#`Ruby`Diamond`Sapphire;0Np;0 1 2 -0W;,2004.02m)")
2000 /// );
2001 /// }
2002 /// ```
2003 pub fn new_compound_list(list: Vec<K>) -> Self {
2004 K::new(
2005 qtype::COMPOUND_LIST,
2006 qattribute::NONE,
2007 k0_inner::list(k0_list::new(list)),
2008 )
2009 }
2010
2011 /// Construct q dictionary from a pair of keys (`K`) and values (`K`).
2012 /// # Example
2013 /// ```
2014 /// use kdbplus::qattribute;
2015 /// use kdbplus::ipc::*;
2016 ///
2017 /// fn main() {
2018 /// let keys = K::new_int_list(vec![20, 30, 40], qattribute::SORTED);
2019 /// let values = K::new_bool_list(vec![false, false, true], qattribute::NONE);
2020 /// let q_dictionary = K::new_dictionary(keys, values).unwrap();
2021 /// assert_eq!(
2022 /// format!("{}", q_dictionary),
2023 /// String::from("`s#20 30 40i!001b")
2024 /// );
2025 /// }
2026 /// ```
2027 /// # Note
2028 /// This constructor can return an error object whose type is `qtype::ERROR`. In that case the error message can be
2029 /// retrieved by [`get_symbol`](#fn.get_symbol).
2030 pub fn new_dictionary(keys: K, values: K) -> Result<Self> {
2031 if keys.len() != values.len() {
2032 Err(Error::length_mismatch(keys.len(), values.len()))
2033 } else {
2034 let qtype = if keys.0.attribute == qattribute::SORTED {
2035 qtype::SORTED_DICTIONARY
2036 } else {
2037 qtype::DICTIONARY
2038 };
2039 Ok(K::new(
2040 qtype,
2041 qattribute::NONE,
2042 k0_inner::list(k0_list::new(vec![keys, values])),
2043 ))
2044 }
2045 }
2046
2047 /// Construct q null.
2048 /// # Example
2049 /// ```
2050 /// use kdbplus::ipc::*;
2051 ///
2052 /// fn main() {
2053 /// let q_null = K::new_null();
2054 /// assert_eq!(format!("{}", q_null), String::from("::"));
2055 /// }
2056 /// ```
2057 pub fn new_null() -> Self {
2058 K::new(qtype::NULL, qattribute::NONE, k0_inner::null(()))
2059 }
2060
2061 /// Construct q error object.
2062 /// # Example
2063 /// ```
2064 /// use kdbplus::ipc::*;
2065 ///
2066 /// fn main(){
2067 /// let q_error=K::new_error(String::from("woops"));
2068 /// assert_eq!(format!("{}", q_error), String::from("'woops"));
2069 /// }
2070 /// ```
2071 pub fn new_error(error: String) -> Self {
2072 K::new(qtype::ERROR, qattribute::NONE, k0_inner::symbol(error))
2073 }
2074
2075 // Getter //---------------------------------/
2076
2077 /// Get underlying `bool` value.
2078 /// # Example
2079 /// ```
2080 /// use kdbplus::ipc::*;
2081 ///
2082 /// fn main() {
2083 /// let q_bool = K::new_bool(true);
2084 /// assert_eq!(q_bool.get_bool(), Ok(true));
2085 /// }
2086 /// ```
2087 pub fn get_bool(&self) -> Result<bool> {
2088 match self.0.qtype {
2089 qtype::BOOL_ATOM => match self.0.value {
2090 k0_inner::byte(boolean) => Ok(boolean != 0),
2091 _ => unreachable!(),
2092 },
2093 _ => Err(Error::invalid_cast(self.0.qtype, qtype::BOOL_ATOM)),
2094 }
2095 }
2096
2097 /// Get underlying `[u8; 16]` value.
2098 /// # Example
2099 /// ```
2100 /// use kdbplus::ipc::*;
2101 ///
2102 /// fn main() {
2103 /// let q_guid = K::new_guid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
2104 /// assert_eq!(
2105 /// q_guid.get_guid(),
2106 /// Ok([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
2107 /// );
2108 /// }
2109 /// ```
2110 pub fn get_guid(&self) -> Result<[u8; 16]> {
2111 match self.0.qtype {
2112 qtype::GUID_ATOM => match self.0.value {
2113 k0_inner::guid(guid) => Ok(guid),
2114 _ => unreachable!(),
2115 },
2116 _ => Err(Error::invalid_cast(self.0.qtype, qtype::GUID_ATOM)),
2117 }
2118 }
2119
2120 /// Get underlying `u8` value. Compatible types are:
2121 /// - bool
2122 /// - byte
2123 /// - char
2124 /// # Example
2125 /// ```
2126 /// use kdbplus::ipc::*;
2127 ///
2128 /// fn main() {
2129 /// let q_byte = K::new_byte(0x77);
2130 /// assert_eq!(q_byte.get_byte(), Ok(0x77));
2131 /// }
2132 /// ```
2133 pub fn get_byte(&self) -> Result<u8> {
2134 match self.0.qtype {
2135 qtype::BOOL_ATOM | qtype::BYTE_ATOM | qtype::CHAR => match self.0.value {
2136 k0_inner::byte(byte) => Ok(byte),
2137 _ => unreachable!(),
2138 },
2139 _ => Err(Error::invalid_cast(self.0.qtype, qtype::BYTE_ATOM)),
2140 }
2141 }
2142
2143 /// Get underlying `i16` value.
2144 /// # Example
2145 /// ```
2146 /// use kdbplus::ipc::*;
2147 ///
2148 /// fn main() {
2149 /// let q_short = K::new_short(-12);
2150 /// assert_eq!(q_short.get_short(), Ok(-12));
2151 /// }
2152 /// ```
2153 pub fn get_short(&self) -> Result<i16> {
2154 match self.0.qtype {
2155 qtype::SHORT_ATOM => match self.0.value {
2156 k0_inner::short(short) => Ok(short),
2157 _ => unreachable!(),
2158 },
2159 _ => Err(Error::invalid_cast(self.0.qtype, qtype::SHORT_ATOM)),
2160 }
2161 }
2162
2163 /// Get underlying `i32` value. Compatible types are:
2164 /// - int
2165 /// - month
2166 /// - date
2167 /// - minute
2168 /// - second
2169 /// - time
2170 /// # Example
2171 /// ```
2172 /// use kdbplus::ipc::*;
2173 ///
2174 /// fn main() {
2175 /// let q_int = K::new_int(144000);
2176 /// assert_eq!(q_int.get_int(), Ok(144000));
2177 /// }
2178 /// ```
2179 pub fn get_int(&self) -> Result<i32> {
2180 match self.0.qtype {
2181 qtype::INT_ATOM
2182 | qtype::MONTH_ATOM
2183 | qtype::DATE_ATOM
2184 | qtype::MINUTE_ATOM
2185 | qtype::SECOND_ATOM
2186 | qtype::TIME_ATOM => match self.0.value {
2187 k0_inner::int(int) => Ok(int),
2188 _ => unreachable!(),
2189 },
2190 _ => Err(Error::invalid_cast(self.0.qtype, qtype::INT_ATOM)),
2191 }
2192 }
2193
2194 /// Get underlying `i64` value. Compatible types are:
2195 /// - long
2196 /// - timestamp
2197 /// - timespan
2198 /// # Example
2199 /// ```
2200 /// use kdbplus::ipc::*;
2201 ///
2202 /// fn main() {
2203 /// let q_long = K::new_long(86400000000000);
2204 /// assert_eq!(q_long.get_long(), Ok(86400000000000));
2205 /// }
2206 /// ```
2207 pub fn get_long(&self) -> Result<i64> {
2208 match self.0.qtype {
2209 qtype::LONG_ATOM | qtype::TIMESTAMP_ATOM | qtype::TIMESPAN_ATOM => match self.0.value {
2210 k0_inner::long(long) => Ok(long),
2211 _ => unreachable!(),
2212 },
2213 _ => Err(Error::invalid_cast(self.0.qtype, qtype::LONG_ATOM)),
2214 }
2215 }
2216
2217 /// Get underlying `f32` value.
2218 /// # Example
2219 /// ```
2220 /// use kdbplus::ipc::*;
2221 ///
2222 /// fn main() {
2223 /// let q_real = K::new_real(0.25);
2224 /// assert_eq!(q_real.get_real(), Ok(0.25));
2225 /// }
2226 /// ```
2227 pub fn get_real(&self) -> Result<f32> {
2228 match self.0.qtype {
2229 qtype::REAL_ATOM => match self.0.value {
2230 k0_inner::real(real) => Ok(real),
2231 _ => unreachable!(),
2232 },
2233 _ => Err(Error::invalid_cast(self.0.qtype, qtype::REAL_ATOM)),
2234 }
2235 }
2236
2237 /// Get underlying `i32` value. Compatible types are:
2238 /// - float
2239 /// - datetime
2240 /// # Example
2241 /// ```
2242 /// use kdbplus::ipc::*;
2243 ///
2244 /// fn main() {
2245 /// let q_float = K::new_float(1000.23456);
2246 /// assert_eq!(q_float.get_float(), Ok(1000.23456));
2247 /// }
2248 /// ```
2249 pub fn get_float(&self) -> Result<f64> {
2250 match self.0.qtype {
2251 qtype::FLOAT_ATOM | qtype::DATETIME_ATOM => match self.0.value {
2252 k0_inner::float(float) => Ok(float),
2253 _ => unreachable!(),
2254 },
2255 _ => Err(Error::invalid_cast(self.0.qtype, qtype::FLOAT_ATOM)),
2256 }
2257 }
2258
2259 /// Get underlying `char` value.
2260 /// # Example
2261 /// ```
2262 /// use kdbplus::ipc::*;
2263 ///
2264 /// fn main() {
2265 /// let q_char = K::new_char('C');
2266 /// assert_eq!(q_char.get_char(), Ok('C'));
2267 /// }
2268 /// ```
2269 pub fn get_char(&self) -> Result<char> {
2270 match self.0.qtype {
2271 qtype::CHAR => match self.0.value {
2272 k0_inner::byte(ch) => Ok(ch as char),
2273 _ => unreachable!(),
2274 },
2275 _ => Err(Error::invalid_cast(self.0.qtype, qtype::CHAR)),
2276 }
2277 }
2278
2279 /// Get underlying `i32` value.
2280 /// # Example
2281 /// ```
2282 /// use kdbplus::ipc::*;
2283 ///
2284 /// fn main() {
2285 /// let q_symbol = K::new_symbol(String::from("Rust"));
2286 /// assert_eq!(q_symbol.get_symbol(), Ok("Rust"));
2287 /// }
2288 /// ```
2289 pub fn get_symbol(&self) -> Result<&str> {
2290 match self.0.qtype {
2291 qtype::SYMBOL_ATOM => match &self.0.value {
2292 k0_inner::symbol(symbol) => Ok(symbol),
2293 _ => unreachable!(),
2294 },
2295 _ => Err(Error::invalid_cast(self.0.qtype, qtype::SYMBOL_ATOM)),
2296 }
2297 }
2298
2299 /// Get underlying timestamp value as `DateTime<Utc>`.
2300 /// # Example
2301 /// ```
2302 /// use kdbplus::ipc::*;
2303 /// use chrono::prelude::*;
2304 ///
2305 /// fn main() {
2306 /// let q_timestamp = K::new_timestamp(
2307 /// NaiveDate::from_ymd_opt(2001, 9, 15)
2308 /// .unwrap()
2309 /// .and_hms_nano_opt(4, 2, 30, 37204)
2310 /// .unwrap()
2311 /// .and_local_timezone(Utc)
2312 /// .unwrap(),
2313 /// );
2314 /// assert_eq!(
2315 /// q_timestamp.get_timestamp(),
2316 /// Ok(NaiveDate::from_ymd_opt(2001, 9, 15)
2317 /// .unwrap()
2318 /// .and_hms_nano_opt(4, 2, 30, 37204)
2319 /// .unwrap()
2320 /// .and_local_timezone(Utc)
2321 /// .unwrap())
2322 /// );
2323 /// }
2324 /// ```
2325 pub fn get_timestamp(&self) -> Result<DateTime<Utc>> {
2326 match self.0.qtype {
2327 qtype::TIMESTAMP_ATOM => match self.0.value {
2328 k0_inner::long(nanos) => Ok(q_timestamp_to_datetime(nanos)),
2329 _ => unreachable!(),
2330 },
2331 _ => Err(Error::invalid_cast(self.0.qtype, qtype::TIMESTAMP_ATOM)),
2332 }
2333 }
2334
2335 /// Get underlying month value as `Date<Utc>`.
2336 /// # Example
2337 /// ```
2338 /// use kdbplus::ipc::*;
2339 /// use chrono::prelude::*;
2340 ///
2341 /// fn main() {
2342 /// let q_month = K::new_month(NaiveDate::from_ymd_opt(2007, 8, 30).unwrap());
2343 /// assert_eq!(
2344 /// q_month.get_month(),
2345 /// Ok(NaiveDate::from_ymd_opt(2007, 8, 1).unwrap())
2346 /// );
2347 /// }
2348 /// ```
2349 pub fn get_month(&self) -> Result<NaiveDate> {
2350 match self.0.qtype {
2351 qtype::MONTH_ATOM => match self.0.value {
2352 k0_inner::int(months) => Ok(q_month_to_date(months)),
2353 _ => unreachable!(),
2354 },
2355 _ => Err(Error::invalid_cast(self.0.qtype, qtype::MONTH_ATOM)),
2356 }
2357 }
2358
2359 /// Get underlying date value as `Date<Utc>`.
2360 /// # Example
2361 /// ```
2362 /// use kdbplus::ipc::*;
2363 /// use chrono::prelude::*;
2364 ///
2365 /// fn main() {
2366 /// let q_date = K::new_date(NaiveDate::from_ymd_opt(2000, 5, 10).unwrap());
2367 /// assert_eq!(
2368 /// q_date.get_date(),
2369 /// Ok(NaiveDate::from_ymd_opt(2000, 5, 10).unwrap())
2370 /// );
2371 /// }
2372 /// ```
2373 pub fn get_date(&self) -> Result<NaiveDate> {
2374 match self.0.qtype {
2375 qtype::DATE_ATOM => match self.0.value {
2376 k0_inner::int(days) => Ok(q_date_to_date(days)?),
2377 _ => unreachable!(),
2378 },
2379 _ => Err(Error::invalid_cast(self.0.qtype, qtype::DATE_ATOM)),
2380 }
2381 }
2382
2383 /// Get underlying datetime value as `DateTime<Utc>`.
2384 /// # Example
2385 /// ```
2386 /// use kdbplus::ipc::*;
2387 /// use chrono::prelude::*;
2388 ///
2389 /// fn main() {
2390 /// let q_datetime = K::new_datetime(
2391 /// NaiveDate::from_ymd_opt(2011, 4, 7)
2392 /// .unwrap()
2393 /// .and_hms_milli_opt(19, 5, 41, 385)
2394 /// .unwrap()
2395 /// .and_local_timezone(Utc)
2396 /// .unwrap(),
2397 /// );
2398 /// assert_eq!(
2399 /// q_datetime.get_datetime(),
2400 /// Ok(NaiveDate::from_ymd_opt(2011, 4, 7)
2401 /// .unwrap()
2402 /// .and_hms_milli_opt(19, 5, 41, 385)
2403 /// .unwrap()
2404 /// .and_local_timezone(Utc)
2405 /// .unwrap())
2406 /// );
2407 /// }
2408 /// ```
2409 pub fn get_datetime(&self) -> Result<DateTime<Utc>> {
2410 match self.0.qtype {
2411 qtype::DATETIME_ATOM => match self.0.value {
2412 k0_inner::float(days) => Ok(q_datetime_to_datetime(days)),
2413 _ => unreachable!(),
2414 },
2415 _ => Err(Error::invalid_cast(self.0.qtype, qtype::DATETIME_ATOM)),
2416 }
2417 }
2418
2419 /// Get underlying timespan value as `Duration`.
2420 /// # Example
2421 /// ```
2422 /// use kdbplus::ipc::*;
2423 /// use chrono::Duration;
2424 ///
2425 /// fn main() {
2426 /// let q_timespan = K::new_timespan(Duration::nanoseconds(131400000000000));
2427 /// assert_eq!(
2428 /// q_timespan.get_timespan(),
2429 /// Ok(Duration::nanoseconds(131400000000000))
2430 /// );
2431 /// }
2432 /// ```
2433 pub fn get_timespan(&self) -> Result<Duration> {
2434 match self.0.qtype {
2435 qtype::TIMESPAN_ATOM => match self.0.value {
2436 k0_inner::long(nanos) => Ok(q_timespan_to_duration(nanos)),
2437 _ => unreachable!(),
2438 },
2439 _ => Err(Error::invalid_cast(self.0.qtype, qtype::TIMESPAN_ATOM)),
2440 }
2441 }
2442
2443 /// Get underlying minute value as `Duration`.
2444 /// # Example
2445 /// ```
2446 /// use kdbplus::ipc::*;
2447 /// use chrono::Duration;
2448 ///
2449 /// fn main() {
2450 /// let q_minute = K::new_minute(Duration::minutes(30));
2451 /// assert_eq!(q_minute.get_minute(), Ok(Duration::minutes(30)));
2452 /// }
2453 /// ```
2454 pub fn get_minute(&self) -> Result<Duration> {
2455 match self.0.qtype {
2456 qtype::MINUTE_ATOM => match self.0.value {
2457 k0_inner::int(minutes) => Ok(q_minute_to_duration(minutes)),
2458 _ => unreachable!(),
2459 },
2460 _ => Err(Error::invalid_cast(self.0.qtype, qtype::MINUTE_ATOM)),
2461 }
2462 }
2463
2464 /// Get underlying second value as `Duration`.
2465 /// # Example
2466 /// ```
2467 /// use kdbplus::ipc::*;
2468 /// use chrono::Duration;
2469 ///
2470 /// fn main() {
2471 /// let q_second = K::new_second(Duration::seconds(30));
2472 /// assert_eq!(q_second.get_second(), Ok(Duration::seconds(30)));
2473 /// }
2474 /// ```
2475 pub fn get_second(&self) -> Result<Duration> {
2476 match self.0.qtype {
2477 qtype::SECOND_ATOM => match self.0.value {
2478 k0_inner::int(seconds) => Ok(q_second_to_duration(seconds)),
2479 _ => unreachable!(),
2480 },
2481 _ => Err(Error::invalid_cast(self.0.qtype, qtype::SECOND_ATOM)),
2482 }
2483 }
2484
2485 /// Get underlying time value as `Duration`.
2486 /// # Example
2487 /// ```
2488 /// use kdbplus::ipc::*;
2489 /// use chrono::Duration;
2490 ///
2491 /// fn main() {
2492 /// let q_time = K::new_time(Duration::milliseconds(3000));
2493 /// assert_eq!(q_time.get_time(), Ok(Duration::milliseconds(3000)));
2494 /// }
2495 /// ```
2496 pub fn get_time(&self) -> Result<Duration> {
2497 match self.0.qtype {
2498 qtype::TIME_ATOM => match self.0.value {
2499 k0_inner::int(millis) => Ok(q_time_to_duration(millis)),
2500 _ => unreachable!(),
2501 },
2502 _ => Err(Error::invalid_cast(self.0.qtype, qtype::TIME_ATOM)),
2503 }
2504 }
2505
2506 /// Get underlying immutable dictionary (flipped table) of table type as `K`.
2507 /// # Example
2508 /// ```
2509 /// use kdbplus::qattribute;
2510 /// use kdbplus::ipc::*;
2511 ///
2512 /// fn main() {
2513 /// let headers = K::new_symbol_list(
2514 /// vec![String::from("fruit"), String::from("price")],
2515 /// qattribute::NONE,
2516 /// );
2517 /// let columns = K::new_compound_list(vec![
2518 /// K::new_symbol_list(
2519 /// vec![
2520 /// String::from("strawberry"),
2521 /// String::from("orange"),
2522 /// qnull::SYMBOL,
2523 /// ],
2524 /// qattribute::PARTED,
2525 /// ),
2526 /// K::new_float_list(vec![2.5, 1.25, 117.8], qattribute::NONE),
2527 /// ]);
2528 /// let q_dictionary = K::new_dictionary(headers, columns).unwrap();
2529 /// let q_table = q_dictionary.flip().unwrap();
2530 /// assert_eq!(
2531 /// format!("{}", q_table.get_dictionary().unwrap()),
2532 /// String::from("`fruit`price!(`p#`strawberry`orange`;2.5 1.25 117.8)")
2533 /// );
2534 /// }
2535 /// ```
2536 pub fn get_dictionary(&self) -> Result<&K> {
2537 match self.0.qtype {
2538 qtype::TABLE => match &self.0.value {
2539 k0_inner::table(dictionary) => Ok(dictionary),
2540 _ => unreachable!(),
2541 },
2542 _ => Err(Error::invalid_cast(self.0.qtype, qtype::TABLE)),
2543 }
2544 }
2545
2546 /// Get underlying mutable dictionary (flipped table) of table type as `K`.
2547 /// # Example
2548 /// ```
2549 /// use kdbplus::qattribute;
2550 /// use kdbplus::ipc::*;
2551 ///
2552 /// fn main() {
2553 /// let headers = K::new_symbol_list(
2554 /// vec![String::from("fruit"), String::from("price")],
2555 /// qattribute::NONE,
2556 /// );
2557 /// let columns = K::new_compound_list(vec![
2558 /// K::new_symbol_list(
2559 /// vec![
2560 /// String::from("strawberry"),
2561 /// String::from("orange"),
2562 /// qnull::SYMBOL,
2563 /// ],
2564 /// qattribute::PARTED,
2565 /// ),
2566 /// K::new_float_list(vec![2.5, 1.25, 117.8], qattribute::NONE),
2567 /// ]);
2568 /// let q_dictionary = K::new_dictionary(headers, columns).unwrap();
2569 /// let mut q_table = q_dictionary.flip().unwrap();
2570 /// let inner = q_table.get_mut_dictionary().unwrap();
2571 ///
2572 /// // modify inner dictionary
2573 /// inner.as_mut_vec::<K>().unwrap()[0]
2574 /// .push(&String::from("color"))
2575 /// .unwrap();
2576 /// inner.as_mut_vec::<K>().unwrap()[1]
2577 /// .push(&K::new_string(String::from("RO"), qattribute::NONE))
2578 /// .unwrap();
2579 ///
2580 /// assert_eq!(
2581 /// format!("{}", q_table),
2582 /// String::from("+`fruit`price`color!(`p#`strawberry`orange`;2.5 1.25 117.8;\"RO\")")
2583 /// );
2584 /// }
2585 /// ```
2586 pub fn get_mut_dictionary(&mut self) -> Result<&mut K> {
2587 match self.0.qtype {
2588 qtype::TABLE => match &mut self.0.value {
2589 k0_inner::table(dictionary) => Ok(dictionary),
2590 _ => unreachable!(),
2591 },
2592 _ => Err(Error::invalid_cast(self.0.qtype, qtype::TABLE)),
2593 }
2594 }
2595
2596 /// Get underlying error value as `String`.
2597 /// # Example
2598 /// ```
2599 /// use kdbplus::ipc::*;
2600 ///
2601 /// #[tokio::main]
2602 /// async fn main() -> Result<()> {
2603 /// let mut socket = QStream::connect(ConnectionMethod::TCP, "localhost", 5000, "kdbuser:pass")
2604 /// .await
2605 /// .expect("Failed to connect");
2606 /// let result = socket.send_sync_message(&"1+`a").await?;
2607 /// assert_eq!(result.get_error_string(), Ok("type"));
2608 /// Ok(())
2609 /// }
2610 /// ```
2611 pub fn get_error_string(&self) -> Result<&str> {
2612 match self.0.qtype {
2613 qtype::ERROR => match &self.0.value {
2614 k0_inner::symbol(error) => Ok(error),
2615 _ => unreachable!(),
2616 },
2617 _ => Err(Error::invalid_cast(self.0.qtype, qtype::ERROR)),
2618 }
2619 }
2620
2621 /// Get underlying immutable `String` value.
2622 /// # Example
2623 /// ```
2624 /// use kdbplus::qattribute;
2625 /// use kdbplus::ipc::*;
2626 ///
2627 /// fn main() {
2628 /// let string = K::new_string(String::from("something"), qattribute::NONE);
2629 /// assert_eq!(string.as_string().unwrap(), "something");
2630 /// }
2631 /// ```
2632 pub fn as_string(&self) -> Result<&str> {
2633 match self.0.qtype {
2634 qtype::STRING => match &self.0.value {
2635 k0_inner::symbol(string) => Ok(string),
2636 _ => unreachable!(),
2637 },
2638 _ => Err(Error::invalid_cast(self.0.qtype, qtype::STRING)),
2639 }
2640 }
2641
2642 /// Get underlying mutable `String` value.
2643 /// # Example
2644 /// ```
2645 /// use kdbplus::qattribute;
2646 /// use kdbplus::ipc::*;
2647 ///
2648 /// fn main() {
2649 /// let mut string = K::new_string(String::from("something"), qattribute::NONE);
2650 /// string.as_mut_string().unwrap().push('!');
2651 /// assert_eq!(format!("{}", string), String::from("\"something!\""));
2652 /// }
2653 /// ```
2654 pub fn as_mut_string(&mut self) -> Result<&mut String> {
2655 match self.0.qtype {
2656 qtype::STRING => match &mut self.0.value {
2657 k0_inner::symbol(string) => Ok(string),
2658 _ => unreachable!(),
2659 },
2660 _ => Err(Error::invalid_cast(self.0.qtype, qtype::STRING)),
2661 }
2662 }
2663
2664 /// Get the underlying mutable vector. If the specified type is wrong, it returns an empty vector.
2665 /// # Example
2666 /// ```
2667 /// use kdbplus::qattribute;
2668 /// use kdbplus::ipc::*;
2669 /// use chrono::prelude::*;
2670 ///
2671 /// fn main() {
2672 /// let mut timestamp_list = K::new_timestamp_list(
2673 /// vec![
2674 /// Utc.ymd(2018, 2, 18).and_hms_nano(4, 0, 0, 100),
2675 /// Utc.ymd(2019, 12, 3).and_hms_nano(4, 5, 10, 3456),
2676 /// ],
2677 /// qattribute::NONE,
2678 /// );
2679 /// timestamp_list
2680 /// .as_mut_vec::<J>()
2681 /// .unwrap()
2682 /// .push(682184439000046395);
2683 /// assert_eq!(format!("{}", timestamp_list), String::from("2018.02.18D04:00:00.000000100 2019.12.03D04:05:10.000003456 2021.08.13D15:40:39.000046395"));
2684 /// }
2685 /// ```
2686 pub fn as_mut_vec<T>(&mut self) -> Result<&mut Vec<T>>
2687 where
2688 T: 'static,
2689 {
2690 match self.0.qtype {
2691 qtype::COMPOUND_LIST
2692 | qtype::BOOL_LIST
2693 | qtype::GUID_LIST
2694 | qtype::BYTE_LIST
2695 | qtype::SHORT_LIST
2696 | qtype::INT_LIST
2697 | qtype::LONG_LIST
2698 | qtype::REAL_LIST
2699 | qtype::FLOAT_LIST
2700 | qtype::SYMBOL_LIST
2701 | qtype::TIMESTAMP_LIST
2702 | qtype::MONTH_LIST
2703 | qtype::DATE_LIST
2704 | qtype::DATETIME_LIST
2705 | qtype::TIMESPAN_LIST
2706 | qtype::MINUTE_LIST
2707 | qtype::SECOND_LIST
2708 | qtype::TIME_LIST
2709 | qtype::DICTIONARY
2710 | qtype::SORTED_DICTIONARY => match &mut self.0.value {
2711 k0_inner::list(list) => match list.G0.as_any_mut().downcast_mut::<Vec<T>>() {
2712 Some(vector) => Ok(vector),
2713 _ => Err(Error::invalid_cast_list(self.0.qtype)),
2714 },
2715 _ => unreachable!(),
2716 },
2717 _ => Err(Error::invalid_cast_list(self.0.qtype)),
2718 }
2719 }
2720
2721 /// Get the underlying immutable vector. If the specified type is wrong, it returns an empty vector.
2722 /// # Example
2723 /// ```
2724 /// use kdbplus::qattribute;
2725 /// use kdbplus::ipc::*;
2726 ///
2727 /// fn main(){
2728 /// let bool_list=K::new_bool_list(vec![true, false], qattribute::UNIQUE);
2729 /// assert_eq!(*bool_list.as_vec::<G>().unwrap(), vec![1_u8, 0]);
2730 /// }
2731 /// ```
2732 pub fn as_vec<T>(&self) -> Result<&Vec<T>>
2733 where
2734 T: 'static,
2735 {
2736 match self.0.qtype {
2737 qtype::COMPOUND_LIST
2738 | qtype::BOOL_LIST
2739 | qtype::GUID_LIST
2740 | qtype::BYTE_LIST
2741 | qtype::SHORT_LIST
2742 | qtype::INT_LIST
2743 | qtype::LONG_LIST
2744 | qtype::REAL_LIST
2745 | qtype::FLOAT_LIST
2746 | qtype::SYMBOL_LIST
2747 | qtype::TIMESTAMP_LIST
2748 | qtype::MONTH_LIST
2749 | qtype::DATE_LIST
2750 | qtype::DATETIME_LIST
2751 | qtype::TIMESPAN_LIST
2752 | qtype::MINUTE_LIST
2753 | qtype::SECOND_LIST
2754 | qtype::TIME_LIST
2755 | qtype::DICTIONARY
2756 | qtype::SORTED_DICTIONARY => match &self.0.value {
2757 k0_inner::list(list) => match list.G0.as_any().downcast_ref::<Vec<T>>() {
2758 Some(vector) => Ok(vector),
2759 _ => Err(Error::invalid_cast_list(self.0.qtype)),
2760 },
2761 _ => unreachable!(),
2762 },
2763 _ => Err(Error::invalid_cast_list(self.0.qtype)),
2764 }
2765 }
2766
2767 /// Get an immutable column of a table with a specified name.
2768 /// # Example
2769 /// ```
2770 /// use kdbplus::qattribute;
2771 /// use kdbplus::ipc::*;
2772 /// use chrono::prelude::*;
2773 ///
2774 /// fn main() {
2775 /// let header = K::new_symbol_list(
2776 /// vec![String::from("time"), String::from("sym")],
2777 /// qattribute::NONE,
2778 /// );
2779 /// let time_column = K::new_timestamp_list(
2780 /// vec![
2781 /// Utc.ymd(2019, 4, 10).and_hms_nano(3, 19, 48, 1234),
2782 /// Utc.ymd(2019, 4, 10).and_hms_nano(3, 21, 30, 948532),
2783 /// ],
2784 /// qattribute::NONE,
2785 /// );
2786 /// let sym_column = K::new_symbol_list(
2787 /// vec![String::from("eggplant"), String::from("tomato")],
2788 /// qattribute::NONE,
2789 /// );
2790 /// let table = K::new_dictionary(header, K::new_compound_list(vec![time_column, sym_column]))
2791 /// .unwrap()
2792 /// .flip()
2793 /// .unwrap();
2794 /// let syms = table.get_column("sym").unwrap();
2795 /// println!("syms: {}", syms);
2796 /// }
2797 /// ```
2798 pub fn get_column<T>(&self, column: T) -> Result<&K>
2799 where
2800 T: ToString,
2801 {
2802 match self.0.qtype {
2803 qtype::TABLE => {
2804 let dictionary = self.get_dictionary().unwrap().as_vec::<K>().unwrap();
2805 match dictionary[0]
2806 .as_vec::<S>()
2807 .unwrap()
2808 .iter()
2809 .position(|name| *name == column.to_string())
2810 {
2811 // It is assured that value is a compound list because this is a table
2812 Some(index) => Ok(&dictionary[1].as_vec::<K>().unwrap()[index]),
2813 _ => Err(Error::no_such_column(column.to_string())),
2814 }
2815 }
2816 qtype::DICTIONARY => {
2817 let key_value = self.as_vec::<K>().unwrap();
2818 if key_value[0].0.qtype == qtype::TABLE {
2819 // Keyed table
2820 if let Ok(found_column) = key_value[0].get_column(column.to_string()) {
2821 // Found in key table
2822 Ok(found_column)
2823 } else if let Ok(found_column) = key_value[1].get_column(column.to_string()) {
2824 // Found in value table
2825 Ok(found_column)
2826 } else {
2827 Err(Error::no_such_column(column.to_string()))
2828 }
2829 } else {
2830 // Not a keyed table
2831 Err(Error::invalid_operation("get_column", self.0.qtype, None))
2832 }
2833 }
2834 _ => Err(Error::invalid_operation("get_column", self.0.qtype, None)),
2835 }
2836 }
2837
2838 /// Get a mutable column of a table with a specified name.
2839 /// # Example
2840 /// ```
2841 /// use kdbplus::qattribute;
2842 /// use kdbplus::ipc::*;
2843 /// use chrono::prelude::*;
2844 ///
2845 /// fn main() {
2846 /// let header = K::new_symbol_list(
2847 /// vec![String::from("time"), String::from("sym")],
2848 /// qattribute::NONE,
2849 /// );
2850 /// let time_column = K::new_timestamp_list(
2851 /// vec![
2852 /// Utc.ymd(2019, 4, 10).and_hms_nano(3, 19, 48, 1234),
2853 /// Utc.ymd(2019, 4, 10).and_hms_nano(3, 21, 30, 948532),
2854 /// ],
2855 /// qattribute::NONE,
2856 /// );
2857 /// let sym_column = K::new_symbol_list(
2858 /// vec![String::from("eggplant"), String::from("tomato")],
2859 /// qattribute::NONE,
2860 /// );
2861 /// let mut table =
2862 /// K::new_dictionary(header, K::new_compound_list(vec![time_column, sym_column]))
2863 /// .unwrap()
2864 /// .flip()
2865 /// .unwrap();
2866 /// let mut syms = table.get_mut_column("sym").unwrap();
2867 /// println!("syms: {}", syms);
2868 /// let _ = std::mem::replace(
2869 /// syms,
2870 /// K::new_symbol_list(
2871 /// vec![String::from("banana"), String::from("strawberry")],
2872 /// qattribute::NONE,
2873 /// ),
2874 /// );
2875 /// println!("table: {}", table);
2876 /// }
2877 /// ```
2878 pub fn get_mut_column<T>(&mut self, column: T) -> Result<&mut K>
2879 where
2880 T: ToString,
2881 {
2882 match self.0.qtype {
2883 qtype::TABLE => {
2884 let dictionary = self
2885 .get_mut_dictionary()
2886 .unwrap()
2887 .as_mut_vec::<K>()
2888 .unwrap();
2889 match dictionary[0]
2890 .as_vec::<S>()
2891 .unwrap()
2892 .iter()
2893 .position(|name| *name == column.to_string())
2894 {
2895 // It is assured that value is a compound list because this is a table
2896 Some(index) => Ok(&mut dictionary[1].as_mut_vec::<K>().unwrap()[index]),
2897 _ => Err(Error::no_such_column(column.to_string())),
2898 }
2899 }
2900 qtype::DICTIONARY => {
2901 let key_value = self.as_vec::<K>().unwrap();
2902 if key_value[0].0.qtype == qtype::TABLE {
2903 // Keyed table
2904 // Search from key table
2905 let mut dictionary = key_value[0]
2906 .get_dictionary()
2907 .unwrap()
2908 .as_vec::<K>()
2909 .unwrap();
2910 if let Some(index) = dictionary[0]
2911 .as_vec::<S>()
2912 .unwrap()
2913 .iter()
2914 .position(|name| *name == column.to_string())
2915 {
2916 // It is assured that value is a compound list because this is a table
2917 return Ok(&mut self.as_mut_vec::<K>().unwrap()[0]
2918 .get_mut_dictionary()
2919 .unwrap()
2920 .as_mut_vec::<K>()
2921 .unwrap()[1]
2922 .as_mut_vec::<K>()
2923 .unwrap()[index]);
2924 }
2925 // Search from value table
2926 dictionary = key_value[1]
2927 .get_dictionary()
2928 .unwrap()
2929 .as_vec::<K>()
2930 .unwrap();
2931 if let Some(index) = dictionary[0]
2932 .as_vec::<S>()
2933 .unwrap()
2934 .iter()
2935 .position(|name| *name == column.to_string())
2936 {
2937 // It is assured that value is a compound list because this is a table
2938 Ok(&mut self.as_mut_vec::<K>().unwrap()[1]
2939 .get_mut_dictionary()
2940 .unwrap()
2941 .as_mut_vec::<K>()
2942 .unwrap()[1]
2943 .as_mut_vec::<K>()
2944 .unwrap()[index])
2945 } else {
2946 Err(Error::no_such_column(column.to_string()))
2947 }
2948 } else {
2949 // Not a keyed table
2950 Err(Error::invalid_operation(
2951 "get_mut_column",
2952 self.0.qtype,
2953 None,
2954 ))
2955 }
2956 }
2957 _ => Err(Error::invalid_operation(
2958 "get_mut_column",
2959 self.0.qtype,
2960 None,
2961 )),
2962 }
2963 }
2964
2965 /// Get a type of q object.
2966 /// # Example
2967 /// ```
2968 /// use kdbplus::*;
2969 /// use kdbplus::ipc::*;
2970 ///
2971 /// fn main() {
2972 /// let q_int = K::new_int(12);
2973 /// assert_eq!(q_int.get_type(), qtype::INT_ATOM);
2974 /// }
2975 /// ```
2976 pub fn get_type(&self) -> i8 {
2977 self.0.qtype
2978 }
2979
2980 /// Get an attribute of q object.
2981 /// # Example
2982 /// ```
2983 /// use kdbplus::qattribute;
2984 /// use kdbplus::ipc::*;
2985 /// use chrono::prelude::*;
2986 ///
2987 /// fn main() {
2988 /// let timestamp_list = K::new_timestamp_list(
2989 /// vec![
2990 /// Utc.ymd(2021, 3, 9).and_hms_nano(12, 5, 40, 67824),
2991 /// Utc.ymd(2021, 3, 13).and_hms_nano(5, 47, 2, 260484387),
2992 /// ],
2993 /// qattribute::SORTED,
2994 /// );
2995 /// assert_eq!(timestamp_list.get_attribute(), qattribute::SORTED);
2996 /// }
2997 /// ```
2998 pub fn get_attribute(&self) -> i8 {
2999 self.0.attribute
3000 }
3001
3002 // Setter //---------------------------------/
3003
3004 /// Set an attribute to the underlying q object.
3005 /// # Example
3006 /// ```
3007 /// use kdbplus::qattribute;
3008 /// use kdbplus::ipc::*;
3009 /// use chrono::prelude::*;
3010 ///
3011 /// fn main() {
3012 /// let mut timestamp_list = K::new_timestamp_list(
3013 /// vec![Utc.ymd(2021, 3, 9).and_hms_nano(12, 5, 40, 67824)],
3014 /// qattribute::NONE,
3015 /// );
3016 /// assert_eq!(timestamp_list.get_attribute(), qattribute::NONE);
3017 /// // Push timestamp
3018 /// timestamp_list
3019 /// .push(&Utc.ymd(2021, 3, 13).and_hms_nano(5, 47, 2, 260484387))
3020 /// .unwrap();
3021 /// timestamp_list.set_attribute(qattribute::SORTED);
3022 /// assert_eq!(timestamp_list.get_attribute(), qattribute::SORTED);
3023 /// }
3024 /// ```
3025 /// # Note
3026 /// The validity of the attribute is not checked. For example, if you set a sorted attribute to
3027 /// an unsorted list, it does not return an error. It will fail in q process.
3028 pub fn set_attribute(&mut self, attribute: i8) {
3029 self.0.attribute = attribute;
3030 }
3031
3032 // Push/Pop //-------------------------------/
3033
3034 /// Increment `n` of `k0_list`.
3035 fn increment(&mut self) {
3036 match &mut self.0.value {
3037 k0_inner::list(list) => list.n += 1,
3038 _ => unreachable!(),
3039 }
3040 }
3041
3042 /// Decrement `n` of `k0_list`.
3043 fn decrement(&mut self) {
3044 match &mut self.0.value {
3045 k0_inner::list(list) => list.n -= 1,
3046 _ => unreachable!(),
3047 }
3048 }
3049
3050 /// Add an element to the tail of the underlying list.
3051 /// # Parameters
3052 /// - `element`: An element to insert. The type needs to be a one used for atom constructor `K::new_*`. For example,
3053 /// int element must be a `i32` type and timestamp element must be a `DateTime<Utc>` type.
3054 /// # Example
3055 /// ```
3056 /// use kdbplus::qattribute;
3057 /// use kdbplus::ipc::*;
3058 ///
3059 /// fn main() {
3060 /// let mut symbol_list = K::new_symbol_list(vec![String::from("first")], qattribute::NONE);
3061 /// symbol_list.push(&String::from("second")).unwrap();
3062 /// if let Err(error) = symbol_list.push(&12) {
3063 /// eprintln!("Oh no!! {}", error);
3064 /// }
3065 /// assert_eq!(
3066 /// *symbol_list.as_vec::<S>().unwrap(),
3067 /// vec![String::from("first"), String::from("second")]
3068 /// );
3069 ///
3070 /// let mut string_list = K::new_compound_list(vec![K::new_string(
3071 /// String::from("string"),
3072 /// qattribute::NONE,
3073 /// )]);
3074 /// string_list.push(&K::new_bool(false)).unwrap();
3075 /// assert_eq!(format!("{}", string_list), String::from("(\"string\";0b)"));
3076 /// }
3077 /// ```
3078 /// # Note
3079 /// If the `DateTime` value for timestamp is not between 1677-09-21T00:12:43.145224192 and 2262-04-11T23:47:16.854775807, it returns `0Np` in q/kdb+.
3080 /// # Note
3081 /// For the range of valid `DateTime`, see [`chrono`](https://docs.rs/chrono/latest/chrono/struct.DateTime.html#method.timestamp_nanos).
3082 pub fn push(&mut self, element: &dyn Any) -> Result<()> {
3083 match self.0.qtype {
3084 qtype::BOOL_LIST => {
3085 if let Some(boolean) = element.downcast_ref::<bool>() {
3086 self.increment();
3087 Ok(self.as_mut_vec::<G>().unwrap().push(*boolean as u8))
3088 } else {
3089 Err(Error::insert_wrong_element(false, qtype::BOOL_LIST, "bool"))
3090 }
3091 }
3092 qtype::GUID_LIST => {
3093 if let Some(guid) = element.downcast_ref::<U>() {
3094 self.increment();
3095 Ok(self.as_mut_vec::<U>().unwrap().push(*guid))
3096 } else {
3097 Err(Error::insert_wrong_element(
3098 false,
3099 qtype::GUID_LIST,
3100 "[u8; 16]",
3101 ))
3102 }
3103 }
3104 qtype::BYTE_LIST => {
3105 if let Some(byte) = element.downcast_ref::<u8>() {
3106 self.increment();
3107 Ok(self.as_mut_vec::<G>().unwrap().push(*byte))
3108 } else {
3109 Err(Error::insert_wrong_element(false, qtype::BYTE_LIST, "u8"))
3110 }
3111 }
3112 qtype::SHORT_LIST => {
3113 if let Some(short) = element.downcast_ref::<i16>() {
3114 self.increment();
3115 Ok(self.as_mut_vec::<H>().unwrap().push(*short))
3116 } else {
3117 Err(Error::insert_wrong_element(false, qtype::SHORT_LIST, "i16"))
3118 }
3119 }
3120 qtype::INT_LIST => {
3121 if let Some(int) = element.downcast_ref::<i32>() {
3122 self.increment();
3123 Ok(self.as_mut_vec::<I>().unwrap().push(*int))
3124 } else {
3125 Err(Error::insert_wrong_element(
3126 false,
3127 qtype::INT_LIST,
3128 "[u8; 16]",
3129 ))
3130 }
3131 }
3132 qtype::LONG_LIST => {
3133 if let Some(long) = element.downcast_ref::<i64>() {
3134 self.increment();
3135 Ok(self.as_mut_vec::<J>().unwrap().push(*long))
3136 } else {
3137 Err(Error::insert_wrong_element(false, qtype::LONG_LIST, "i64"))
3138 }
3139 }
3140 qtype::REAL_LIST => {
3141 if let Some(real) = element.downcast_ref::<f32>() {
3142 self.increment();
3143 Ok(self.as_mut_vec::<E>().unwrap().push(*real))
3144 } else {
3145 Err(Error::insert_wrong_element(false, qtype::FLOAT_LIST, "f32"))
3146 }
3147 }
3148 qtype::FLOAT_LIST => {
3149 if let Some(float) = element.downcast_ref::<f64>() {
3150 self.increment();
3151 Ok(self.as_mut_vec::<F>().unwrap().push(*float))
3152 } else {
3153 Err(Error::insert_wrong_element(false, qtype::FLOAT_LIST, "f64"))
3154 }
3155 }
3156 qtype::STRING => {
3157 if let Some(ch) = element.downcast_ref::<char>() {
3158 Ok(self.as_mut_string().unwrap().push(*ch))
3159 } else {
3160 Err(Error::insert_wrong_element(false, qtype::STRING, "char"))
3161 }
3162 }
3163 qtype::SYMBOL_LIST => {
3164 if let Some(symbol) = element.downcast_ref::<String>() {
3165 self.increment();
3166 Ok(self.as_mut_vec::<S>().unwrap().push(symbol.clone()))
3167 } else {
3168 Err(Error::insert_wrong_element(
3169 false,
3170 qtype::SYMBOL_LIST,
3171 "String",
3172 ))
3173 }
3174 }
3175 qtype::TIMESTAMP_LIST => {
3176 if let Some(timestamp) = element.downcast_ref::<DateTime<Utc>>() {
3177 self.increment();
3178 Ok(self
3179 .as_mut_vec::<J>()
3180 .unwrap()
3181 .push(datetime_to_q_timestamp(*timestamp)))
3182 } else {
3183 Err(Error::insert_wrong_element(
3184 false,
3185 qtype::TIMESTAMP_LIST,
3186 "DateTime<Utc>",
3187 ))
3188 }
3189 }
3190 qtype::MONTH_LIST => {
3191 if let Some(month) = element.downcast_ref::<NaiveDate>() {
3192 self.increment();
3193 Ok(self
3194 .as_mut_vec::<I>()
3195 .unwrap()
3196 .push(date_to_q_month(*month)))
3197 } else {
3198 Err(Error::insert_wrong_element(
3199 false,
3200 qtype::MONTH_LIST,
3201 "Date<Utc>",
3202 ))
3203 }
3204 }
3205 qtype::DATE_LIST => {
3206 if let Some(date) = element.downcast_ref::<NaiveDate>() {
3207 self.increment();
3208 Ok(self.as_mut_vec::<I>().unwrap().push(date_to_q_date(*date)))
3209 } else {
3210 Err(Error::insert_wrong_element(
3211 false,
3212 qtype::DATE_LIST,
3213 "Date<Utc>",
3214 ))
3215 }
3216 }
3217 qtype::DATETIME_LIST => {
3218 if let Some(datetime) = element.downcast_ref::<DateTime<Utc>>() {
3219 self.increment();
3220 Ok(self
3221 .as_mut_vec::<F>()
3222 .unwrap()
3223 .push(datetime_to_q_datetime(*datetime)))
3224 } else {
3225 Err(Error::insert_wrong_element(
3226 false,
3227 qtype::DATETIME_LIST,
3228 "DateTime<Utc>",
3229 ))
3230 }
3231 }
3232 qtype::TIMESPAN_LIST => {
3233 if let Some(timespan) = element.downcast_ref::<Duration>() {
3234 self.increment();
3235 Ok(self
3236 .as_mut_vec::<J>()
3237 .unwrap()
3238 .push(timespan.num_nanoseconds().expect("duration overflow")))
3239 } else {
3240 Err(Error::insert_wrong_element(
3241 false,
3242 qtype::TIMESPAN_LIST,
3243 "Duration",
3244 ))
3245 }
3246 }
3247 qtype::MINUTE_LIST => {
3248 if let Some(minute) = element.downcast_ref::<Duration>() {
3249 self.increment();
3250 Ok(self
3251 .as_mut_vec::<I>()
3252 .unwrap()
3253 .push(minute.num_minutes() as i32))
3254 } else {
3255 Err(Error::insert_wrong_element(
3256 false,
3257 qtype::MINUTE_LIST,
3258 "Duration",
3259 ))
3260 }
3261 }
3262 qtype::SECOND_LIST => {
3263 if let Some(second) = element.downcast_ref::<Duration>() {
3264 self.increment();
3265 Ok(self
3266 .as_mut_vec::<I>()
3267 .unwrap()
3268 .push(second.num_seconds() as i32))
3269 } else {
3270 Err(Error::insert_wrong_element(
3271 false,
3272 qtype::SECOND_LIST,
3273 "Duration",
3274 ))
3275 }
3276 }
3277 qtype::TIME_LIST => {
3278 if let Some(time) = element.downcast_ref::<Duration>() {
3279 self.increment();
3280 Ok(self
3281 .as_mut_vec::<I>()
3282 .unwrap()
3283 .push(time.num_milliseconds() as i32))
3284 } else {
3285 Err(Error::insert_wrong_element(
3286 false,
3287 qtype::TIME_LIST,
3288 "Duration",
3289 ))
3290 }
3291 }
3292 qtype::COMPOUND_LIST => {
3293 if let Some(k) = element.downcast_ref::<K>() {
3294 self.increment();
3295 Ok(self.as_mut_vec::<K>().unwrap().push(k.clone()))
3296 } else {
3297 Err(Error::insert_wrong_element(
3298 false,
3299 qtype::COMPOUND_LIST,
3300 "K",
3301 ))
3302 }
3303 }
3304 _ => Err(Error::invalid_operation("push", self.0.qtype, None)),
3305 }
3306 }
3307
3308 /// Insert an element to the underlying q list at the specified location by an index.
3309 /// # Parameters
3310 /// - `index`: Index of the location where the new element is inserted.
3311 /// - `element`: An element to insert. The type needs to be a one used for atom constructor `K::new_*`. For example,
3312 /// int element must be a `i32` type and timestamp element must be a `DateTime<Utc>` type.
3313 /// # Example
3314 /// ```
3315 /// use kdbplus::qattribute;
3316 /// use kdbplus::ipc::*;
3317 /// use chrono::Duration;
3318 ///
3319 /// fn main() {
3320 /// let mut q_symbol_list = K::new_symbol_list(vec![String::from("almond")], qattribute::NONE);
3321 /// q_symbol_list.push(&String::from("hazel")).unwrap();
3322 /// q_symbol_list.insert(1, &String::from("macadamia")).unwrap();
3323 /// assert_eq!(
3324 /// *q_symbol_list.as_vec::<S>().unwrap(),
3325 /// vec![
3326 /// String::from("almond"),
3327 /// String::from("macadamia"),
3328 /// String::from("hazel")
3329 /// ]
3330 /// );
3331 ///
3332 /// let mut q_minute_list = K::new_minute_list(vec![Duration::minutes(1024)], qattribute::NONE);
3333 /// q_minute_list.insert(0, &Duration::minutes(12)).unwrap();
3334 /// assert_eq!(*q_minute_list.as_vec::<I>().unwrap(), vec![12, 1024]);
3335 /// }
3336 /// ```
3337 pub fn insert(&mut self, index: usize, element: &dyn Any) -> Result<()> {
3338 if index > self.len() {
3339 Err(Error::index_out_of_bounds(self.len(), index))
3340 } else {
3341 match self.0.qtype {
3342 qtype::BOOL_LIST => {
3343 if let Some(boolean) = element.downcast_ref::<bool>() {
3344 self.increment();
3345 Ok(self
3346 .as_mut_vec::<G>()
3347 .unwrap()
3348 .insert(index, *boolean as u8))
3349 } else {
3350 Err(Error::insert_wrong_element(true, qtype::BOOL_LIST, "bool"))
3351 }
3352 }
3353 qtype::GUID_LIST => {
3354 if let Some(guid) = element.downcast_ref::<U>() {
3355 self.increment();
3356 Ok(self.as_mut_vec::<U>().unwrap().insert(index, *guid))
3357 } else {
3358 Err(Error::insert_wrong_element(
3359 true,
3360 qtype::GUID_LIST,
3361 "[u8; 16]",
3362 ))
3363 }
3364 }
3365 qtype::BYTE_LIST => {
3366 if let Some(byte) = element.downcast_ref::<u8>() {
3367 self.increment();
3368 Ok(self.as_mut_vec::<G>().unwrap().insert(index, *byte))
3369 } else {
3370 Err(Error::insert_wrong_element(true, qtype::BYTE_LIST, "u8"))
3371 }
3372 }
3373 qtype::SHORT_LIST => {
3374 if let Some(short) = element.downcast_ref::<i16>() {
3375 self.increment();
3376 Ok(self.as_mut_vec::<H>().unwrap().insert(index, *short))
3377 } else {
3378 Err(Error::insert_wrong_element(false, qtype::SHORT_LIST, "i16"))
3379 }
3380 }
3381 qtype::INT_LIST => {
3382 if let Some(int) = element.downcast_ref::<i32>() {
3383 self.increment();
3384 Ok(self.as_mut_vec::<I>().unwrap().insert(index, *int))
3385 } else {
3386 Err(Error::insert_wrong_element(false, qtype::INT_LIST, "i32"))
3387 }
3388 }
3389 qtype::LONG_LIST => {
3390 if let Some(long) = element.downcast_ref::<i64>() {
3391 self.increment();
3392 Ok(self.as_mut_vec::<J>().unwrap().insert(index, *long))
3393 } else {
3394 Err(Error::insert_wrong_element(false, qtype::LONG_LIST, "i64"))
3395 }
3396 }
3397 qtype::REAL_LIST => {
3398 if let Some(real) = element.downcast_ref::<f32>() {
3399 self.increment();
3400 Ok(self.as_mut_vec::<E>().unwrap().insert(index, *real))
3401 } else {
3402 Err(Error::insert_wrong_element(false, qtype::REAL_LIST, "f32"))
3403 }
3404 }
3405 qtype::FLOAT_LIST => {
3406 if let Some(float) = element.downcast_ref::<f64>() {
3407 self.increment();
3408 Ok(self.as_mut_vec::<F>().unwrap().insert(index, *float))
3409 } else {
3410 Err(Error::insert_wrong_element(false, qtype::FLOAT_LIST, "f64"))
3411 }
3412 }
3413 qtype::STRING => {
3414 if let Some(ch) = element.downcast_ref::<char>() {
3415 Ok(self.as_mut_string().unwrap().insert(index, *ch))
3416 } else {
3417 Err(Error::insert_wrong_element(false, qtype::STRING, "char"))
3418 }
3419 }
3420 qtype::SYMBOL_LIST => {
3421 if let Some(symbol) = element.downcast_ref::<String>() {
3422 self.increment();
3423 Ok(self
3424 .as_mut_vec::<S>()
3425 .unwrap()
3426 .insert(index, symbol.clone()))
3427 } else {
3428 Err(Error::insert_wrong_element(
3429 false,
3430 qtype::SYMBOL_LIST,
3431 "String",
3432 ))
3433 }
3434 }
3435 qtype::TIMESTAMP_LIST => {
3436 if let Some(timestamp) = element.downcast_ref::<DateTime<Utc>>() {
3437 self.increment();
3438 Ok(self
3439 .as_mut_vec::<J>()
3440 .unwrap()
3441 .insert(index, datetime_to_q_timestamp(*timestamp)))
3442 } else {
3443 Err(Error::insert_wrong_element(
3444 false,
3445 qtype::TIMESTAMP_LIST,
3446 "DateTime<Utc>",
3447 ))
3448 }
3449 }
3450 qtype::MONTH_LIST => {
3451 if let Some(month) = element.downcast_ref::<NaiveDate>() {
3452 self.increment();
3453 Ok(self
3454 .as_mut_vec::<I>()
3455 .unwrap()
3456 .insert(index, date_to_q_month(*month)))
3457 } else {
3458 Err(Error::insert_wrong_element(
3459 false,
3460 qtype::MONTH_LIST,
3461 "Date<Utc>",
3462 ))
3463 }
3464 }
3465 qtype::DATE_LIST => {
3466 if let Some(date) = element.downcast_ref::<NaiveDate>() {
3467 self.increment();
3468 Ok(self
3469 .as_mut_vec::<I>()
3470 .unwrap()
3471 .insert(index, date_to_q_date(*date)))
3472 } else {
3473 Err(Error::insert_wrong_element(
3474 false,
3475 qtype::DATE_LIST,
3476 "Date<Utc>",
3477 ))
3478 }
3479 }
3480 qtype::DATETIME_LIST => {
3481 if let Some(datetime) = element.downcast_ref::<DateTime<Utc>>() {
3482 self.increment();
3483 Ok(self
3484 .as_mut_vec::<F>()
3485 .unwrap()
3486 .insert(index, datetime_to_q_datetime(*datetime)))
3487 } else {
3488 Err(Error::insert_wrong_element(
3489 false,
3490 qtype::DATETIME_LIST,
3491 "DateTime<Utc>",
3492 ))
3493 }
3494 }
3495 qtype::TIMESPAN_LIST => {
3496 if let Some(timespan) = element.downcast_ref::<Duration>() {
3497 self.increment();
3498 Ok(self.as_mut_vec::<J>().unwrap().insert(
3499 index,
3500 timespan.num_nanoseconds().expect("duration overflow"),
3501 ))
3502 } else {
3503 Err(Error::insert_wrong_element(
3504 false,
3505 qtype::TIMESPAN_LIST,
3506 "Duration",
3507 ))
3508 }
3509 }
3510 qtype::MINUTE_LIST => {
3511 if let Some(minute) = element.downcast_ref::<Duration>() {
3512 self.increment();
3513 Ok(self
3514 .as_mut_vec::<I>()
3515 .unwrap()
3516 .insert(index, minute.num_minutes() as i32))
3517 } else {
3518 Err(Error::insert_wrong_element(
3519 false,
3520 qtype::MINUTE_LIST,
3521 "Duration",
3522 ))
3523 }
3524 }
3525 qtype::SECOND_LIST => {
3526 if let Some(second) = element.downcast_ref::<Duration>() {
3527 self.increment();
3528 Ok(self
3529 .as_mut_vec::<I>()
3530 .unwrap()
3531 .insert(index, second.num_seconds() as i32))
3532 } else {
3533 Err(Error::insert_wrong_element(
3534 false,
3535 qtype::SECOND_LIST,
3536 "Duration",
3537 ))
3538 }
3539 }
3540 qtype::TIME_LIST => {
3541 if let Some(time) = element.downcast_ref::<Duration>() {
3542 self.increment();
3543 Ok(self
3544 .as_mut_vec::<I>()
3545 .unwrap()
3546 .insert(index, time.num_milliseconds() as i32))
3547 } else {
3548 Err(Error::insert_wrong_element(
3549 false,
3550 qtype::TIME_LIST,
3551 "Duration",
3552 ))
3553 }
3554 }
3555 qtype::COMPOUND_LIST => {
3556 if let Some(k) = element.downcast_ref::<K>() {
3557 self.increment();
3558 Ok(self.as_mut_vec::<K>().unwrap().insert(index, k.clone()))
3559 } else {
3560 Err(Error::insert_wrong_element(
3561 false,
3562 qtype::COMPOUND_LIST,
3563 "K",
3564 ))
3565 }
3566 }
3567 _ => Err(Error::invalid_operation("insert", self.0.qtype, None)),
3568 }
3569 }
3570 }
3571
3572 /// Pop a `bool` object from q bool list.
3573 /// # Example
3574 /// ```
3575 /// use kdbplus::qattribute;
3576 /// use kdbplus::ipc::*;
3577 ///
3578 /// fn main() {
3579 /// let mut q_bool_list = K::new_bool_list(vec![false, true], qattribute::NONE);
3580 /// let tail = q_bool_list.pop_bool().unwrap();
3581 /// assert_eq!(tail, true);
3582 /// }
3583 /// ```
3584 pub fn pop_bool(&mut self) -> Result<bool> {
3585 if self.len() == 0 {
3586 // 0 length
3587 Err(Error::pop_from_empty_list())
3588 } else {
3589 match self.0.qtype {
3590 qtype::BOOL_LIST => {
3591 self.decrement();
3592 Ok(self.as_mut_vec::<G>().unwrap().pop().unwrap() != 0)
3593 }
3594 _ => Err(Error::invalid_operation(
3595 "pop_bool",
3596 self.0.qtype,
3597 Some(qtype::BOOL_LIST),
3598 )),
3599 }
3600 }
3601 }
3602
3603 /// Pop a `[u8; 16]` object from q GUID list.
3604 /// # Example
3605 /// ```
3606 /// use kdbplus::qattribute;
3607 /// use kdbplus::ipc::*;
3608 ///
3609 /// fn main() {
3610 /// let mut q_guid_list = K::new_guid_list(
3611 /// vec![[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]],
3612 /// qattribute::NONE,
3613 /// );
3614 /// let tail = q_guid_list.pop_guid().unwrap();
3615 /// assert_eq!(
3616 /// tail,
3617 /// [0_u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
3618 /// );
3619 /// }
3620 /// ```
3621 pub fn pop_guid(&mut self) -> Result<[u8; 16]> {
3622 if self.len() == 0 {
3623 // 0 length
3624 Err(Error::pop_from_empty_list())
3625 } else {
3626 match self.0.qtype {
3627 qtype::GUID_LIST => {
3628 self.decrement();
3629 Ok(self.as_mut_vec::<U>().unwrap().pop().unwrap())
3630 }
3631 _ => Err(Error::invalid_operation(
3632 "pop_guid",
3633 self.0.qtype,
3634 Some(qtype::GUID_LIST),
3635 )),
3636 }
3637 }
3638 }
3639
3640 /// Pop a `u8` object from q byte list.
3641 /// # Example
3642 /// ```
3643 /// use kdbplus::qattribute;
3644 /// use kdbplus::ipc::*;
3645 ///
3646 /// fn main() {
3647 /// let mut q_byte_list = K::new_byte_list(vec![0x77, 0x99, 0xae], qattribute::NONE);
3648 /// let tail = q_byte_list.pop_byte().unwrap();
3649 /// assert_eq!(tail, 0xae_u8);
3650 /// }
3651 /// ```
3652 pub fn pop_byte(&mut self) -> Result<u8> {
3653 if self.len() == 0 {
3654 // 0 length
3655 Err(Error::pop_from_empty_list())
3656 } else {
3657 match self.0.qtype {
3658 qtype::BYTE_LIST => {
3659 self.decrement();
3660 Ok(self.as_mut_vec::<G>().unwrap().pop().unwrap())
3661 }
3662 _ => Err(Error::invalid_operation(
3663 "pop_byte",
3664 self.0.qtype,
3665 Some(qtype::BYTE_LIST),
3666 )),
3667 }
3668 }
3669 }
3670
3671 /// Pop a `i16` object from q short list.
3672 /// # Example
3673 /// ```
3674 /// use kdbplus::qattribute;
3675 /// use kdbplus::ipc::*;
3676 ///
3677 /// fn main() {
3678 /// let mut q_short_list = K::new_short_list(vec![12, 50], qattribute::NONE);
3679 /// let tail = q_short_list.pop_short().unwrap();
3680 /// assert_eq!(tail, 50_i16);
3681 /// }
3682 /// ```
3683 pub fn pop_short(&mut self) -> Result<i16> {
3684 if self.len() == 0 {
3685 // 0 length
3686 Err(Error::pop_from_empty_list())
3687 } else {
3688 match self.0.qtype {
3689 qtype::SHORT_LIST => {
3690 self.decrement();
3691 Ok(self.as_mut_vec::<H>().unwrap().pop().unwrap())
3692 }
3693 _ => Err(Error::invalid_operation(
3694 "pop_short",
3695 self.0.qtype,
3696 Some(qtype::SHORT_LIST),
3697 )),
3698 }
3699 }
3700 }
3701
3702 /// Pop a `i32` object from q int list.
3703 /// # Example
3704 /// ```
3705 /// use kdbplus::qattribute;
3706 /// use kdbplus::ipc::*;
3707 ///
3708 /// fn main() {
3709 /// let mut q_int_list = K::new_int_list(vec![144000, -1, 888], qattribute::NONE);
3710 /// let tail = q_int_list.pop_int().unwrap();
3711 /// assert_eq!(tail, 888);
3712 /// }
3713 /// ```
3714 pub fn pop_int(&mut self) -> Result<i32> {
3715 if self.len() == 0 {
3716 // 0 length
3717 Err(Error::pop_from_empty_list())
3718 } else {
3719 match self.0.qtype {
3720 qtype::INT_LIST => {
3721 self.decrement();
3722 Ok(self.as_mut_vec::<I>().unwrap().pop().unwrap())
3723 }
3724 _ => Err(Error::invalid_operation(
3725 "pop_int",
3726 self.0.qtype,
3727 Some(qtype::INT_LIST),
3728 )),
3729 }
3730 }
3731 }
3732
3733 /// Pop a `i64` object from q long list.
3734 /// # Example
3735 /// ```
3736 /// use kdbplus::qattribute;
3737 /// use kdbplus::ipc::*;
3738 ///
3739 /// fn main() {
3740 /// let mut q_long_list = K::new_long_list(vec![-86400_i64, 13800000000], qattribute::NONE);
3741 /// let tail = q_long_list.pop_long().unwrap();
3742 /// assert_eq!(tail, 13800000000_i64);
3743 /// }
3744 /// ```
3745 pub fn pop_long(&mut self) -> Result<i64> {
3746 if self.len() == 0 {
3747 // 0 length
3748 Err(Error::pop_from_empty_list())
3749 } else {
3750 match self.0.qtype {
3751 qtype::LONG_LIST => {
3752 self.decrement();
3753 Ok(self.as_mut_vec::<J>().unwrap().pop().unwrap())
3754 }
3755 _ => Err(Error::invalid_operation(
3756 "pop_long",
3757 self.0.qtype,
3758 Some(qtype::LONG_LIST),
3759 )),
3760 }
3761 }
3762 }
3763
3764 /// Pop a `f32` object from q real list.
3765 /// # Example
3766 /// ```
3767 /// use kdbplus::qattribute;
3768 /// use kdbplus::ipc::*;
3769 ///
3770 /// fn main() {
3771 /// let mut q_real_list = K::new_real_list(vec![9.22_f32, -0.1], qattribute::NONE);
3772 /// let tail = q_real_list.pop_real().unwrap();
3773 /// assert_eq!(tail, -0.1_f32);
3774 /// }
3775 /// ```
3776 pub fn pop_real(&mut self) -> Result<f32> {
3777 if self.len() == 0 {
3778 // 0 length
3779 Err(Error::pop_from_empty_list())
3780 } else {
3781 match self.0.qtype {
3782 qtype::REAL_LIST => {
3783 self.decrement();
3784 Ok(self.as_mut_vec::<E>().unwrap().pop().unwrap())
3785 }
3786 _ => Err(Error::invalid_operation(
3787 "pop_real",
3788 self.0.qtype,
3789 Some(qtype::REAL_LIST),
3790 )),
3791 }
3792 }
3793 }
3794
3795 /// Pop a `f64` object from q float list.
3796 /// # Example
3797 /// ```
3798 /// use kdbplus::qattribute;
3799 /// use kdbplus::ipc::*;
3800 ///
3801 /// fn main() {
3802 /// let mut q_float_list = K::new_float_list(vec![5634.7666, 120.45, 1001.3], qattribute::NONE);
3803 /// let tail = q_float_list.pop_float().unwrap();
3804 /// assert_eq!(tail, 1001.3);
3805 /// }
3806 /// ```
3807 pub fn pop_float(&mut self) -> Result<f64> {
3808 if self.len() == 0 {
3809 // 0 length
3810 Err(Error::pop_from_empty_list())
3811 } else {
3812 match self.0.qtype {
3813 qtype::FLOAT_LIST => {
3814 self.decrement();
3815 Ok(self.as_mut_vec::<F>().unwrap().pop().unwrap())
3816 }
3817 _ => Err(Error::invalid_operation(
3818 "pop_float",
3819 self.0.qtype,
3820 Some(qtype::FLOAT_LIST),
3821 )),
3822 }
3823 }
3824 }
3825
3826 /// Pop a `char` object from q string.
3827 /// # Example
3828 /// ```
3829 /// use kdbplus::qattribute;
3830 /// use kdbplus::ipc::*;
3831 ///
3832 /// fn main() {
3833 /// let mut q_string = K::new_string(String::from("speedy"), qattribute::NONE);
3834 /// let tail = q_string.pop_char().unwrap();
3835 /// assert_eq!(tail, 'y');
3836 /// }
3837 /// ```
3838 pub fn pop_char(&mut self) -> Result<char> {
3839 if self.len() == 0 {
3840 // 0 length
3841 Err(Error::pop_from_empty_list())
3842 } else {
3843 match self.0.qtype {
3844 qtype::STRING => Ok(self.as_mut_string().unwrap().pop().unwrap()),
3845 _ => Err(Error::invalid_operation(
3846 "pop_char",
3847 self.0.qtype,
3848 Some(qtype::STRING),
3849 )),
3850 }
3851 }
3852 }
3853
3854 /// Pop a `String` object from q symbol list.
3855 /// # Example
3856 /// ```
3857 /// use kdbplus::qattribute;
3858 /// use kdbplus::ipc::*;
3859 ///
3860 /// fn main(){
3861 /// let mut q_symbol_list=K::new_symbol_list(vec![String::from("almond"), String::from("macadamia"), String::from("hazel")], qattribute::NONE);
3862 /// let tail=q_symbol_list.pop_symbol().unwrap();
3863 /// assert_eq!(tail, String::from("hazel"));
3864 /// }
3865 /// ```
3866 pub fn pop_symbol(&mut self) -> Result<String> {
3867 if self.len() == 0 {
3868 // 0 length
3869 Err(Error::pop_from_empty_list())
3870 } else {
3871 match self.0.qtype {
3872 qtype::SYMBOL_LIST => {
3873 self.decrement();
3874 Ok(self.as_mut_vec::<S>().unwrap().pop().unwrap())
3875 }
3876 _ => Err(Error::invalid_operation(
3877 "pop_symbol",
3878 self.0.qtype,
3879 Some(qtype::SYMBOL_LIST),
3880 )),
3881 }
3882 }
3883 }
3884
3885 /// Pop a `DateTime<Utc>` object from q timestamp list.
3886 /// # Example
3887 /// ```
3888 /// use kdbplus::qattribute;
3889 /// use kdbplus::ipc::*;
3890 /// use chrono::prelude::*;
3891 ///
3892 /// fn main() {
3893 /// let mut q_timestamp_list = K::new_timestamp_list(
3894 /// vec![Utc.ymd(2019, 8, 9).and_hms_nano(16, 28, 2, 468276775)],
3895 /// qattribute::NONE,
3896 /// );
3897 /// let tail = q_timestamp_list.pop_timestamp().unwrap();
3898 /// assert_eq!(tail, Utc.ymd(2019, 8, 9).and_hms_nano(16, 28, 2, 468276775));
3899 /// }
3900 /// ```
3901 pub fn pop_timestamp(&mut self) -> Result<DateTime<Utc>> {
3902 if self.len() == 0 {
3903 // 0 length
3904 Err(Error::pop_from_empty_list())
3905 } else {
3906 match self.0.qtype {
3907 qtype::TIMESTAMP_LIST => {
3908 self.decrement();
3909 Ok(q_timestamp_to_datetime(
3910 self.as_mut_vec::<J>().unwrap().pop().unwrap(),
3911 ))
3912 }
3913 _ => Err(Error::invalid_operation(
3914 "pop_timestamp",
3915 self.0.qtype,
3916 Some(qtype::TIMESTAMP_LIST),
3917 )),
3918 }
3919 }
3920 }
3921
3922 /// Pop a `Date<Utc>` object from q month list.
3923 /// # Example
3924 /// ```
3925 /// use kdbplus::qattribute;
3926 /// use kdbplus::ipc::*;
3927 /// use chrono::prelude::*;
3928 ///
3929 /// fn main() {
3930 /// let mut q_month_list = K::new_month_list(
3931 /// vec![
3932 /// NaiveDate::from_ymd_opt(2011, 5, 1).unwrap(),
3933 /// NaiveDate::from_ymd_opt(2004, 8, 1).unwrap(),
3934 /// ],
3935 /// qattribute::NONE,
3936 /// );
3937 /// let tail = q_month_list.pop_month().unwrap();
3938 /// assert_eq!(tail, NaiveDate::from_ymd_opt(2004, 8, 1).unwrap());
3939 /// }
3940 /// ```
3941 pub fn pop_month(&mut self) -> Result<NaiveDate> {
3942 if self.len() == 0 {
3943 // 0 length
3944 Err(Error::pop_from_empty_list())
3945 } else {
3946 match self.0.qtype {
3947 qtype::MONTH_LIST => {
3948 self.decrement();
3949 Ok(q_month_to_date(
3950 self.as_mut_vec::<I>().unwrap().pop().unwrap(),
3951 ))
3952 }
3953 _ => Err(Error::invalid_operation(
3954 "pop_month",
3955 self.0.qtype,
3956 Some(qtype::MONTH_LIST),
3957 )),
3958 }
3959 }
3960 }
3961
3962 /// Pop a `Date<Utc>` object from q date list.
3963 /// # Example
3964 /// ```
3965 /// use kdbplus::qattribute;
3966 /// use kdbplus::ipc::*;
3967 /// use chrono::prelude::*;
3968 ///
3969 /// fn main() {
3970 /// let mut q_date_list = K::new_date_list(
3971 /// vec![
3972 /// NaiveDate::from_ymd_opt(2021, 3, 19).unwrap(),
3973 /// NaiveDate::from_ymd_opt(2004, 8, 1).unwrap(),
3974 /// NaiveDate::from_ymd_opt(2014, 6, 4).unwrap(),
3975 /// ],
3976 /// qattribute::NONE,
3977 /// );
3978 /// let tail = q_date_list.pop_date().unwrap();
3979 /// assert_eq!(tail, NaiveDate::from_ymd_opt(2014, 6, 4).unwrap());
3980 /// }
3981 /// ```
3982 pub fn pop_date(&mut self) -> Result<NaiveDate> {
3983 if self.len() == 0 {
3984 // 0 length
3985 Err(Error::pop_from_empty_list())
3986 } else {
3987 match self.0.qtype {
3988 qtype::DATE_LIST => {
3989 self.decrement();
3990 Ok(q_date_to_date(
3991 self.as_mut_vec::<I>().unwrap().pop().unwrap(),
3992 )?)
3993 }
3994 _ => Err(Error::invalid_operation(
3995 "pop_date",
3996 self.0.qtype,
3997 Some(qtype::DATE_LIST),
3998 )),
3999 }
4000 }
4001 }
4002
4003 /// Pop a `DateTime<Utc>` object from q datetime list.
4004 /// # Example
4005 /// ```
4006 /// use kdbplus::qattribute;
4007 /// use kdbplus::ipc::*;
4008 /// use chrono::prelude::*;
4009 ///
4010 /// fn main() {
4011 /// let mut q_datetime_list = K::new_datetime_list(
4012 /// vec![
4013 /// Utc.ymd(2018, 9, 22).and_hms_milli(4, 58, 30, 204),
4014 /// Utc.ymd(2003, 12, 9).and_hms_milli(19, 58, 30, 326),
4015 /// ],
4016 /// qattribute::NONE,
4017 /// );
4018 /// let tail = q_datetime_list.pop_datetime().unwrap();
4019 /// assert_eq!(tail, Utc.ymd(2003, 12, 9).and_hms_milli(19, 58, 30, 326));
4020 /// }
4021 /// ```
4022 pub fn pop_datetime(&mut self) -> Result<DateTime<Utc>> {
4023 if self.len() == 0 {
4024 // 0 length
4025 Err(Error::pop_from_empty_list())
4026 } else {
4027 match self.0.qtype {
4028 qtype::DATETIME_LIST => {
4029 self.decrement();
4030 Ok(q_datetime_to_datetime(
4031 self.as_mut_vec::<F>().unwrap().pop().unwrap(),
4032 ))
4033 }
4034 _ => Err(Error::invalid_operation(
4035 "pop_datetime",
4036 self.0.qtype,
4037 Some(qtype::DATETIME_LIST),
4038 )),
4039 }
4040 }
4041 }
4042
4043 /// Pop a `Duration` object from q timespan list.
4044 /// # Example
4045 /// ```
4046 /// use kdbplus::qattribute;
4047 /// use kdbplus::ipc::*;
4048 /// use chrono::Duration;
4049 ///
4050 /// fn main() {
4051 /// let mut q_timespan_list = K::new_timespan_list(
4052 /// vec![
4053 /// Duration::nanoseconds(6782392639932),
4054 /// Duration::nanoseconds(219849398328832),
4055 /// ],
4056 /// qattribute::NONE,
4057 /// );
4058 /// let tail = q_timespan_list.pop_timespan().unwrap();
4059 /// assert_eq!(tail, Duration::nanoseconds(219849398328832));
4060 /// }
4061 /// ```
4062 pub fn pop_timespan(&mut self) -> Result<Duration> {
4063 if self.len() == 0 {
4064 // 0 length
4065 Err(Error::pop_from_empty_list())
4066 } else {
4067 match self.0.qtype {
4068 qtype::TIMESPAN_LIST => {
4069 self.decrement();
4070 Ok(Duration::nanoseconds(
4071 self.as_mut_vec::<J>().unwrap().pop().unwrap(),
4072 ))
4073 }
4074 _ => Err(Error::invalid_operation(
4075 "pop_timespan",
4076 self.0.qtype,
4077 Some(qtype::TIMESPAN_LIST),
4078 )),
4079 }
4080 }
4081 }
4082
4083 /// Pop a `Duration` object from q minute list.
4084 /// # Example
4085 /// ```
4086 /// use kdbplus::qattribute;
4087 /// use kdbplus::ipc::*;
4088 /// use chrono::Duration;
4089 ///
4090 /// fn main() {
4091 /// let mut q_minute_list = K::new_minute_list(
4092 /// vec![Duration::minutes(1024), Duration::minutes(-503)],
4093 /// qattribute::NONE,
4094 /// );
4095 /// let tail = q_minute_list.pop_minute().unwrap();
4096 /// assert_eq!(tail, Duration::minutes(-503));
4097 /// }
4098 /// ```
4099 pub fn pop_minute(&mut self) -> Result<Duration> {
4100 if self.len() == 0 {
4101 // 0 length
4102 Err(Error::pop_from_empty_list())
4103 } else {
4104 match self.0.qtype {
4105 qtype::MINUTE_LIST => {
4106 self.decrement();
4107 Ok(Duration::minutes(
4108 self.as_mut_vec::<I>().unwrap().pop().unwrap() as i64,
4109 ))
4110 }
4111 _ => Err(Error::invalid_operation(
4112 "pop_minute",
4113 self.0.qtype,
4114 Some(qtype::MINUTE_LIST),
4115 )),
4116 }
4117 }
4118 }
4119
4120 /// Pop a `Duration` object from q second list.
4121 /// # Example
4122 /// ```
4123 /// use kdbplus::qattribute;
4124 /// use kdbplus::ipc::*;
4125 /// use chrono::Duration;
4126 ///
4127 /// fn main() {
4128 /// let mut q_second_list = K::new_second_list(
4129 /// vec![Duration::seconds(-32467), Duration::seconds(73984)],
4130 /// qattribute::NONE,
4131 /// );
4132 /// let tail = q_second_list.pop_second().unwrap();
4133 /// assert_eq!(tail, Duration::seconds(73984));
4134 /// }
4135 /// ```
4136 pub fn pop_second(&mut self) -> Result<Duration> {
4137 if self.len() == 0 {
4138 // 0 length
4139 Err(Error::pop_from_empty_list())
4140 } else {
4141 match self.0.qtype {
4142 qtype::SECOND_LIST => {
4143 self.decrement();
4144 Ok(Duration::seconds(
4145 self.as_mut_vec::<I>().unwrap().pop().unwrap() as i64,
4146 ))
4147 }
4148 _ => Err(Error::invalid_operation(
4149 "pop_second",
4150 self.0.qtype,
4151 Some(qtype::SECOND_LIST),
4152 )),
4153 }
4154 }
4155 }
4156
4157 /// Pop a `Duration` object from q time list.
4158 /// # Example
4159 /// ```
4160 /// use kdbplus::qattribute;
4161 /// use kdbplus::ipc::*;
4162 /// use chrono::Duration;
4163 ///
4164 /// fn main() {
4165 /// let mut q_time_list = K::new_time_list(
4166 /// vec![
4167 // Duration::milliseconds(902467),
4168 /// Duration::milliseconds(-23587934),
4169 /// ],
4170 /// qattribute::NONE,
4171 /// );
4172 /// let tail = q_time_list.pop_time().unwrap();
4173 /// assert_eq!(tail, Duration::milliseconds(-23587934));
4174 /// }
4175 /// ```
4176 pub fn pop_time(&mut self) -> Result<Duration> {
4177 if self.len() == 0 {
4178 // 0 length
4179 Err(Error::pop_from_empty_list())
4180 } else {
4181 match self.0.qtype {
4182 qtype::TIME_LIST => {
4183 self.decrement();
4184 Ok(Duration::milliseconds(
4185 self.as_mut_vec::<I>().unwrap().pop().unwrap() as i64,
4186 ))
4187 }
4188 _ => Err(Error::invalid_operation(
4189 "pop_time",
4190 self.0.qtype,
4191 Some(qtype::TIME_LIST),
4192 )),
4193 }
4194 }
4195 }
4196
4197 /// Pop an element as `K` from the tail of the underlying list.
4198 /// # Example
4199 /// ```
4200 /// use kdbplus::qattribute;
4201 /// use kdbplus::ipc::*;
4202 /// use chrono::prelude::*;
4203 /// use chrono::Duration;
4204 ///
4205 /// fn main() {
4206 /// let mut q_time_list = K::new_time_list(
4207 /// vec![
4208 /// Duration::milliseconds(902467),
4209 /// Duration::milliseconds(-23587934),
4210 /// ],
4211 /// qattribute::NONE,
4212 /// );
4213 /// let mut tail = q_time_list.pop().unwrap();
4214 /// assert_eq!(format!("{}", tail), String::from("-06:33:07.934"));
4215 /// let mut q_compound_list = K::new_compound_list(vec![
4216 /// K::new_long_list(vec![10000324_i64, -43890], qattribute::NONE),
4217 /// K::new_symbol(String::from("fire")),
4218 /// K::new_timestamp_list(
4219 /// vec![
4220 /// Utc.ymd(2018, 4, 10).and_hms_nano(15, 47, 39, 758934332),
4221 /// Utc.ymd(2008, 12, 4).and_hms_nano(14, 12, 7, 548932080),
4222 /// ],
4223 /// qattribute::NONE,
4224 /// ),
4225 /// ]);
4226 /// tail = q_compound_list.pop().unwrap();
4227 /// assert_eq!(
4228 /// format!("{}", tail),
4229 /// String::from("2018.04.10D15:47:39.758934332 2008.12.04D14:12:07.548932080")
4230 /// );
4231 /// }
4232 /// ```
4233 pub fn pop(&mut self) -> Result<K> {
4234 if self.len() == 0 {
4235 // 0 length
4236 Err(Error::pop_from_empty_list())
4237 } else {
4238 match self.0.qtype {
4239 qtype::BOOL_LIST => {
4240 self.decrement();
4241 Ok(K::new_bool(
4242 self.as_mut_vec::<G>().unwrap().pop().unwrap() != 0,
4243 ))
4244 }
4245 qtype::GUID_LIST => {
4246 self.decrement();
4247 Ok(K::new_guid(self.as_mut_vec::<U>().unwrap().pop().unwrap()))
4248 }
4249 qtype::BYTE_LIST => {
4250 self.decrement();
4251 Ok(K::new_byte(self.as_mut_vec::<G>().unwrap().pop().unwrap()))
4252 }
4253 qtype::SHORT_LIST => {
4254 self.decrement();
4255 Ok(K::new_short(self.as_mut_vec::<H>().unwrap().pop().unwrap()))
4256 }
4257 qtype::INT_LIST => {
4258 self.decrement();
4259 Ok(K::new_int(self.as_mut_vec::<I>().unwrap().pop().unwrap()))
4260 }
4261 qtype::LONG_LIST => {
4262 self.decrement();
4263 Ok(K::new_long(self.as_mut_vec::<J>().unwrap().pop().unwrap()))
4264 }
4265 qtype::REAL_LIST => {
4266 self.decrement();
4267 Ok(K::new_real(self.as_mut_vec::<E>().unwrap().pop().unwrap()))
4268 }
4269 qtype::FLOAT_LIST => {
4270 self.decrement();
4271 Ok(K::new_float(self.as_mut_vec::<F>().unwrap().pop().unwrap()))
4272 }
4273 qtype::STRING => Ok(K::new_char(self.as_mut_string().unwrap().pop().unwrap())),
4274 qtype::SYMBOL_LIST => {
4275 self.decrement();
4276 Ok(K::new_symbol(
4277 self.as_mut_vec::<S>().unwrap().pop().unwrap(),
4278 ))
4279 }
4280 qtype::TIMESTAMP_LIST => {
4281 self.decrement();
4282 Ok(K::new(
4283 qtype::TIMESTAMP_ATOM,
4284 qattribute::NONE,
4285 k0_inner::long(self.as_mut_vec::<J>().unwrap().pop().unwrap()),
4286 ))
4287 }
4288 qtype::MONTH_LIST => {
4289 self.decrement();
4290 Ok(K::new(
4291 qtype::MONTH_ATOM,
4292 qattribute::NONE,
4293 k0_inner::int(self.as_mut_vec::<I>().unwrap().pop().unwrap()),
4294 ))
4295 }
4296 qtype::DATE_LIST => {
4297 self.decrement();
4298 Ok(K::new(
4299 qtype::DATE_ATOM,
4300 qattribute::NONE,
4301 k0_inner::int(self.as_mut_vec::<I>().unwrap().pop().unwrap()),
4302 ))
4303 }
4304 qtype::DATETIME_LIST => {
4305 self.decrement();
4306 Ok(K::new(
4307 qtype::DATETIME_ATOM,
4308 qattribute::NONE,
4309 k0_inner::float(self.as_mut_vec::<F>().unwrap().pop().unwrap()),
4310 ))
4311 }
4312 qtype::TIMESPAN_LIST => {
4313 self.decrement();
4314 Ok(K::new(
4315 qtype::TIMESPAN_ATOM,
4316 qattribute::NONE,
4317 k0_inner::long(self.as_mut_vec::<J>().unwrap().pop().unwrap()),
4318 ))
4319 }
4320 qtype::MINUTE_LIST => {
4321 self.decrement();
4322 Ok(K::new(
4323 qtype::MINUTE_ATOM,
4324 qattribute::NONE,
4325 k0_inner::int(self.as_mut_vec::<I>().unwrap().pop().unwrap()),
4326 ))
4327 }
4328 qtype::SECOND_LIST => {
4329 self.decrement();
4330 Ok(K::new(
4331 qtype::SECOND_ATOM,
4332 qattribute::NONE,
4333 k0_inner::int(self.as_mut_vec::<I>().unwrap().pop().unwrap()),
4334 ))
4335 }
4336 qtype::TIME_LIST => {
4337 self.decrement();
4338 Ok(K::new(
4339 qtype::TIME_ATOM,
4340 qattribute::NONE,
4341 k0_inner::int(self.as_mut_vec::<I>().unwrap().pop().unwrap()),
4342 ))
4343 }
4344 qtype::COMPOUND_LIST => {
4345 self.decrement();
4346 Ok(self.as_mut_vec::<K>().unwrap().pop().unwrap())
4347 }
4348 _ => Err(Error::invalid_operation("pop", self.0.qtype, None)),
4349 }
4350 }
4351 }
4352
4353 /// Remove a `bool` object from the underlying q bool list.
4354 /// # Example
4355 /// ```
4356 /// use kdbplus::qattribute;
4357 /// use kdbplus::ipc::*;
4358 ///
4359 /// fn main() {
4360 /// let mut q_bool_list = K::new_bool_list(vec![false, true], qattribute::NONE);
4361 /// let tail = q_bool_list.remove_bool(0).unwrap();
4362 /// assert_eq!(tail, false);
4363 /// }
4364 /// ```
4365 pub fn remove_bool(&mut self, index: usize) -> Result<bool> {
4366 if index >= self.len() {
4367 // 0 length
4368 Err(Error::index_out_of_bounds(self.len(), index))
4369 } else {
4370 match self.0.qtype {
4371 qtype::BOOL_LIST => Ok(self.as_mut_vec::<G>().unwrap().remove(index) != 0),
4372 _ => Err(Error::invalid_operation(
4373 "remove_bool",
4374 self.0.qtype,
4375 Some(qtype::BOOL_LIST),
4376 )),
4377 }
4378 }
4379 }
4380
4381 /// Remove a `[u8;16]` object from the underlying q GUID list.
4382 /// # Example
4383 /// ```
4384 /// use kdbplus::qattribute;
4385 /// use kdbplus::ipc::*;
4386 ///
4387 /// fn main(){
4388 /// let mut q_guid_list=K::new_guid_list(vec![[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]], qattribute::NONE);
4389 /// let tail=q_guid_list.remove_guid(1).unwrap();
4390 /// assert_eq!(tail, [1_u8,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
4391 /// }
4392 /// ```
4393 pub fn remove_guid(&mut self, index: usize) -> Result<[u8; 16]> {
4394 if index >= self.len() {
4395 // 0 length
4396 Err(Error::index_out_of_bounds(self.len(), index))
4397 } else {
4398 match self.0.qtype {
4399 qtype::GUID_LIST => Ok(self.as_mut_vec::<U>().unwrap().remove(index)),
4400 _ => Err(Error::invalid_operation(
4401 "remove_guid",
4402 self.0.qtype,
4403 Some(qtype::GUID_LIST),
4404 )),
4405 }
4406 }
4407 }
4408
4409 /// Remove a `u8` object from the underlying q byte list.
4410 /// # Example
4411 /// ```
4412 /// use kdbplus::qattribute;
4413 /// use kdbplus::ipc::*;
4414 ///
4415 /// fn main() {
4416 /// let mut q_byte_list = K::new_byte_list(vec![0x77, 0x99, 0xae], qattribute::NONE);
4417 /// let tail = q_byte_list.remove_byte(1).unwrap();
4418 /// assert_eq!(tail, 0x99_u8);
4419 /// }
4420 /// ```
4421 pub fn remove_byte(&mut self, index: usize) -> Result<u8> {
4422 if index >= self.len() {
4423 // 0 length
4424 Err(Error::index_out_of_bounds(self.len(), index))
4425 } else {
4426 match self.0.qtype {
4427 qtype::BYTE_LIST => Ok(self.as_mut_vec::<G>().unwrap().remove(index)),
4428 _ => Err(Error::invalid_operation(
4429 "remove_byte",
4430 self.0.qtype,
4431 Some(qtype::BYTE_LIST),
4432 )),
4433 }
4434 }
4435 }
4436
4437 /// Remove a `i16` object from the underlying q short list.
4438 /// # Example
4439 /// ```
4440 /// use kdbplus::qattribute;
4441 /// use kdbplus::ipc::*;
4442 ///
4443 /// fn main() {
4444 /// let mut q_short_list = K::new_short_list(vec![12, 50], qattribute::NONE);
4445 /// let tail = q_short_list.remove_short(0).unwrap();
4446 /// assert_eq!(tail, 12_i16);
4447 /// }
4448 /// ```
4449 pub fn remove_short(&mut self, index: usize) -> Result<i16> {
4450 if index >= self.len() {
4451 // 0 length
4452 Err(Error::index_out_of_bounds(self.len(), index))
4453 } else {
4454 match self.0.qtype {
4455 qtype::SHORT_LIST => Ok(self.as_mut_vec::<H>().unwrap().remove(index)),
4456 _ => Err(Error::invalid_operation(
4457 "remove_short",
4458 self.0.qtype,
4459 Some(qtype::SHORT_LIST),
4460 )),
4461 }
4462 }
4463 }
4464
4465 /// Remove a `i32` object from the underlying q int list.
4466 /// # Example
4467 /// ```
4468 /// use kdbplus::qattribute;
4469 /// use kdbplus::ipc::*;
4470 ///
4471 /// fn main() {
4472 /// let mut q_int_list = K::new_int_list(vec![144000, -1, 888], qattribute::NONE);
4473 /// let tail = q_int_list.remove_int(1).unwrap();
4474 /// assert_eq!(tail, -1);
4475 /// }
4476 /// ```
4477 pub fn remove_int(&mut self, index: usize) -> Result<i32> {
4478 if index >= self.len() {
4479 // 0 length
4480 Err(Error::index_out_of_bounds(self.len(), index))
4481 } else {
4482 match self.0.qtype {
4483 qtype::INT_LIST => Ok(self.as_mut_vec::<I>().unwrap().remove(index)),
4484 _ => Err(Error::invalid_operation(
4485 "remove_int",
4486 self.0.qtype,
4487 Some(qtype::INT_LIST),
4488 )),
4489 }
4490 }
4491 }
4492
4493 /// Remove a `i64` object from the underlying q long list.
4494 /// # Example
4495 /// ```
4496 /// use kdbplus::qattribute;
4497 /// use kdbplus::ipc::*;
4498 ///
4499 /// fn main() {
4500 /// let mut q_long_list = K::new_long_list(vec![-86400_i64, 13800000000], qattribute::NONE);
4501 /// let tail = q_long_list.remove_long(0).unwrap();
4502 /// assert_eq!(tail, -86400_i64);
4503 /// }
4504 /// ```
4505 pub fn remove_long(&mut self, index: usize) -> Result<i64> {
4506 if index >= self.len() {
4507 // 0 length
4508 Err(Error::index_out_of_bounds(self.len(), index))
4509 } else {
4510 match self.0.qtype {
4511 qtype::LONG_LIST => Ok(self.as_mut_vec::<J>().unwrap().remove(index)),
4512 _ => Err(Error::invalid_operation(
4513 "remove_long",
4514 self.0.qtype,
4515 Some(qtype::LONG_LIST),
4516 )),
4517 }
4518 }
4519 }
4520
4521 /// Remove a `f32` object from the underlying q real list.
4522 /// # Example
4523 /// ```
4524 /// use kdbplus::qattribute;
4525 /// use kdbplus::ipc::*;
4526 ///
4527 /// fn main() {
4528 /// let mut q_real_list = K::new_real_list(vec![9.22_f32, -0.1], qattribute::NONE);
4529 /// let tail = q_real_list.remove_real(1).unwrap();
4530 /// assert_eq!(tail, -0.1_f32);
4531 /// }
4532 /// ```
4533 pub fn remove_real(&mut self, index: usize) -> Result<f32> {
4534 if index >= self.len() {
4535 // 0 length
4536 Err(Error::index_out_of_bounds(self.len(), index))
4537 } else {
4538 match self.0.qtype {
4539 qtype::REAL_LIST => Ok(self.as_mut_vec::<E>().unwrap().remove(index)),
4540 _ => Err(Error::invalid_operation(
4541 "remove_real",
4542 self.0.qtype,
4543 Some(qtype::REAL_LIST),
4544 )),
4545 }
4546 }
4547 }
4548
4549 /// Remove a `f64` object from the underlying q float list.
4550 /// # Example
4551 /// ```
4552 /// use kdbplus::qattribute;
4553 /// use kdbplus::ipc::*;
4554 ///
4555 /// fn main() {
4556 /// let mut q_float_list = K::new_float_list(vec![5634.7666, 120.45, 1001.3], qattribute::NONE);
4557 /// let tail = q_float_list.remove_float(0).unwrap();
4558 /// assert_eq!(tail, 5634.7666);
4559 /// }
4560 /// ```
4561 pub fn remove_float(&mut self, index: usize) -> Result<f64> {
4562 if index >= self.len() {
4563 // 0 length
4564 Err(Error::index_out_of_bounds(self.len(), index))
4565 } else {
4566 match self.0.qtype {
4567 qtype::FLOAT_LIST => Ok(self.as_mut_vec::<F>().unwrap().remove(index)),
4568 _ => Err(Error::invalid_operation(
4569 "remove_float",
4570 self.0.qtype,
4571 Some(qtype::FLOAT_LIST),
4572 )),
4573 }
4574 }
4575 }
4576
4577 /// Remove a `char` object from the underlying q string.
4578 /// # Example
4579 /// ```
4580 /// use kdbplus::qattribute;
4581 /// use kdbplus::ipc::*;
4582 ///
4583 /// fn main() {
4584 /// let mut q_string = K::new_string(String::from("speedy"), qattribute::NONE);
4585 /// let tail = q_string.remove_char(2).unwrap();
4586 /// assert_eq!(tail, 'e');
4587 /// }
4588 /// ```
4589 pub fn remove_char(&mut self, index: usize) -> Result<char> {
4590 if index >= self.len() {
4591 // 0 length
4592 Err(Error::index_out_of_bounds(self.len(), index))
4593 } else {
4594 match self.0.qtype {
4595 qtype::STRING => Ok(self.as_mut_string().unwrap().remove(index)),
4596 _ => Err(Error::invalid_operation(
4597 "remove_char",
4598 self.0.qtype,
4599 Some(qtype::STRING),
4600 )),
4601 }
4602 }
4603 }
4604
4605 /// Remove a `String` object from the underlying q symbol list.
4606 /// # Example
4607 /// ```
4608 /// use kdbplus::qattribute;
4609 /// use kdbplus::ipc::*;
4610 ///
4611 /// fn main() {
4612 /// let mut q_symbol_list = K::new_symbol_list(
4613 /// vec![
4614 /// String::from("almond"),
4615 /// String::from("macadamia"),
4616 /// String::from("hazel"),
4617 /// ],
4618 /// qattribute::NONE,
4619 /// );
4620 /// let tail = q_symbol_list.remove_symbol(2).unwrap();
4621 /// assert_eq!(tail, String::from("hazel"));
4622 /// }
4623 /// ```
4624 pub fn remove_symbol(&mut self, index: usize) -> Result<String> {
4625 if index >= self.len() {
4626 // 0 length
4627 Err(Error::index_out_of_bounds(self.len(), index))
4628 } else {
4629 match self.0.qtype {
4630 qtype::SYMBOL_LIST => Ok(self.as_mut_vec::<S>().unwrap().remove(index)),
4631 _ => Err(Error::invalid_operation(
4632 "remove_symbol",
4633 self.0.qtype,
4634 Some(qtype::SYMBOL_LIST),
4635 )),
4636 }
4637 }
4638 }
4639
4640 /// Remove a `DateTime<Utc>` object from the underlying q timestamp list.
4641 /// # Example
4642 /// ```
4643 /// use kdbplus::qattribute;
4644 /// use kdbplus::ipc::*;
4645 /// use chrono::prelude::*;
4646 ///
4647 /// fn main() {
4648 /// let mut q_timestamp_list = K::new_timestamp_list(
4649 /// vec![
4650 /// Utc.ymd(2019, 8, 9).and_hms_nano(16, 28, 2, 468276775),
4651 /// Utc.ymd(2015, 3, 28).and_hms_nano(14, 2, 41, 46827329),
4652 /// ],
4653 /// qattribute::NONE,
4654 /// );
4655 /// let tail = q_timestamp_list.remove_timestamp(0).unwrap();
4656 /// assert_eq!(tail, Utc.ymd(2019, 8, 9).and_hms_nano(16, 28, 2, 468276775));
4657 /// }
4658 /// ```
4659 pub fn remove_timestamp(&mut self, index: usize) -> Result<DateTime<Utc>> {
4660 if index >= self.len() {
4661 // 0 length
4662 Err(Error::index_out_of_bounds(self.len(), index))
4663 } else {
4664 match self.0.qtype {
4665 qtype::TIMESTAMP_LIST => Ok(q_timestamp_to_datetime(
4666 self.as_mut_vec::<J>().unwrap().remove(index),
4667 )),
4668 _ => Err(Error::invalid_operation(
4669 "remove_timestamp",
4670 self.0.qtype,
4671 Some(qtype::TIMESTAMP_LIST),
4672 )),
4673 }
4674 }
4675 }
4676
4677 /// Remove a `Date<Utc>` object from the underlying q month list.
4678 /// # Example
4679 /// ```
4680 /// use kdbplus::qattribute;
4681 /// use kdbplus::ipc::*;
4682 /// use chrono::prelude::*;
4683 ///
4684 /// fn main() {
4685 /// let mut q_month_list = K::new_month_list(
4686 /// vec![
4687 /// NaiveDate::from_ymd_opt(2011, 5, 1).unwrap(),
4688 /// NaiveDate::from_ymd_opt(2004, 8, 1).unwrap(),
4689 /// ],
4690 /// qattribute::NONE,
4691 /// );
4692 /// let tail = q_month_list.remove_month(0).unwrap();
4693 /// assert_eq!(tail, NaiveDate::from_ymd_opt(2011, 5, 1).unwrap());
4694 /// }
4695 /// ```
4696 pub fn remove_month(&mut self, index: usize) -> Result<NaiveDate> {
4697 if index >= self.len() {
4698 // 0 length
4699 Err(Error::index_out_of_bounds(self.len(), index))
4700 } else {
4701 match self.0.qtype {
4702 qtype::MONTH_LIST => Ok(q_month_to_date(
4703 self.as_mut_vec::<I>().unwrap().remove(index),
4704 )),
4705 _ => Err(Error::invalid_operation(
4706 "remove_month",
4707 self.0.qtype,
4708 Some(qtype::MONTH_LIST),
4709 )),
4710 }
4711 }
4712 }
4713
4714 /// Remove a `Date<Utc>` object from the underlying q date list.
4715 /// # Example
4716 /// ```
4717 /// use kdbplus::qattribute;
4718 /// use kdbplus::ipc::*;
4719 /// use chrono::prelude::*;
4720 ///
4721 /// fn main() {
4722 /// let mut q_date_list = K::new_date_list(
4723 /// vec![
4724 /// NaiveDate::from_ymd_opt(2021, 3, 19).unwrap(),
4725 /// NaiveDate::from_ymd_opt(2004, 8, 1).unwrap(),
4726 /// NaiveDate::from_ymd_opt(2014, 6, 4).unwrap(),
4727 /// ],
4728 /// qattribute::NONE,
4729 /// );
4730 /// let tail = q_date_list.remove_date(1).unwrap();
4731 /// assert_eq!(tail, NaiveDate::from_ymd_opt(2004, 8, 1).unwrap());
4732 /// }
4733 /// ```
4734 pub fn remove_date(&mut self, index: usize) -> Result<NaiveDate> {
4735 if index >= self.len() {
4736 // 0 length
4737 Err(Error::index_out_of_bounds(self.len(), index))
4738 } else {
4739 match self.0.qtype {
4740 qtype::DATE_LIST => Ok(q_date_to_date(
4741 self.as_mut_vec::<I>().unwrap().remove(index),
4742 )?),
4743 _ => Err(Error::invalid_operation(
4744 "remove_date",
4745 self.0.qtype,
4746 Some(qtype::DATE_LIST),
4747 )),
4748 }
4749 }
4750 }
4751
4752 /// Remove a `DateTime<Utc>` object from the underlying q datetime list.
4753 /// # Example
4754 /// ```
4755 /// use kdbplus::qattribute;
4756 /// use kdbplus::ipc::*;
4757 /// use chrono::prelude::*;
4758 ///
4759 /// fn main() {
4760 /// let mut q_datetime_list = K::new_datetime_list(
4761 /// vec![
4762 /// Utc.ymd(2018, 9, 22).and_hms_milli(4, 58, 30, 204),
4763 /// Utc.ymd(2003, 12, 9).and_hms_milli(19, 58, 30, 326),
4764 /// ],
4765 /// qattribute::NONE,
4766 /// );
4767 /// let tail = q_datetime_list.remove_datetime(1).unwrap();
4768 /// assert_eq!(tail, Utc.ymd(2003, 12, 9).and_hms_milli(19, 58, 30, 326));
4769 /// }
4770 /// ```
4771 pub fn remove_datetime(&mut self, index: usize) -> Result<DateTime<Utc>> {
4772 if index >= self.len() {
4773 // 0 length
4774 Err(Error::index_out_of_bounds(self.len(), index))
4775 } else {
4776 match self.0.qtype {
4777 qtype::DATETIME_LIST => Ok(q_datetime_to_datetime(
4778 self.as_mut_vec::<F>().unwrap().remove(index),
4779 )),
4780 _ => Err(Error::invalid_operation(
4781 "remove_datetime",
4782 self.0.qtype,
4783 Some(qtype::DATETIME_LIST),
4784 )),
4785 }
4786 }
4787 }
4788
4789 /// Remove a `Duration` object from the underlying q timespan list.
4790 /// # Example
4791 /// ```
4792 /// use kdbplus::qattribute;
4793 /// use kdbplus::ipc::*;
4794 /// use chrono::Duration;
4795 ///
4796 /// fn main() {
4797 /// let mut q_timespan_list = K::new_timespan_list(
4798 /// vec![
4799 /// Duration::nanoseconds(6782392639932),
4800 /// Duration::nanoseconds(219849398328832),
4801 /// ],
4802 /// qattribute::NONE,
4803 /// );
4804 /// let tail = q_timespan_list.remove_timespan(0).unwrap();
4805 /// assert_eq!(tail, Duration::nanoseconds(6782392639932));
4806 /// }
4807 /// ```
4808 pub fn remove_timespan(&mut self, index: usize) -> Result<Duration> {
4809 if index >= self.len() {
4810 // 0 length
4811 Err(Error::index_out_of_bounds(self.len(), index))
4812 } else {
4813 match self.0.qtype {
4814 qtype::TIMESPAN_LIST => Ok(Duration::nanoseconds(
4815 self.as_mut_vec::<J>().unwrap().remove(index),
4816 )),
4817 _ => Err(Error::invalid_operation(
4818 "remove_timespan",
4819 self.0.qtype,
4820 Some(qtype::TIMESPAN_LIST),
4821 )),
4822 }
4823 }
4824 }
4825
4826 /// Remove a `Duration` object from the underlying q minute list.
4827 /// # Example
4828 /// ```
4829 /// use kdbplus::qattribute;
4830 /// use kdbplus::ipc::*;
4831 /// use chrono::Duration;
4832 ///
4833 /// fn main() {
4834 /// let mut q_minute_list = K::new_minute_list(
4835 /// vec![Duration::minutes(1024), Duration::minutes(-503)],
4836 /// qattribute::NONE,
4837 /// );
4838 /// let tail = q_minute_list.remove_minute(1).unwrap();
4839 /// assert_eq!(tail, Duration::minutes(-503));
4840 /// }
4841 /// ```
4842 pub fn remove_minute(&mut self, index: usize) -> Result<Duration> {
4843 if index >= self.len() {
4844 // 0 length
4845 Err(Error::index_out_of_bounds(self.len(), index))
4846 } else {
4847 match self.0.qtype {
4848 qtype::MINUTE_LIST => Ok(Duration::minutes(
4849 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
4850 )),
4851 _ => Err(Error::invalid_operation(
4852 "remove_minute",
4853 self.0.qtype,
4854 Some(qtype::MINUTE_LIST),
4855 )),
4856 }
4857 }
4858 }
4859
4860 /// Remove a `Duration` object from the underlying q second list.
4861 /// # Example
4862 /// ```
4863 /// use kdbplus::qattribute;
4864 /// use kdbplus::ipc::*;
4865 /// use chrono::Duration;
4866 ///
4867 /// fn main() {
4868 /// let mut q_second_list = K::new_second_list(
4869 /// vec![Duration::seconds(-32467), Duration::seconds(73984)],
4870 /// qattribute::NONE,
4871 /// );
4872 /// let tail = q_second_list.remove_second(0).unwrap();
4873 /// assert_eq!(tail, Duration::seconds(-32467));
4874 /// }
4875 /// ```
4876 pub fn remove_second(&mut self, index: usize) -> Result<Duration> {
4877 if index >= self.len() {
4878 // 0 length
4879 Err(Error::index_out_of_bounds(self.len(), index))
4880 } else {
4881 match self.0.qtype {
4882 qtype::SECOND_LIST => Ok(Duration::seconds(
4883 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
4884 )),
4885 _ => Err(Error::invalid_operation(
4886 "remove_second",
4887 self.0.qtype,
4888 Some(qtype::SECOND_LIST),
4889 )),
4890 }
4891 }
4892 }
4893
4894 /// Remove a `Duration` object from the underlying q time list.
4895 /// # Example
4896 /// ```
4897 /// use kdbplus::qattribute;
4898 /// use kdbplus::ipc::*;
4899 /// use chrono::Duration;
4900 ///
4901 /// fn main() {
4902 /// let mut q_time_list = K::new_time_list(
4903 /// vec![
4904 /// Duration::milliseconds(902467),
4905 /// Duration::milliseconds(-23587934),
4906 /// Duration::milliseconds(278958528),
4907 /// ],
4908 /// qattribute::NONE,
4909 /// );
4910 /// let tail = q_time_list.remove_time(2).unwrap();
4911 /// assert_eq!(tail, Duration::milliseconds(278958528));
4912 /// }
4913 /// ```
4914 pub fn remove_time(&mut self, index: usize) -> Result<Duration> {
4915 if index >= self.len() {
4916 // 0 length
4917 Err(Error::index_out_of_bounds(self.len(), index))
4918 } else {
4919 match self.0.qtype {
4920 qtype::TIME_LIST => Ok(Duration::milliseconds(
4921 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
4922 )),
4923 _ => Err(Error::invalid_operation(
4924 "remove_time",
4925 self.0.qtype,
4926 Some(qtype::TIME_LIST),
4927 )),
4928 }
4929 }
4930 }
4931
4932 /// Remove an element as `K` object from the underlying q list.
4933 /// # Example
4934 /// ```
4935 /// use kdbplus::qattribute;
4936 /// use kdbplus::ipc::*;
4937 /// use chrono::prelude::*;
4938 /// use chrono::Duration;
4939 ///
4940 /// fn main() {
4941 /// let mut q_time_list = K::new_time_list(
4942 /// vec![
4943 /// Duration::milliseconds(902467),
4944 /// Duration::milliseconds(-23587934),
4945 /// ],
4946 /// qattribute::NONE,
4947 /// );
4948 /// let mut tail = q_time_list.remove(1).unwrap();
4949 /// assert_eq!(format!("{}", tail), String::from("-06:33:07.934"));
4950 ///
4951 /// let mut q_compound_list = K::new_compound_list(vec![
4952 /// K::new_long_list(vec![10000324_i64, -43890], qattribute::UNIQUE),
4953 /// K::new_symbol(String::from("fire")),
4954 /// K::new_timestamp_list(
4955 /// vec![
4956 /// Utc.ymd(2018, 4, 10).and_hms_nano(15, 47, 39, 758934332),
4957 /// Utc.ymd(2008, 12, 4).and_hms_nano(14, 12, 7, 548932080),
4958 /// ],
4959 /// qattribute::NONE,
4960 /// ),
4961 /// ]);
4962 /// tail = q_compound_list.remove(0).unwrap();
4963 /// assert_eq!(format!("{}", tail), String::from("`u#10000324 -43890"));
4964 /// }
4965 /// ```
4966 pub fn remove(&mut self, index: usize) -> Result<K> {
4967 if index >= self.len() {
4968 // 0 length
4969 Err(Error::index_out_of_bounds(self.len(), index))
4970 } else {
4971 match self.0.qtype {
4972 qtype::BOOL_LIST => Ok(K::new_bool(
4973 self.as_mut_vec::<G>().unwrap().remove(index) != 0,
4974 )),
4975 qtype::GUID_LIST => Ok(K::new_guid(self.as_mut_vec::<U>().unwrap().remove(index))),
4976 qtype::BYTE_LIST => Ok(K::new_byte(self.as_mut_vec::<G>().unwrap().remove(index))),
4977 qtype::SHORT_LIST => {
4978 Ok(K::new_short(self.as_mut_vec::<H>().unwrap().remove(index)))
4979 }
4980 qtype::INT_LIST => Ok(K::new_int(self.as_mut_vec::<I>().unwrap().remove(index))),
4981 qtype::LONG_LIST => Ok(K::new_long(self.as_mut_vec::<J>().unwrap().remove(index))),
4982 qtype::REAL_LIST => Ok(K::new_real(self.as_mut_vec::<E>().unwrap().remove(index))),
4983 qtype::FLOAT_LIST => {
4984 Ok(K::new_float(self.as_mut_vec::<F>().unwrap().remove(index)))
4985 }
4986 qtype::STRING => Ok(K::new_char(self.as_mut_string().unwrap().remove(index))),
4987 qtype::SYMBOL_LIST => {
4988 Ok(K::new_symbol(self.as_mut_vec::<S>().unwrap().remove(index)))
4989 }
4990 qtype::TIMESTAMP_LIST => Ok(K::new_timestamp(q_timestamp_to_datetime(
4991 self.as_mut_vec::<J>().unwrap().remove(index),
4992 ))),
4993 qtype::MONTH_LIST => Ok(K::new_month(q_month_to_date(
4994 self.as_mut_vec::<I>().unwrap().remove(index),
4995 ))),
4996 qtype::DATE_LIST => Ok(K::new_date(q_date_to_date(
4997 self.as_mut_vec::<I>().unwrap().remove(index),
4998 )?)),
4999 qtype::DATETIME_LIST => Ok(K::new_datetime(q_datetime_to_datetime(
5000 self.as_mut_vec::<F>().unwrap().remove(index),
5001 ))),
5002 qtype::TIMESPAN_LIST => Ok(K::new_timespan(Duration::nanoseconds(
5003 self.as_mut_vec::<J>().unwrap().remove(index),
5004 ))),
5005 qtype::MINUTE_LIST => Ok(K::new_minute(Duration::minutes(
5006 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
5007 ))),
5008 qtype::SECOND_LIST => Ok(K::new_second(Duration::seconds(
5009 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
5010 ))),
5011 qtype::TIME_LIST => Ok(K::new_time(Duration::milliseconds(
5012 self.as_mut_vec::<I>().unwrap().remove(index) as i64,
5013 ))),
5014 qtype::COMPOUND_LIST => Ok(self.as_mut_vec::<K>().unwrap().remove(index)),
5015 _ => Err(Error::invalid_operation("remove", self.0.qtype, None)),
5016 }
5017 }
5018 }
5019
5020 /// Add a pair of key-value to a q dictionary.
5021 /// # Example
5022 /// ```
5023 /// use kdbplus::qattribute;
5024 /// use kdbplus::ipc::*;
5025 /// use chrono::prelude::*;
5026 ///
5027 /// fn main() {
5028 /// let keys = K::new_int_list(vec![0, 1, 2], qattribute::NONE);
5029 /// let values = K::new_date_list(
5030 /// vec![
5031 /// NaiveDate::from_ymd_opt(2000, 1, 9).unwrap(),
5032 /// NaiveDate::from_ymd_opt(2001, 4, 10).unwrap(),
5033 /// NaiveDate::from_ymd_opt(2015, 3, 16).unwrap(),
5034 /// ],
5035 /// qattribute::NONE,
5036 /// );
5037 /// let mut q_dictionary = K::new_dictionary(keys, values).unwrap();
5038 ///
5039 /// q_dictionary
5040 /// .push_pair(&3, &NaiveDate::from_ymd_opt(2020, 8, 9).unwrap())
5041 /// .unwrap();
5042 /// assert_eq!(
5043 /// format!("{}", q_dictionary),
5044 /// String::from("0 1 2 3i!2000.01.09 2001.04.10 2015.03.16 2020.08.09")
5045 /// );
5046 /// }
5047 /// ```
5048 pub fn push_pair(&mut self, key: &dyn Any, value: &dyn Any) -> Result<()> {
5049 match self.0.qtype {
5050 qtype::DICTIONARY => {
5051 let dictionary = self.as_mut_vec::<K>().unwrap();
5052 match dictionary[0].push(key) {
5053 Ok(_) => match dictionary[1].push(value) {
5054 Ok(_) => Ok(()),
5055 Err(error) => {
5056 // Revert the change to the key
5057 dictionary[0].pop().unwrap();
5058 Err(error)
5059 }
5060 },
5061 Err(error) => Err(error),
5062 }
5063 }
5064 _ => Err(Error::invalid_operation(
5065 "push_pair",
5066 self.0.qtype,
5067 Some(qtype::DICTIONARY),
5068 )),
5069 }
5070 }
5071
5072 /// Pop the last key-vaue pair from a q dictionary.
5073 /// # Example
5074 /// ```
5075 /// use kdbplus::qattribute;
5076 /// use kdbplus::ipc::*;
5077 /// use chrono::prelude::*;
5078 ///
5079 /// fn main() {
5080 /// let keys = K::new_int_list(vec![0, 1, 2], qattribute::NONE);
5081 /// let values = K::new_date_list(
5082 /// vec![
5083 /// NaiveDate::from_ymd_opt(2000, 1, 9).unwrap(),
5084 /// NaiveDate::from_ymd_opt(2001, 4, 10).unwrap(),
5085 /// NaiveDate::from_ymd_opt(2015, 3, 16).unwrap(),
5086 /// ],
5087 /// qattribute::NONE,
5088 /// );
5089 /// let mut q_dictionary = K::new_dictionary(keys, values).unwrap();
5090 ///
5091 /// q_dictionary.pop_pair().unwrap();
5092 /// assert_eq!(
5093 /// format!("{}", q_dictionary),
5094 /// String::from("0 1i!2000.01.09 2001.04.10")
5095 /// );
5096 /// }
5097 /// ```
5098 pub fn pop_pair(&mut self) -> Result<(K, K)> {
5099 match self.0.qtype {
5100 qtype::DICTIONARY => {
5101 let dictionary = self.as_mut_vec::<K>().unwrap();
5102 if let (Ok(key), Ok(value)) = (dictionary[0].pop(), dictionary[1].pop()) {
5103 Ok((key, value))
5104 } else {
5105 // Dictionary type assures the result is one of failure for both key and value, or success for both key and value.
5106 Err(Error::pop_from_empty_list())
5107 }
5108 }
5109 _ => Err(Error::invalid_operation(
5110 "pop_pair",
5111 self.0.qtype,
5112 Some(qtype::DICTIONARY),
5113 )),
5114 }
5115 }
5116
5117 /// Get the length of q object. The meaning of the returned value varies according to the type:
5118 /// - atom: 1
5119 /// - list: The number of elements in the list.
5120 /// - table: The number of rows.
5121 /// - dictionary: The number of keys.
5122 /// - general null: 1
5123 /// # Example
5124 /// ```
5125 /// use kdbplus::qattribute;
5126 /// use kdbplus::ipc::*;
5127 /// use chrono::prelude::*;
5128 ///
5129 /// fn main() {
5130 /// let q_symbol_list = K::new_symbol_list(
5131 /// vec![
5132 /// String::from("almond"),
5133 /// String::from("macadamia"),
5134 /// String::from("hazel"),
5135 /// ],
5136 /// qattribute::NONE,
5137 /// );
5138 /// assert_eq!(q_symbol_list.len(), 3);
5139 ///
5140 /// let keys = K::new_int_list(vec![0, 1, 2], qattribute::NONE);
5141 /// let values = K::new_date_list(
5142 /// vec![
5143 /// NaiveDate::from_ymd_opt(2000, 1, 9).unwrap(),
5144 /// NaiveDate::from_ymd_opt(2001, 4, 10).unwrap(),
5145 /// NaiveDate::from_ymd_opt(2015, 3, 16).unwrap(),
5146 /// ],
5147 /// qattribute::NONE,
5148 /// );
5149 /// let mut q_dictionary = K::new_dictionary(keys, values).unwrap();
5150 /// assert_eq!(q_dictionary.len(), 3);
5151 /// }
5152 /// ```
5153 pub fn len(&self) -> usize {
5154 match self.0.qtype {
5155 _t @ qtype::COMPOUND_LIST..=qtype::TIME_LIST => {
5156 // List
5157 match &self.0.value {
5158 // string is stored as symbol (`String`).
5159 k0_inner::symbol(string) => string.len(),
5160 // The other lists.
5161 k0_inner::list(list) => list.n as usize,
5162 _ => unreachable!(),
5163 }
5164 }
5165 qtype::TABLE => {
5166 // Table
5167 match &self.0.value {
5168 k0_inner::table(dictionary) => {
5169 // Dictionary is a vector of [K (keys), K (values)]
5170 // values is assured to be a list of K as this is a table type.
5171 // Retrieve the first column and get its length.
5172 match &dictionary.as_vec::<K>().unwrap()[1].as_vec::<K>().unwrap()[0]
5173 .0
5174 .value
5175 {
5176 k0_inner::list(column) => {
5177 // Return the number of rows
5178 column.n as usize
5179 }
5180 k0_inner::symbol(column) => {
5181 // char column
5182 // Return the number of rows
5183 column.len()
5184 }
5185 _ => unreachable!(),
5186 }
5187 }
5188 _ => unreachable!(),
5189 }
5190 }
5191 qtype::DICTIONARY | qtype::SORTED_DICTIONARY => {
5192 // Dictionary is a vector of [K (keys), K (values)]
5193 // Get keys and return its length.
5194 match &self.as_vec::<K>().unwrap()[0].0.value {
5195 k0_inner::list(list) => list.n as usize,
5196 // Keyed table
5197 // Get the number of rows by deligating it to table.len()
5198 k0_inner::table(_) => self.as_vec::<K>().unwrap()[0].len(),
5199 _ => unreachable!(),
5200 }
5201 }
5202 // Atom and general null
5203 _ => 1,
5204 }
5205 }
5206
5207 /// Create a table object from a dictionary object. Return value is either of:
5208 /// - `Err(original value)`: If the argument is not a dictionary. The returned object
5209 /// is wrapped in error enum and can be retrieved by [`into_inner`](error/enum.Error.html#method.into_inner).
5210 /// - `Ok(table)`: In case of successful conversion.
5211 /// # Note
5212 /// - Key type must be a symbol.
5213 /// - This function does not check if lengths of columns are same.
5214 /// # Example
5215 /// ```
5216 /// use kdbplus::qattribute;
5217 /// use kdbplus::ipc::*;
5218 ///
5219 /// fn main() {
5220 /// let q_dictionary = K::new_dictionary(
5221 /// K::new_symbol_list(
5222 /// vec![String::from("a"), String::from("b"), String::from("c")],
5223 /// qattribute::NONE,
5224 /// ),
5225 /// K::new_compound_list(vec![
5226 /// K::new_int_list(vec![10, 20, 30], qattribute::NONE),
5227 /// K::new_symbol_list(
5228 /// vec![
5229 /// String::from("honey"),
5230 /// String::from("sugar"),
5231 /// String::from("maple"),
5232 /// ],
5233 /// qattribute::NONE,
5234 /// ),
5235 /// K::new_bool_list(vec![false, false, true], qattribute::NONE),
5236 /// ]),
5237 /// )
5238 /// .unwrap();
5239 ///
5240 /// let q_table = q_dictionary.flip().unwrap();
5241 /// assert_eq!(
5242 /// format!("{}", q_table),
5243 /// String::from("+`a`b`c!(10 20 30i;`honey`sugar`maple;001b)")
5244 /// );
5245 /// }
5246 /// ```
5247 pub fn flip(self) -> Result<Self> {
5248 match self.0.qtype {
5249 qtype::DICTIONARY | qtype::SORTED_DICTIONARY => {
5250 let keys_values = (&self).as_vec::<K>().unwrap();
5251 if keys_values[0].0.qtype == qtype::SYMBOL_LIST
5252 && keys_values[1].0.qtype == qtype::COMPOUND_LIST
5253 {
5254 Ok(K::new(
5255 qtype::TABLE,
5256 qattribute::NONE,
5257 k0_inner::table(self),
5258 ))
5259 } else {
5260 Err(Error::object(self))
5261 }
5262 }
5263 // Failed to convert. Return the original argument.
5264 _ => Err(Error::object(self)),
5265 }
5266 }
5267
5268 /// Convert a table into a keyed table with the first `n` columns ebing keys.
5269 /// In case of error for type mismatch the original object is returned wrapped
5270 /// in error enum and can be retrieved by [`into_inner`](error/enum.Error.html#method.into_inner).
5271 /// # Example
5272 /// ```
5273 /// use kdbplus::qattribute;
5274 /// use kdbplus::ipc::*;
5275 ///
5276 /// fn main() {
5277 /// let q_dictionary = K::new_dictionary(
5278 /// K::new_symbol_list(
5279 /// vec![String::from("a"), String::from("b"), String::from("c")],
5280 /// qattribute::NONE,
5281 /// ),
5282 /// K::new_compound_list(vec![
5283 /// K::new_int_list(vec![10, 20, 30], qattribute::NONE),
5284 /// K::new_symbol_list(
5285 /// vec![
5286 /// String::from("honey"),
5287 /// String::from("sugar"),
5288 /// String::from("maple"),
5289 /// ],
5290 /// qattribute::NONE,
5291 /// ),
5292 /// K::new_bool_list(vec![false, false, true], qattribute::NONE),
5293 /// ]),
5294 /// )
5295 /// .unwrap();
5296 ///
5297 /// let q_table = q_dictionary.flip().unwrap();
5298 /// let q_keyed_table = q_table.enkey(1).unwrap();
5299 /// assert_eq!(
5300 /// format!("{}", q_keyed_table),
5301 /// String::from("(+,`a!,10 20 30i)!(+`b`c!(`honey`sugar`maple;001b))")
5302 /// );
5303 /// }
5304 /// ```
5305 pub fn enkey(self, mut n: usize) -> Result<Self> {
5306 match self.0.value {
5307 k0_inner::table(mut dictionary) => {
5308 let headers_columns = dictionary.as_mut_vec::<K>().unwrap();
5309 if headers_columns[0].len() <= n {
5310 // Maximum number of keys are #columns - 1
5311 n = headers_columns[0].len() - 1;
5312 }
5313 let value_heders = K::new_symbol_list(
5314 headers_columns[0].as_mut_vec::<S>().unwrap().split_off(n),
5315 qattribute::NONE,
5316 );
5317 let value_columns = K::new_compound_list(
5318 headers_columns[1].as_mut_vec::<K>().unwrap().split_off(n),
5319 );
5320 // Build value table
5321 let value_table = K::new_dictionary(value_heders, value_columns)
5322 .unwrap()
5323 .flip()
5324 .unwrap();
5325 Ok(K::new_dictionary(dictionary.flip().unwrap(), value_table)
5326 .expect("failed to build keyed table"))
5327 }
5328 // Not a table. Return the original argument.
5329 _ => Err(Error::object(self)),
5330 }
5331 }
5332
5333 /// Convert a keyed table into an ordinary table. In case of error for type mismatch
5334 /// the original object is returned wrapped in error enum and can be retrieved by [`into_inner`](error/enum.Error.html#method.into_inner).
5335 /// # Example
5336 /// ```
5337 /// use kdbplus::qattribute;
5338 /// use kdbplus::ipc::*;
5339 ///
5340 /// fn main() {
5341 /// let q_dictionary = K::new_dictionary(
5342 /// K::new_symbol_list(
5343 /// vec![String::from("a"), String::from("b"), String::from("c")],
5344 /// qattribute::NONE,
5345 /// ),
5346 /// K::new_compound_list(vec![
5347 /// K::new_int_list(vec![10, 20, 30], qattribute::NONE),
5348 /// K::new_symbol_list(
5349 /// vec![
5350 /// String::from("honey"),
5351 /// String::from("sugar"),
5352 /// String::from("maple"),
5353 /// ],
5354 /// qattribute::NONE,
5355 /// ),
5356 /// K::new_bool_list(vec![false, false, true], qattribute::NONE),
5357 /// ]),
5358 /// )
5359 /// .unwrap();
5360 ///
5361 /// let q_table = q_dictionary.flip().unwrap();
5362 /// let q_keyed_table = q_table.enkey(1).unwrap();
5363 /// assert_eq!(
5364 /// format!("{}", q_keyed_table),
5365 /// String::from("(+,`a!,10 20 30i)!(+`b`c!(`honey`sugar`maple;001b))")
5366 /// );
5367 /// let revived_table = q_keyed_table.unkey().unwrap();
5368 /// assert_eq!(
5369 /// format!("{}", revived_table),
5370 /// String::from("+`a`b`c!(10 20 30i;`honey`sugar`maple;001b)")
5371 /// );
5372 /// }
5373 /// ```
5374 pub fn unkey(mut self) -> Result<Self> {
5375 match self.0.qtype {
5376 qtype::DICTIONARY => {
5377 // Key table and value table
5378 let value_table = self.as_mut_vec::<K>().unwrap().pop().unwrap();
5379 let key_table = self.as_mut_vec::<K>().unwrap().pop().unwrap();
5380 match (key_table.0.value, value_table.0.value) {
5381 (
5382 k0_inner::table(mut key_dictionary),
5383 k0_inner::table(mut value_dictionary),
5384 ) => {
5385 // Key dictionary and value dictionary
5386 key_dictionary
5387 .as_mut_vec::<K>()
5388 .unwrap()
5389 .into_iter()
5390 .zip(value_dictionary.as_mut_vec::<K>().unwrap().into_iter())
5391 .enumerate()
5392 .for_each(|(i, (key, value))| {
5393 // Merge key component and value component
5394 if i == 0 {
5395 // Header
5396 key.as_mut_vec::<S>()
5397 .unwrap()
5398 .append(value.as_mut_vec::<S>().unwrap());
5399 } else {
5400 // Column
5401 key.as_mut_vec::<K>()
5402 .unwrap()
5403 .append(value.as_mut_vec::<K>().unwrap());
5404 }
5405 });
5406 // Flip joint dictionary to table
5407 key_dictionary.flip()
5408 }
5409 _ => unreachable!(),
5410 }
5411 }
5412 // Not a keyed table. Return the original argument.
5413 _ => Err(Error::object(self)),
5414 }
5415 }
5416}
5417
5418//++++++++++++++++++++++++++++++++++++++++++++++++++//
5419// >> Private Functions
5420//++++++++++++++++++++++++++++++++++++++++++++++++++//
5421
5422//%% Constructors //%%vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
5423
5424/// Convert `DateTime<Utc>` into `i64`. The returned value is an elapsed time in nanoseconds since `2000.01.01D00:00:00`.
5425/// If the nanoseconds value is not between 1677-09-21T00:12:43.145224192 and 2262-04-11T23:47:16.854775807, it returns `i64::MIN` which is `0Np` in q/kdb+.
5426/// # Note
5427/// For the range of valid `DateTime`, see [`chrono`](https://docs.rs/chrono/latest/chrono/struct.DateTime.html#method.timestamp_nanos).
5428fn datetime_to_q_timestamp(timestamp: DateTime<Utc>) -> i64 {
5429 // q |----------------------------------------|
5430 // Rust |----------------------------------------------------|
5431
5432 if timestamp <= *qnull::TIMESTAMP {
5433 // 0Np
5434 qnull_base::J
5435 } else if timestamp == *qninf::TIMESTAMP {
5436 // -0Wp
5437 qninf_base::J
5438 } else if timestamp >= *qinf::TIMESTAMP {
5439 // 0Wp
5440 qinf_base::J
5441 } else {
5442 timestamp
5443 .timestamp_nanos_opt()
5444 // This is null `0N`
5445 .unwrap_or(i64::MIN)
5446 .saturating_sub(KDB_TIMESTAMP_OFFSET)
5447 }
5448}
5449
5450/// Convert `Date<Utc>` into `i32`. The returned value is an elapsed time in months since `2000.01.01`.
5451fn date_to_q_month(month: NaiveDate) -> i32 {
5452 // q |------------------------------------------------------|
5453 // Rust |----------------------------------------|
5454
5455 if month == qnull::MONTH {
5456 // 0Nm
5457 qnull_base::I
5458 } else if month == *qninf::MONTH {
5459 // -0Wm
5460 qninf_base::I
5461 } else if month >= *qinf::MONTH {
5462 // 0Wm
5463 qinf_base::I
5464 } else {
5465 let months = (month.year() - 1970) * 12 + month.month0() as i32;
5466 months.saturating_sub(KDB_MONTH_OFFSET)
5467 }
5468}
5469
5470/// Convert `Date<Utc>` into `i32`. The returned value is an elapsed time in days since `2000.01.01`.
5471fn date_to_q_date(date: NaiveDate) -> i32 {
5472 // q |------------------------------------------------------|
5473 // Rust |-----------------------------------------|
5474
5475 if date == qnull::DATE {
5476 // 0Nd
5477 qnull_base::I
5478 } else if date == *qninf::DATE {
5479 // -0Wd
5480 qninf_base::I
5481 } else if date == qinf::DATE {
5482 // 0Wd
5483 qinf_base::I
5484 } else {
5485 let days =
5486 NaiveDate::signed_duration_since(date, NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
5487 .num_days() as i32;
5488 days.saturating_sub(KDB_DAY_OFFSET)
5489 }
5490}
5491
5492/// Convert `Date<Utc>` into `i32`. The returned value is an elapsed time in days since `2000.01.01`.
5493fn datetime_to_q_datetime(datetime: DateTime<Utc>) -> f64 {
5494 // q |------------------------------------------------------|
5495 // Rust |-----------------------------------------|
5496
5497 if datetime == qnull::DATETIME {
5498 // 0Nz
5499 qnull_base::F
5500 } else if datetime <= *qninf::DATETIME {
5501 // -0Wz
5502 qninf_base::F
5503 } else if datetime >= *qinf::DATETIME {
5504 // 0Wz
5505 qinf_base::F
5506 } else {
5507 let millis = datetime.timestamp_millis() as f64 / ONE_DAY_MILLIS as f64;
5508 millis - KDB_DAY_OFFSET as f64
5509 }
5510}
5511
5512//%% Getter //%%vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/
5513
5514/// Convert q timestamp (elapsed time in nanoseconds since `2000.01.01D00:00:00`) into `DateTime<Utc>`.
5515pub fn q_timestamp_to_datetime(nanos: i64) -> DateTime<Utc> {
5516 // q |----------------------------------------|
5517 // Rust |----------------------------------------------------|
5518
5519 // Add duration to avoid overflow
5520 Utc.timestamp_nanos(nanos) + Duration::nanoseconds(KDB_TIMESTAMP_OFFSET)
5521}
5522
5523/// Convert q month (elapsed time in months since `2000.01.01`) into `Date<Utc>`.
5524pub fn q_month_to_date(months: i32) -> NaiveDate {
5525 // q |------------------------------------------------------|
5526 // Rust |-----------------------------------------|
5527
5528 if months == qnull_base::I {
5529 qnull::MONTH
5530 } else if months <= -3171072 {
5531 // Consider pulling month value from q, not only reverse Rust->q.
5532 // Convert Date::signed_duration_since(chrono::MIN_DATE, Utc.ymd(2000, 1,1)).num_days()) into months
5533 // with 1461 as 4 years, 36525 as 100 years and 146097 as 400 years
5534 *qninf::MONTH
5535 } else if months >= 3121728 {
5536 // Consider pulling month value from q, not only reverse Rust->q.
5537 // Convert Date::signed_duration_since(chrono::MAX_DATE - Duration::days(30), Utc.ymd(2000, 1,1)).num_days()) into months
5538 // with 1461 as 4 years, 36525 as 100 years and 146097 as 400 years
5539 *qinf::MONTH
5540 } else {
5541 NaiveDate::from_ymd_opt(2000 + months / 12, 1 + (months % 12) as u32, 1).unwrap()
5542 }
5543}
5544
5545/// Convert q month (elapsed time in days since `2000.01.01`) into `Date<Utc>`.
5546pub fn q_date_to_date(days: i32) -> Result<NaiveDate> {
5547 // q |------------------------------------------------------|
5548 // Rust |-----------------------------------------|
5549
5550 if days == qnull_base::I {
5551 Ok(qnull::DATE)
5552 } else if days <= -96476615 {
5553 // Consider pulling date value from q, not only reverse Rust->q.
5554 // Date::signed_duration_since(chrono::MIN_DATE, Utc.ymd(2000, 1,1)).num_days())
5555 Ok(*qninf::DATE)
5556 } else if days >= 95015644 {
5557 // Consider pulling date value from q, not only reverse Rust->q.
5558 // Date::signed_duration_since(chrono::MAX_DATE, Utc.ymd(2000, 1,1)).num_days())
5559 Ok(qinf::DATE)
5560 } else {
5561 Ok((NaiveDate::from_ymd_opt(2000, 1, 1)
5562 .ok_or_else(|| Error::InvalidDateTime)?
5563 .and_hms_opt(0, 0, 0)
5564 .ok_or_else(|| Error::InvalidDateTime)?
5565 .and_local_timezone(Utc)
5566 .unwrap()
5567 + Duration::days(days as i64))
5568 .date_naive())
5569 }
5570}
5571
5572/// Convert q datetime (elapsed time in days with glanularity of milliseconds since `2000.01.01T00:00:00`) into `DateTime<Utc>`.
5573pub fn q_datetime_to_datetime(days: f64) -> DateTime<Utc> {
5574 // q |------------------------------------------------------|
5575 // Rust |-----------------------------------------|
5576
5577 if days.is_nan() {
5578 qnull::DATETIME
5579 } else if days <= -96476615 as f64 {
5580 // Consider pulling datetime value from q, not only reverse Rust->q.
5581 // DateTime::signed_duration_since(chrono::MIN_DATETIME, Utc.ymd(2000,1,1).and_hms_nano(0, 0, 0, 0)).num_days())
5582 *qninf::DATETIME
5583 } else if days >= 95015644 as f64 {
5584 // Consider pulling datetime value from q, not only reverse Rust->q.
5585 // DateTime::signed_duration_since(chrono::MAX_DATETIME, Utc.ymd(2000,1,1).and_hms_nano(0, 0, 0, 0)).num_days())
5586 *qinf::DATETIME
5587 } else {
5588 Utc.timestamp_millis_opt((ONE_DAY_MILLIS as f64 * (days + KDB_DAY_OFFSET as f64)) as i64)
5589 .unwrap()
5590 }
5591}
5592
5593/// Convert q timespan into `Duration`.
5594pub fn q_timespan_to_duration(nanos: i64) -> Duration {
5595 Duration::nanoseconds(nanos)
5596}
5597
5598/// Convert q minute into `Duration`.
5599pub fn q_minute_to_duration(minutes: i32) -> Duration {
5600 Duration::minutes(minutes as i64)
5601}
5602
5603/// Convert q second into `Duration`.
5604pub fn q_second_to_duration(seconds: i32) -> Duration {
5605 Duration::seconds(seconds as i64)
5606}
5607
5608/// Convert q time into `Duration`.
5609pub fn q_time_to_duration(millis: i32) -> Duration {
5610 Duration::milliseconds(millis as i64)
5611}
5612
5613//++++++++++++++++++++++++++++++++++++++++++++++++++//
5614// >> Load Modules
5615//++++++++++++++++++++++++++++++++++++++++++++++++++//
5616
5617mod connection;
5618mod deserialize;
5619mod format;
5620mod serialize;
5621// Inject into `ipc` namespace.
5622pub use connection::*;