rumtk-core 0.7.0

Core library for providing general functionality to support the other RUMTK crates. See rumtk-hl7-v2 crate as example
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
 * This toolkit aims to be reliable, simple, performant, and standards compliant.
 * Copyright (C) 2024  Luis M. Santos, M.D.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

//#![feature(unboxed_closures)]
#![feature(inherent_associated_types)]
#![feature(type_alias_impl_trait)]
#![feature(unboxed_closures)]

pub mod cache;
pub mod cli;
pub mod core;
pub mod json;
pub mod log;
pub mod maths;
pub mod net;
pub mod queue;
pub mod search;
pub mod strings;
pub mod threading;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::RUMCache;
    use crate::search::rumtk_search::*;
    use crate::strings::{RUMArrayConversions, RUMString, RUMStringConversions, StringUtils};
    use compact_str::{format_compact, CompactString};
    use serde::Deserialize;
    use std::future::IntoFuture;
    use std::sync::Arc;
    use tokio::sync::RwLock;

    #[test]
    fn test_escaping_control() {
        let input = "\r\n\'\"";
        let expected = "\\r\\n\\'\\\"";
        let result = strings::escape(&input);
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            expected,
            result.as_str()
        );
        assert_eq!(expected, result, "Incorrect string escaping!");
        println!("Passed!")
    }

    #[test]
    fn test_escaping_unicode() {
        let input = "";
        let expected = "\\u2764";
        let result = strings::escape(&input);
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            expected,
            result.as_str()
        );
        assert_eq!(expected, result, "Incorrect string escaping!");
        println!("Passed!")
    }

    #[test]
    fn test_unescaping_unicode() {
        let input = "";
        let escaped = strings::escape(&input);
        let expected = "";
        let result = RUMString::from_utf8(strings::unescape(&escaped.as_str()).unwrap()).unwrap();
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            expected,
            result.as_str()
        );
        assert_eq!(expected, result.as_str(), "Incorrect string unescaping!");
        println!("Passed!")
    }

    #[test]
    fn test_unescaping_string() {
        let input = "I \\u2764 my wife!";
        let expected = "I ❤ my wife!";
        let result = strings::unescape_string(&input).unwrap();
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            expected,
            result.as_str()
        );
        assert_eq!(expected, result.as_str(), "Incorrect string unescaping!");
        println!("Passed!")
    }

    #[test]
    fn test_unique_string() {
        let input = "I❤mywife!";
        assert!(input.is_unique(), "String was not detected as unique.");
    }

    #[test]
    fn test_non_unique_string() {
        let input = "I❤❤mywife!";
        assert!(!input.is_unique(), "String was detected as unique.");
    }

    #[test]
    fn test_escaping_string() {
        let input = "I ❤ my wife!";
        let expected = "I \\u2764 my wife!";
        let result = strings::escape(&input);
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            expected,
            result.as_str()
        );
        assert_eq!(expected, result.as_str(), "Incorrect string escaping!");
        println!("Passed!")
    }

    #[test]
    fn test_autodecode_utf8() {
        let input = "I ❤ my wife!";
        let result = strings::try_decode(input.as_bytes());
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            input,
            result.as_str()
        );
        assert_eq!(input, result, "Incorrect string decoding!");
        println!("Passed!")
    }

    #[test]
    fn test_autodecode_other() {
        //TODO: Need an example of other encoding texts.
        let input = "I ❤ my wife!";
        let expected = "I ❤ my wife!";
        let result = input;
        println!("Input: {} Expected: {} Got: {}", input, input, result);
        assert_eq!(input, result, "Incorrect string decoding!");
        println!("Passed!")
    }

    #[test]
    fn test_decode() {
        let input = "I ❤ my wife!";
        let expected = "I ❤ my wife!";
        let result = strings::try_decode_with(input.as_bytes(), "utf-8");
        println!(
            "Input: {} Expected: {} Got: {}",
            input,
            input,
            result.as_str()
        );
        assert_eq!(input, result, "Incorrect string decoding!");
        println!("Passed!")
    }

    #[test]
    fn test_rumcache_insertion() {
        let mut cache: RUMCache<&str, CompactString> = RUMCache::with_capacity(5);
        cache.insert("", CompactString::from("I ❤ my wife!"));
        println!("Contents: {:#?}", &cache);
        assert_eq!(cache.len(), 1, "Incorrect number of items in cache!");
        println!("Passed!")
    }

    #[test]
    fn test_search_string_letters() {
        let input = "Hello World!";
        let expr = r"\w";
        let result = string_search(input, expr, "");
        let expected: RUMString = RUMString::from("HelloWorld");
        println!(
            "Input: {:?} Expected: {:?} Got: {:?}",
            input, expected, result
        );
        assert_eq!(expected, result, "String search results mismatch");
        println!("Passed!")
    }

    #[test]
    fn test_search_string_words() {
        let input = "Hello World!";
        let expr = r"\w+";
        let result = string_search(input, expr, " ");
        let expected: RUMString = RUMString::from("Hello World");
        println!(
            "Input: {:?} Expected: {:?} Got: {:?}",
            input, expected, result
        );
        assert_eq!(expected, result, "String search results mismatch");
        println!("Passed!")
    }

    #[test]
    fn test_search_string_named_groups() {
        let input = "Hello World!";
        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
        let result = string_search_named_captures(input, expr, "");
        let expected: RUMString = RUMString::from("World");
        println!(
            "Input: {:?} Expected: {:?} Got: {:?}",
            input, expected, result
        );
        assert_eq!(expected, result["world"], "String search results mismatch");
        println!("Passed!")
    }

    #[test]
    fn test_search_string_all_groups() {
        let input = "Hello World!";
        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
        let result = string_search_all_captures(input, expr, "");
        let expected: Vec<&str> = vec!["Hello", "World"];
        println!(
            "Input: {:?} Expected: {:?} Got: {:?}",
            input, expected, result
        );
        assert_eq!(expected, result, "String search results mismatch");
        println!("Passed!")
    }

    ///////////////////////////////////Threading Tests/////////////////////////////////////////////////
    #[test]
    fn test_default_num_threads() {
        use num_cpus;
        let threads = threading::threading_functions::get_default_system_thread_count();
        assert_eq!(
            threads >= num_cpus::get(),
            true,
            "Default thread count is incorrect! We got {}, but expected {}!",
            threads,
            num_cpus::get()
        );
    }

    #[test]
    fn test_execute_job() {
        let rt = rumtk_init_threads!();
        let expected = vec![1, 2, 3];
        let task_processor = async |args: &SafeTaskArgs<i32>| -> TaskResult<i32> {
            let owned_args = Arc::clone(args);
            let lock_future = owned_args.read();
            let locked_args = lock_future.await;
            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
            print!("Contents: ");
            for arg in locked_args.iter() {
                results.push(arg.clone());
                println!("{} ", &arg);
            }
            Ok(results)
        };
        let locked_args = RwLock::new(expected.clone());
        let task_args = SafeTaskArgs::<i32>::new(locked_args);
        let task_result = rumtk_wait_on_task!(rt, task_processor, &task_args);
        let result = task_result.unwrap();
        assert_eq!(&result, &expected, "{}", format_compact!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
    }

    #[test]
    fn test_execute_job_macros() {
        let rt = rumtk_init_threads!();
        let expected = vec![1, 2, 3];
        let task_processor = async |args: &SafeTaskArgs<i32>| -> TaskResult<i32> {
            let owned_args = Arc::clone(args);
            let lock_future = owned_args.read();
            let locked_args = lock_future.await;
            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
            print!("Contents: ");
            for arg in locked_args.iter() {
                results.push(arg.clone());
                println!("{} ", &arg);
            }
            Ok(results)
        };
        let task_args = rumtk_create_task_args!(1, 2, 3);
        let task_result = rumtk_wait_on_task!(rt, task_processor, &task_args);
        let result = task_result.unwrap();
        assert_eq!(&result, &expected, "{}", format_compact!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
    }

    #[test]
    fn test_execute_job_macros_one_line() {
        let rt = rumtk_init_threads!();
        let expected = vec![1, 2, 3];
        let result = rumtk_exec_task!(
            async |args: &SafeTaskArgs<i32>| -> TaskResult<i32> {
                let owned_args = Arc::clone(args);
                let lock_future = owned_args.read();
                let locked_args = lock_future.await;
                let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
                print!("Contents: ");
                for arg in locked_args.iter() {
                    results.push(arg.clone());
                    println!("{} ", &arg);
                }
                Ok(results)
            },
            vec![1, 2, 3]
        )
        .unwrap();
        assert_eq!(&result, &expected, "{}", format_compact!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
    }

    #[test]
    fn test_clamp_index_positive_index() {
        let values = vec![1, 2, 3, 4];
        let given_index = 3isize;
        let max_size = values.len() as isize;
        let index = clamp_index(&given_index, &max_size).unwrap();
        assert_eq!(
            index, 3,
            "Index mismatch! Requested index {} but got {}",
            &given_index, &index
        );
        assert_eq!(
            values[index], 4,
            "Value mismatch! Expected {} but got {}",
            &values[3], &values[index]
        );
    }

    #[test]
    fn test_clamp_index_reverse_index() {
        let values = vec![1, 2, 3, 4];
        let given_index = -1isize;
        let max_size = values.len() as isize;
        let index = clamp_index(&given_index, &max_size).unwrap();
        assert_eq!(
            index, 4,
            "Index mismatch! Requested index {} but got {}",
            &given_index, &index
        );
        assert_eq!(
            values[index - 1],
            4,
            "Value mismatch! Expected {} but got {}",
            &values[3],
            &values[index]
        );
    }

    ///////////////////////////////////Queue Tests/////////////////////////////////////////////////
    use crate::core::clamp_index;
    use crate::json::serialization::Serialize;
    use crate::net::tcp::LOCALHOST;
    use crate::threading::thread_primitives::{SafeTaskArgs, TaskItems, TaskResult};
    use crate::threading::threading_functions::sleep;
    use queue::queue::*;

    #[test]
    fn test_queue_data() {
        let expected = vec![
            RUMString::from("Hello"),
            RUMString::from("World!"),
            RUMString::from("Overcast"),
            RUMString::from("and"),
            RUMString::from("Sad"),
        ];
        let mut queue = TaskQueue::<RUMString>::new(&5).unwrap();
        let locked_args = RwLock::new(expected.clone());
        let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
        let processor = rumtk_create_task!(
            async |args: &SafeTaskArgs<RUMString>| -> TaskResult<RUMString> {
                let owned_args = Arc::clone(args);
                let lock_future = owned_args.read();
                let locked_args = lock_future.await;
                let mut results = TaskItems::<RUMString>::with_capacity(locked_args.len());
                print!("Contents: ");
                for arg in locked_args.iter() {
                    print!("{} ", &arg);
                    results.push(RUMString::new(arg));
                }
                Ok(results)
            },
            task_args
        );
        queue.add_task::<_>(processor);
        let results = queue.wait();
        let mut result_data = Vec::<RUMString>::with_capacity(5);
        for r in results {
            for v in r.unwrap().iter() {
                result_data.push(v.clone());
            }
        }
        assert_eq!(result_data, expected, "Results do not match expected!");
    }

    ///////////////////////////////////Net Tests/////////////////////////////////////////////////
    #[test]
    fn test_server_start() {
        let mut server = match rumtk_create_server!("localhost", 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        }
    }

    #[test]
    fn test_server_send() {
        let msg = RUMString::from("Hello World!");
        let mut server = match rumtk_create_server!(LOCALHOST, 0, 1) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        let address_info = server.get_address_info().unwrap();
        let (ip, port) = rumtk_get_ip_port!(address_info);
        println!("Sleeping");
        rumtk_sleep!(1);
        let mut client = match rumtk_connect!(port) {
            Ok(client) => client,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        let client_id = client.get_address().unwrap();
        rumtk_sleep!(1);
        match server.send(&client_id, &msg.to_raw()) {
            Ok(_) => (),
            Err(e) => panic!("Server failed to send message because {}", e),
        };
        rumtk_sleep!(1);
        let received_message = client.receive().unwrap();
        assert_eq!(
            &msg.to_raw(),
            &received_message,
            "{}",
            format_compact!(
                "Received message does not match sent message by server {:?}",
                &received_message
            )
        );
    }

    #[test]
    fn test_server_receive() {
        let msg = RUMString::from("Hello World!");
        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        let address_info = server.get_address_info().unwrap();
        let (ip, port) = rumtk_get_ip_port!(address_info);
        println!("Sleeping");
        rumtk_sleep!(1);
        let mut client = match rumtk_connect!(port) {
            Ok(client) => client,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match client.send(&msg.to_raw()) {
            Ok(_) => (),
            Err(e) => panic!("Failed to send message because {}", e),
        };
        rumtk_sleep!(1);
        let client_id = client.get_address().expect("Failed to get client id");
        let incoming_message = server.receive(&client_id).unwrap().to_rumstring();
        println!("Received message => {:?}", &incoming_message);
        assert_eq!(&incoming_message, msg, "Received message corruption!");
    }

    #[test]
    fn test_server_get_clients() {
        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        let address_info = server.get_address_info().unwrap();
        let (ip, port) = rumtk_get_ip_port!(address_info);
        println!("Sleeping");
        rumtk_sleep!(1);
        let mut client = match rumtk_connect!(port) {
            Ok(client) => client,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        rumtk_sleep!(1);
        let expected_client_id = client.get_address().expect("Failed to get client id");
        let clients = server.get_client_ids();
        let incoming_client_id = clients.get(0).expect("Expected client to have connected!");
        println!("Connected client id => {}", &incoming_client_id);
        assert_eq!(
            &incoming_client_id, &expected_client_id,
            "Connected client does not match the connecting client! Client id => {}",
            &incoming_client_id
        );
    }

    #[test]
    fn test_server_stop() {
        let msg = RUMString::from("Hello World!");
        let mut server = match rumtk_create_server!("localhost", 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        println!("Sleeping");
        rumtk_sleep!(1);
        match server.stop() {
            Ok(_) => (),
            Err(e) => panic!("Failed to stop server because {}", e),
        };
    }

    #[test]
    fn test_server_get_address_info() {
        let msg = RUMString::from("Hello World!");
        let mut server = match rumtk_create_server!("localhost", 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        println!("Sleeping");
        rumtk_sleep!(1);
        match server.get_address_info() {
            Some(addr) => println!("Server address info => {}", addr),
            None => panic!("No address. Perhaps the server was never initialized?"),
        };
    }

    #[test]
    fn test_client_send() {
        let msg = RUMString::from("Hello World!");
        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
            Ok(server) => server,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        match server.start(false) {
            Ok(_) => (),
            Err(e) => panic!("Failed to start server because {}", e),
        };
        let address_info = server.get_address_info().unwrap();
        let (ip, port) = rumtk_get_ip_port!(address_info);
        println!("Sleeping");
        rumtk_sleep!(1);
        let mut client = match rumtk_connect!(port) {
            Ok(client) => client,
            Err(e) => panic!("Failed to create server because {}", e),
        };
        rumtk_sleep!(2);
        match client.send(&msg.to_raw()) {
            Ok(_) => (),
            Err(e) => panic!("Failed to send message because {}", e),
        };
        rumtk_sleep!(1);
        let clients = server.get_client_ids();
        let incoming_client_id = clients.first().expect("Expected client to have connected!");
        let mut received_message = server.receive(incoming_client_id).unwrap();
        if received_message.is_empty() {
            rumtk_sleep!(1);
            received_message = server.receive(incoming_client_id).unwrap();
        }
        assert_eq!(
            &msg.to_raw(),
            &received_message,
            "{}",
            format_compact!(
                "Received message does not match sent message by client {:?}",
                &received_message
            )
        );
    }

    ////////////////////////////JSON Tests/////////////////////////////////

    #[test]
    fn test_serialize_json() {
        #[derive(Serialize)]
        struct MyStruct {
            hello: RUMString,
        }

        let hw = MyStruct {
            hello: RUMString::from("World"),
        };
        let hw_str = rumtk_serialize!(&hw, true).unwrap();

        assert!(
            !hw_str.is_empty(),
            "Empty JSON string generated from the test struct!"
        );
    }

    #[test]
    fn test_deserialize_json() {
        #[derive(Serialize, Deserialize, PartialEq)]
        struct MyStruct {
            hello: RUMString,
        }

        let hw = MyStruct {
            hello: RUMString::from("World"),
        };
        let hw_str = rumtk_serialize!(&hw, true).unwrap();
        let new_hw: MyStruct = rumtk_deserialize!(&hw_str).unwrap();

        assert!(
            new_hw == hw,
            "Deserialized JSON does not match the expected value!"
        );
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
}