Skip to main content

rumtk_core/
lib.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2024  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20
21//#![feature(unboxed_closures)]
22//#![feature(inherent_associated_types)]
23#![feature(type_alias_impl_trait)]
24#![feature(unboxed_closures)]
25#![feature(buf_read_has_data_left)]
26#![feature(mapped_lock_guards)]
27#![feature(str_as_str)]
28#![feature(const_trait_impl)]
29#![feature(const_cmp)]
30#![feature(macro_metavar_expr)]
31#![feature(const_default)]
32#![feature(portable_simd)]
33#![feature(write_all_vectored)]
34
35pub mod cache;
36pub mod cli;
37pub mod base;
38pub mod dependencies;
39pub mod hash;
40pub mod id;
41pub mod serde;
42pub mod log;
43pub mod maths;
44pub mod net;
45pub mod pipelines;
46pub mod scripting;
47pub mod strings;
48pub mod threading;
49pub mod types;
50pub mod instrumentation;
51pub mod regex;
52
53pub use rumtk_arena::buffers;
54pub use rumtk_arena::cpu;
55pub use rumtk_arena::mem;
56
57pub use rumtk_arena::*;
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::base::{clamp_index, RUMResult};
63    use crate::buffers::*;
64    use crate::buffers::{buffer_count, buffer_find, buffer_replace, buffer_replace_in_place, buffer_slice_trim, buffer_to_string, buffer_trim, new_random_buffer, RUMBufferIteratorExt};
65    use crate::cache::RUMCache;
66    use crate::cpu::cpu_replace_byte;
67    use crate::regex::*;
68    use crate::serde::{from_json, to_json, RUMDeJson, RUMSerJson};
69    use crate::strings::{rumtk_format, AsStr, RUMArrayConversions, RUMString, RUMStringConversions, ASCII_ESCAPE_PREFIX_DEFAULT};
70    use std::process::Stdio;
71    use std::sync::Arc;
72    use std::thread::spawn;
73    use std::usize;
74    use tokio::io::AsyncBufReadExt;
75    use tokio::sync::RwLock;
76
77
78    use crate::cli::cli_utils::print_license_notice;
79    use crate::cpu::{cpu_collect, cpu_find, cpu_tokenize, CPU_SEARCH_WINDOW_16_SIZE};
80    use crate::hash::hash_data;
81    use crate::net::tcp::LOCALHOST;
82    use crate::pipelines::pipeline_functions::{pipeline_create_command, pipeline_patch_args, pipeline_pipe_processes, pipeline_spawn_process};
83    use crate::pipelines::pipeline_types::RUMCommand;
84    use crate::threading::threading_functions::block_on_task;
85    use crate::threading::threading_manager::*;
86
87    #[test]
88    fn test_is_escaped_str() {
89        let input = "\r\n\'\\\"";
90        let expected = false;
91        let result = strings::is_escaped_str(input);
92        println!("Input: {} Expected: {} Got: {}", input, expected, result);
93        assert_eq!(
94            expected, result,
95            "Incorrect detection of unescaped string as escaped!!"
96        );
97        println!("Passed!")
98    }
99
100    #[test]
101    fn test_escaping_control() {
102        let input = "\r\n\'\"\\\t";
103        let expected = "\r\n\'\"\\\\x0009";
104        let result = rumtk_string_escape!(input);
105        println!(
106            "Input: {} Expected: {} Got: {}",
107            input,
108            expected,
109            result.as_str()
110        );
111        assert_eq!(expected, result, "Incorrect string escaping!");
112        println!("Passed!")
113    }
114
115    #[test]
116    fn test_escaping_unicode() {
117        let input = "❤";
118        let expected = "\\x2764";
119        let result = rumtk_string_escape!(input);
120        println!(
121            "Input: {} Expected: {} Got: {}",
122            input,
123            expected,
124            result.as_str()
125        );
126        assert_eq!(expected, result, "Incorrect string escaping!");
127        println!("Passed!")
128    }
129
130    #[test]
131    fn test_unescaping_unicode() {
132        let input = "❤";
133        let escaped = rumtk_string_escape!(input, ASCII_ESCAPE_PREFIX_DEFAULT);
134        let expected = "❤";
135        let result = RUMString::from_utf8(strings::unescape(escaped.as_str()).unwrap()).unwrap();
136        println!(
137            "Input: {} Expected: {} Got: {}",
138            input,
139            expected,
140            result.as_str()
141        );
142        assert_eq!(expected, result.as_str(), "Incorrect string unescaping!");
143        println!("Passed!")
144    }
145
146    #[test]
147    fn test_unescaping_string() {
148        let input = "I \\u2764 my wife!";
149        let expected = "I ❤ my wife!";
150        let result = strings::unescape_string(input).unwrap();
151        println!(
152            "Input: {} Expected: {} Got: {}",
153            input,
154            expected,
155            result.as_str()
156        );
157        assert_eq!(expected, result.as_str(), "Incorrect string unescaping!");
158        println!("Passed!")
159    }
160
161    #[test]
162    fn test_is_escaped_string() {
163        let input = "I \\u2764 my wife!";
164        let expected = true;
165        let result = strings::is_escaped_str(input);
166        println!("Input: {} Expected: {} Got: {}", input, expected, result);
167        assert_eq!(
168            expected, result,
169            "Escaped string detected as unescaped string!"
170        );
171        println!("Passed!")
172    }
173
174    #[test]
175    fn test_is_unescaped_string() {
176        let input = "I ❤ my wife!";
177        let expected = false;
178        let result = strings::is_escaped_str(input);
179        println!("Input: {} Expected: {} Got: {}", input, expected, result);
180        assert_eq!(
181            expected, result,
182            "Unescaped string detected as escaped string!"
183        );
184        println!("Passed!")
185    }
186
187    #[test]
188    fn test_unique_string() {
189        let input = "I❤mywife!";
190        assert!(
191            input.as_grapheme_str().is_unique(),
192            "String was not detected as unique."
193        );
194    }
195
196    #[test]
197    fn test_non_unique_string() {
198        let input = "I❤❤mywife!";
199        assert!(
200            !input.as_grapheme_str().is_unique(),
201            "String was detected as unique."
202        );
203    }
204
205    #[test]
206    fn test_escaping_string() {
207        let input = "I ❤ my wife!";
208        let expected = "I \\x2764 my wife!";
209        let result = strings::string_escape(input, ASCII_ESCAPE_PREFIX_DEFAULT);
210        println!(
211            "Input: {} Expected: {} Got: {}",
212            input,
213            expected,
214            result.as_str()
215        );
216        assert_eq!(expected, result.as_str(), "Incorrect string escaping!");
217        println!("Passed!")
218    }
219
220    #[test]
221    fn test_escaping_string_macro() {
222        let input = "I ❤ my wife!";
223        let expected = "I \\x2764 my wife!";
224        let result = rumtk_string_escape!(input);
225        println!(
226            "Input: {} Expected: {} Got: {}",
227            input,
228            expected,
229            result.as_str()
230        );
231        assert_eq!(expected, result.as_str(), "Incorrect string escaping!");
232        println!("Passed!")
233    }
234
235    #[test]
236    fn test_escaping_string_macro_with_exception() {
237        let input = "I ❤ my wife!";
238        let expected = "I \\x2764 my wife!";
239        let result = rumtk_string_escape!(input, ASCII_ESCAPE_PREFIX_DEFAULT);
240        println!(
241            "Input: {} Expected: {} Got: {}",
242            input,
243            expected,
244            result.as_str()
245        );
246        assert_eq!(expected, result.as_str(), "Incorrect string escaping!");
247        println!("Passed!")
248    }
249
250    #[test]
251    fn test_autodecode_utf8() {
252        let input = "I ❤ my wife!";
253        let result = strings::string_try_decode(input.as_bytes()).unwrap();
254        println!(
255            "Input: {} Expected: {} Got: {}",
256            input,
257            input,
258            result.as_str()
259        );
260        assert_eq!(input, result, "Incorrect string decoding!");
261        println!("Passed!")
262    }
263
264    #[test]
265    fn test_autodecode_other() {
266        //TODO: Need an example of other encoding texts.
267        let input = "I ❤ my wife!";
268        let result = input;
269        println!("Input: {} Expected: {} Got: {}", input, input, result);
270        assert_eq!(input, result, "Incorrect string decoding!");
271        println!("Passed!")
272    }
273
274    #[test]
275    fn test_decode() {
276        let input = "I ❤ my wife!";
277        let result = strings::string_try_decode_with(input.as_bytes(), "utf-8").unwrap();
278        println!(
279            "Input: {} Expected: {} Got: {}",
280            input,
281            input,
282            result.as_str()
283        );
284        assert_eq!(input, result, "Incorrect string decoding!");
285        println!("Passed!")
286    }
287
288    #[test]
289    fn test_rumcache_insertion() {
290        let mut cache: RUMCache<&str, RUMString> = RUMCache::with_capacity(5);
291        cache.insert("❤", RUMString::from("I ❤ my wife!"));
292        println!("Contents: {:#?}", &cache);
293        assert_eq!(cache.len(), 1, "Incorrect number of items in cache!");
294        println!("Passed!")
295    }
296
297    #[test]
298    fn test_search_string_letters() {
299        let input = "Hello World!";
300        let expr = r"\w";
301        let result = string_search(input, expr).unwrap();
302        let expected: RUMString = RUMString::from("HelloWorld");
303        println!(
304            "Input: {:?} Expected: {:?} Got: {:?}",
305            input, expected, result
306        );
307        assert_eq!(expected, result, "String search results mismatch");
308        println!("Passed!")
309    }
310
311    #[test]
312    fn test_search_string_words() {
313        let input = "Hello World!";
314        let expr = r"\w+|\s+";
315        let result = string_search(input, expr).unwrap();
316        let expected: RUMString = RUMString::from("Hello World");
317        println!(
318            "Input: {:?} Expected: {:?} Got: {:?}",
319            input, expected, result
320        );
321        assert_eq!(expected, result, "String search results mismatch");
322        println!("Passed!")
323    }
324
325    #[test]
326    fn test_search_string_named_groups() {
327        let input = "Hello World!";
328        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
329        let result = string_search_named_captures(input, expr).unwrap();
330        let expected: RUMString = RUMString::from("World");
331        println!(
332            "Input: {:?} Expected: {:?} Got: {:?}",
333            input, expected, result
334        );
335        assert_eq!(expected, result["world"], "String search results mismatch");
336        println!("Passed!")
337    }
338
339    #[test]
340    fn test_search_string_all_groups() {
341        let input = "Hello World!";
342        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
343        let result = string_search_all_captures(input, expr).unwrap();
344        let expected: Vec<&str> = vec!["Hello", "World"];
345        println!(
346            "Input: {:?} Expected: {:?} Got: {:?}",
347            input, expected, result
348        );
349        assert_eq!(expected, result, "String search results mismatch");
350        println!("Passed!")
351    }
352
353    #[test]
354    fn test_find_value_in_string() {
355        let haystack = "Range (min \\xe2\\x80\\xa6 max):     0.6 ms \\xe2\\x80\\xa6   2.9 ms    1273 runs";
356        let patterns = ["\\d+ runs", "\\d+"];
357        let expected = 1273;
358        let result = string_find_value::<usize>(haystack, &patterns);
359
360        assert_eq!(result, Ok(expected), "Did not find the needle in the haystack or returned the wrong type!");
361    }
362
363    ///////////////////////////////////Threading Tests/////////////////////////////////////////////////
364    #[test]
365    fn test_default_num_threads() {
366        use num_cpus;
367        let threads = threading::threading_functions::get_default_system_thread_count();
368        assert_eq!(
369            threads >= num_cpus::get(),
370            true,
371            "Default thread count is incorrect! We got {}, but expected {}!",
372            threads,
373            num_cpus::get()
374        );
375    }
376
377    #[test]
378    fn test_execute_job() {
379        let expected = vec![1, 2, 3];
380        let task_processor = async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
381            let owned_args = Arc::clone(args);
382            let lock_future = owned_args.read();
383            let locked_args = lock_future.await;
384            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
385            print!("Contents: ");
386            for arg in locked_args.iter() {
387                results.push(arg.clone());
388                println!("{} ", &arg);
389            }
390            Ok(results)
391        };
392        let locked_args = RwLock::new(expected.clone());
393        let task_args = SafeTaskArgs::<i32>::new(locked_args);
394        let task_result = rumtk_wait_on_task!(task_processor, &task_args);
395        let result = task_result.unwrap();
396        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
397    }
398
399    #[test]
400    fn test_execute_job_macros() {
401        let expected = vec![1, 2, 3];
402        let task_processor = async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
403            let owned_args = Arc::clone(args);
404            let lock_future = owned_args.read();
405            let locked_args = lock_future.await;
406            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
407            print!("Contents: ");
408            for arg in locked_args.iter() {
409                results.push(arg.clone());
410                println!("{} ", &arg);
411            }
412            Ok(results)
413        };
414        let task_args = rumtk_create_task_args!(1, 2, 3);
415        let task_result = rumtk_wait_on_task!(task_processor, &task_args);
416        let result = task_result.unwrap();
417        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
418    }
419
420    #[test]
421    fn test_execute_job_macros_one_line() {
422        let expected = vec![1, 2, 3];
423        let result = rumtk_exec_task!(
424            async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
425                let owned_args = Arc::clone(args);
426                let lock_future = owned_args.read();
427                let locked_args = lock_future.await;
428                let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
429                print!("Contents: ");
430                for arg in locked_args.iter() {
431                    results.push(arg.clone());
432                    println!("{} ", &arg);
433                }
434                Ok(results)
435            },
436            vec![1, 2, 3]
437        )
438        .unwrap();
439        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
440    }
441
442    #[test]
443    fn test_clamp_index_positive_index() {
444        let values = vec![1, 2, 3, 4];
445        let given_index = 3isize;
446        let max_size = values.len() as isize;
447        let index = clamp_index(&given_index, &max_size).unwrap();
448        assert_eq!(
449            index, 3,
450            "Index mismatch! Requested index {} but got {}",
451            &given_index, &index
452        );
453        assert_eq!(
454            values[index], 4,
455            "Value mismatch! Expected {} but got {}",
456            &values[3], &values[index]
457        );
458    }
459
460    #[test]
461    fn test_clamp_index_reverse_index() {
462        let values = vec![1, 2, 3, 4];
463        let given_index = -1isize;
464        let max_size = values.len() as isize;
465        let index = clamp_index(&given_index, &max_size).unwrap();
466        assert_eq!(
467            index, 4,
468            "Index mismatch! Requested index {} but got {}",
469            &given_index, &index
470        );
471        assert_eq!(
472            values[index - 1],
473            4,
474            "Value mismatch! Expected {} but got {}",
475            &values[3],
476            &values[index]
477        );
478    }
479
480    #[test]
481    fn test_block_on_task() {
482        let expect = 5;
483        let value = block_on_task(async move { 5 });
484        assert_eq!(
485            value, 5,
486            "Value mismatch from async task! Expected {} but got {}",
487            &expect, &value
488        );
489    }
490
491    ///////////////////////////////////Queue Tests/////////////////////////////////////////////////
492    #[test]
493    fn test_queue_data() {
494        let expected = vec![
495            RUMString::from("Hello"),
496            RUMString::from("World!"),
497            RUMString::from("Overcast"),
498            RUMString::from("and"),
499            RUMString::from("Sad"),
500        ];
501        type TestResult = RUMResult<Vec<RUMString>>;
502        let mut queue: TaskManager<TestResult> = TaskManager::new(&5).unwrap();
503        let locked_args = RwLock::new(expected.clone());
504        let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
505        let processor = rumtk_create_task!(
506            async |args: &SafeTaskArgs<RUMString>| -> TestResult {
507                let owned_args = Arc::clone(args);
508                let lock_future = owned_args.read();
509                let locked_args = lock_future.await;
510                let mut results = TaskItems::<RUMString>::with_capacity(locked_args.len());
511                print!("Contents: ");
512                for arg in locked_args.iter() {
513                    print!("{} ", &arg);
514                    results.push(RUMString::from(arg));
515                }
516                Ok(results)
517            },
518            task_args
519        );
520
521        queue.add_task::<_>(processor);
522        let results = queue.wait();
523
524        let mut result_data = Vec::<RUMString>::with_capacity(5);
525        for r in results {
526            for v in r.unwrap().unwrap().iter() {
527                for value in v.iter() {
528                    result_data.push(value.clone());
529                }
530            }
531        }
532        assert_eq!(result_data, expected, "Results do not match expected!");
533    }
534
535    ///////////////////////////////////Net Tests/////////////////////////////////////////////////
536    #[test]
537    fn test_server_start() {
538        let server = match rumtk_create_server!("localhost", 0) {
539            Ok(server) => server,
540            Err(e) => panic!("Failed to create server because {}", e),
541        };
542    }
543
544    #[test]
545    fn test_server_send() {
546        let (t1, t2) = std::sync::mpsc::channel();
547        let (t3, t4) = std::sync::mpsc::channel();
548        let msg = RUMString::from("Hello World!");
549        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
550            Ok(server) => server,
551            Err(e) => panic!("Failed to create server because {}", e),
552        };
553        let address_info = server.get_address_info().unwrap();
554        let (ip, port) = rumtk_get_ip_port!(address_info);
555        
556        let connect_h = spawn(move || {
557            let mut client = match rumtk_connect!(port) {
558                Ok(client) => client,
559                Err(e) => panic!("Failed to create server because {}", e),
560            };
561            t1.send(client.get_address());
562
563            let mut received_message = client.receive().unwrap();
564
565            while (received_message.is_empty()) {
566                received_message = client.receive().unwrap();
567            }
568
569            t3.send(received_message);
570        });
571
572        let client_id = t2.recv().unwrap().unwrap();
573        match server.send(&client_id, &msg.to_raw()) {
574            Ok(_) => (),
575            Err(e) => panic!("Server failed to send message because {}", e),
576        };
577        let received_message = t4.recv().unwrap();
578        assert_eq!(
579            &msg.len(),
580            &received_message.len(),
581            "Received message does not match expected length!"
582        );
583        assert_eq!(
584            &msg.to_raw(),
585            &received_message,
586            "{}",
587            rumtk_format!(
588                "Received message does not match sent message by server {:?}",
589                &received_message
590            )
591        );
592    }
593
594    #[test]
595    fn test_server_receive() {
596        let (t1, t2) = std::sync::mpsc::channel();
597        let msg = RUMString::from("Hello World!");
598        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
599            Ok(server) => server,
600            Err(e) => panic!("Failed to create server because {}", e),
601        };
602        let address_info = server.get_address_info().unwrap();
603        let (ip, port) = rumtk_get_ip_port!(address_info);
604        println!("Sleeping");
605        rumtk_sleep!(1);
606        let connect_h = spawn(move || {
607            let mut client = match rumtk_connect!(port) {
608                Ok(client) => client,
609                Err(e) => panic!("Failed to create server because {}", e),
610            };
611            match client.send("Hello World!".to_raw()) {
612                Ok(_) => (),
613                Err(e) => panic!("Failed to send message because {}", e),
614            };
615            t1.send(client.get_address());
616        });
617
618        let client_id = t2.recv().unwrap().expect("Failed to get client id");
619        let incoming_message = server.receive(&client_id, true).unwrap().to_string().unwrap();
620        println!("Received message => {:?}", &incoming_message);
621        assert_eq!(incoming_message, msg, "Received message corruption!");
622    }
623
624    #[test]
625    fn test_server_get_clients() {
626        let (t1, t2) = std::sync::mpsc::channel();
627        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
628            Ok(server) => server,
629            Err(e) => panic!("Failed to create server because {}", e),
630        };
631        let address_info = server.get_address_info().unwrap();
632        let (ip, port) = rumtk_get_ip_port!(address_info);
633
634        let connect_h = spawn(move || {
635            let mut client = match rumtk_connect!(port) {
636                Ok(client) => client,
637                Err(e) => panic!("Failed to create client because {}", e),
638            };
639            t1.send(client.get_address());
640        });
641
642        let expected_client_id = t2.recv().unwrap().expect("Failed to get client id");
643        let mut clients = server.get_client_ids();
644
645        while clients.is_empty() {
646            clients = server.get_client_ids();
647            rumtk_sleep!(0.3);
648        }
649
650        let incoming_client_id = clients.get(0).expect("Expected client to have connected!");
651        println!("Connected client id => {}", &incoming_client_id);
652        assert_eq!(
653            incoming_client_id, &expected_client_id,
654            "Connected client does not match the connecting client! Client id => {}",
655            &incoming_client_id
656        );
657    }
658
659    #[test]
660    fn test_server_stop() {
661        let msg = RUMString::from("Hello World!");
662        let server = match rumtk_create_server!("localhost", 0) {
663            Ok(server) => server,
664            Err(e) => panic!("Failed to create server because {}", e),
665        };
666        println!("Sleeping");
667    }
668
669    #[test]
670    fn test_server_get_address_info() {
671        let msg = RUMString::from("Hello World!");
672        let mut server = match rumtk_create_server!("localhost", 0) {
673            Ok(server) => server,
674            Err(e) => panic!("Failed to create server because {}", e),
675        };
676        let addr = server.get_address_info().unwrap();
677        assert!(!addr.is_empty(), "No address returned....Got => {}", addr)
678    }
679
680    #[test]
681    fn test_client_send() {
682        let (t1, t2) = std::sync::mpsc::channel();
683        let msg = RUMString::from("Hello World!");
684        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
685            Ok(server) => server,
686            Err(e) => panic!("Failed to create server because {}", e),
687        };
688        let address_info = server.get_address_info().unwrap();
689        let (ip, port) = rumtk_get_ip_port!(address_info);
690
691        let connect_h = spawn(move || {
692            let mut client = match rumtk_connect!(port) {
693                Ok(client) => client,
694                Err(e) => panic!("Failed to create server because {}", e),
695            };
696            match client.send("Hello World!".to_raw()) {
697                Ok(_) => (),
698                Err(e) => panic!("Failed to send message because {}", e),
699            };
700            t1.send(()).unwrap();
701        });
702        t2.recv().unwrap();
703        let mut clients = server.get_client_ids();
704
705        while clients.is_empty() {
706            clients = server.get_client_ids();
707        }
708
709        let incoming_client_id = clients.first().expect("Expected client to have connected!");
710        let mut received_message = server.receive(incoming_client_id, true).unwrap();
711        if received_message.is_empty() {
712            received_message = server.receive(incoming_client_id, true).unwrap();
713        }
714        assert_eq!(
715            &msg.to_raw(),
716            &received_message,
717            "{}",
718            rumtk_format!(
719                "Received message does not match sent message by client {:?}",
720                &received_message
721            )
722        );
723    }
724
725    ////////////////////////////JSON Tests/////////////////////////////////
726
727    #[test]
728    fn test_serialize_json() {
729        #[derive(RUMSerJson)]
730        struct MyStruct {
731            hello: RUMString,
732        }
733
734        let hw = MyStruct {
735            hello: RUMString::from("World"),
736        };
737        let hw_str = rumtk_serialize!(&hw).unwrap();
738
739        assert!(
740            !hw_str.is_empty(),
741            "Empty JSON string generated from the test struct!"
742        );
743    }
744
745    #[test]
746    fn test_deserialize_serde_json() {
747        #[derive(RUMSerJson, RUMDeJson, PartialEq, Debug, Clone)]
748        struct MyStruct {
749            hello: RUMString,
750        }
751
752        let hw = MyStruct {
753            hello: RUMString::from("World"),
754        };
755        let hw_str = to_json(&hw).unwrap();
756        let new_hw: MyStruct = from_json(&hw_str).unwrap();
757
758        assert_eq!(
759            new_hw, hw,
760            "Deserialized JSON does not match the expected value!"
761        );
762    }
763
764    #[test]
765    fn test_deserialize_buffer_serde_json() {
766        let hw = RUMBuffer::from(b"Hello World!");
767        let hw_str = to_json(&hw).unwrap();
768        let new_hw: RUMBuffer = from_json(&hw_str).unwrap();
769
770        assert_eq!(
771            new_hw, hw,
772            "Deserialized Buffer from JSON does not match the expected value!"
773        );
774    }
775
776    #[test]
777    fn test_deserialize_json() {
778        #[derive(RUMSerJson, RUMDeJson, PartialEq)]
779        struct MyStruct {
780            hello: RUMString,
781        }
782
783        let hw = MyStruct {
784            hello: RUMString::from("World"),
785        };
786        let hw_str = rumtk_serialize!(&hw).unwrap();
787        let new_hw: MyStruct = rumtk_deserialize!(&hw_str).unwrap();
788
789        assert!(
790            new_hw == hw,
791            "Deserialized JSON does not match the expected value!"
792        );
793    }
794
795
796    #[test]
797    fn test_escape_unescape_json() {
798        #[derive(RUMSerJson, RUMDeJson, PartialEq)]
799        struct MyStruct {
800            hello: RUMString,
801        }
802
803        let hw = MyStruct {
804            hello: RUMString::from("World"),
805        };
806
807        let hw_str = rumtk_serialize!(&hw).unwrap();
808        let hw_escaped_str = strings::string_escape(&hw_str, ASCII_ESCAPE_PREFIX_DEFAULT);
809        println!("Escaped => {}", hw_escaped_str);
810
811        let hw_unescaped_str = strings::unescape_string(&hw_escaped_str).unwrap();
812        println!("Unescaped => {}", hw_unescaped_str);
813        assert_eq!(
814            hw_str.to_string(),
815            hw_unescaped_str.to_string(),
816            "Unescaped serialized JSON mismatch!"
817        );
818
819        let new_hw: MyStruct = rumtk_deserialize!(&hw_unescaped_str).unwrap();
820
821        assert!(
822            new_hw == hw,
823            "Deserialized JSON does not match the expected value!"
824        );
825    }
826
827    ////////////////////////////CLI Tests/////////////////////////////////
828
829    #[test]
830    fn test_print_license_notice() {
831        print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
832    }
833
834    //////////////////////////////////////////////////////////////////////////////////////////////
835
836    ////////////////////////////Pipeline Tests/////////////////////////////////
837
838    #[test]
839    fn test_pipe_processes() {
840        let ls_name = "ls";
841        let mut ls_command = RUMCommand::default();
842        ls_command.path = RUMString::from(ls_name);
843        let mut sys_ls_command = pipeline_create_command(&ls_command);
844        sys_ls_command.stdin(Stdio::piped());
845        sys_ls_command.stdout(Stdio::piped());
846
847        let wc_name = "wc";
848        let mut wc_command = RUMCommand::default();
849        wc_command.path = RUMString::from(wc_name);
850        let mut sys_wc_command = pipeline_create_command(&wc_command);
851
852        let mut sys_ls_process = pipeline_spawn_process(&mut sys_ls_command).unwrap();
853        pipeline_pipe_processes(&mut sys_ls_process, &mut sys_wc_command).unwrap();
854        let mut sys_wc_process = pipeline_spawn_process(&mut sys_wc_command).unwrap();
855
856        sys_ls_process.wait();
857        sys_wc_process.wait();
858    }
859
860    #[test]
861    fn test_quick_pipe() {let data = RUMBuffer::from(b"Hello World");
862        let wc_name = "wc";
863        let mut wc_command = RUMCommand::default();
864        wc_command.path = RUMString::from(wc_name);
865        let mut pipeline = vec![
866            wc_command
867        ];
868
869        let processor = || -> RUMResult<RUMBuffer> {rumtk_pipeline_run!(&pipeline, &data)};
870        let result_string = buffer_to_string(&processor().unwrap()).unwrap();
871        let binding = result_string.as_str().replace('\n', "");
872        let result_items: Vec<&str> = binding.split("      ").collect();
873        let result = result_items.get(2).unwrap().trim().parse::<i32>().unwrap();
874
875        assert_eq!(result, 2, "Data was not piped properly!");
876    }
877
878    #[test]
879    fn test_patch_pipeline_arguments() {let data = RUMBuffer::from(b"Hello World");
880        let ls_name = "ls";
881        let mut ls_command = RUMCommand::default();
882        ls_command.path = RUMString::from(ls_name);
883        ls_command.args.push(RUMString::from("{options}"));
884        let mut pipeline = vec![
885            ls_command
886        ];
887        pipeline_patch_args(&mut pipeline, &[("{options}", "-la")]);
888
889        let processor = || -> RUMResult<RUMBuffer> {rumtk_pipeline_run!(&pipeline)};
890        let result_string = buffer_to_string(&processor().unwrap()).unwrap();
891        let results: Vec<&str> = result_string.as_str().split("\n").collect();
892        let dot_dir = results.get(1).unwrap().chars().last().unwrap();
893
894        assert_eq!(dot_dir, '.', "Incorrect options passed!");
895    }
896
897    //////////////////////////////////////////////////////////////////////////////////////////////
898
899    ////////////////////////////Buffer Tests/////////////////////////////////
900    #[test]
901    fn test_buffer_split() {
902        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
903        let mut splits = vec![];
904
905        let mut splitter = data.split_fast('|' as u8);
906        for split in &mut splitter {
907            splits.push(split);
908        }
909        splits.push(splitter.remainder);
910
911        assert_eq!(splits.len(), 22, "Bad buffer split! Got {:?}", splits);
912    }
913
914    #[test]
915    fn test_buffer_find() {
916        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
917        let indx = buffer_find(data.as_slice(), &['|' as u8]);
918
919        assert_eq!(indx, 5, "Bad buffer find! Got {:?}", indx);
920    }
921
922    #[test]
923    fn test_buffer_find_long() {
924        let pattern = "|Test";
925        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
926        let indx = buffer_find(data.as_slice(), pattern.as_bytes());
927
928        assert_eq!(indx, 11, "Bad buffer find! Got {:?}", indx);
929    }
930
931    #[test]
932    fn test_buffer_replace() {
933        let pattern = "|Test";
934        let replacement = "|Test123";
935        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
936        let expected = RUMBuffer::from(b"Hello|World|Test123|||||||||||||||||||");
937        let new = buffer_replace(data.as_slice(), pattern.as_bytes(), replacement.as_bytes());
938
939        assert_eq!(new, expected, "Bad buffer replace! Got {:?}", new);
940    }
941
942    #[test]
943    fn test_buffer_replace_in_place() {
944        let pattern = "|Test";
945        let replacement = "|Tes1";
946        let mut data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
947        let expected = RUMBuffer::from(b"Hello|World|Tes1|||||||||||||||||||");
948
949        buffer_replace_in_place(&mut data, pattern.as_bytes(), replacement.as_bytes());
950
951        assert_eq!(data, expected, "Bad buffer replace! Got {:?}", data);
952    }
953
954    #[test]
955    fn test_buffer_trim() {
956        let data = RUMBuffer::from(b"\n Hello|World \n");
957        let expected = RUMBuffer::from(b"Hello|World");
958        let new = buffer_trim(&data);
959
960        assert_eq!(new, expected.as_slice(), "Bad buffer trim! Got {:?}", new);
961    }
962
963    #[test]
964    fn test_buffer_slice_trim() {
965        let data = b"\n Hello|World \n";
966        let expected = b"Hello|World";
967        let new = buffer_slice_trim(data);
968
969        assert_eq!(new, expected, "Bad buffer slice trim! Got {:?}", new);
970    }
971
972    #[test]
973    fn test_buffer_count() {
974        let data = b"\n Hello|World \n";
975        let expected = 2;
976        let found = buffer_count(data, b'\n');
977
978        assert_eq!(found, expected, "Incorrect number of occurrences of newline found! Got {:?}", found);
979    }
980
981    #[test]
982    fn test_buffer_count_2mb() {
983        let data = new_random_buffer::<2048>();
984        let expected = 1000;
985        let (found, time) = rumtk_benchmark_snippet!(||{
986            buffer_count(&data, b'\n')
987        });
988
989        assert!(time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", time);
990    }
991
992    #[test]
993    fn test_buffer_split_simple() {
994        let mut data = RUMBuffer::from(b"Hello|World");
995        let split = data.split_to(5);
996        let expected = RUMBuffer::from(b"Hello");
997
998        assert_eq!(split, Some(expected), "Bad buffer trim! Got {:?}", split);
999    }
1000
1001    #[test]
1002    fn test_buffer_struct_size() {
1003        let data = RUMBuffer::new();
1004        let struct_size = size_of::<RUMBuffer>();
1005
1006        assert!(struct_size <= 16, "Empty RUMBuffer structure size is too large! Length is {} bytes.", struct_size);
1007    }
1008
1009    //////////////////////////////////////////////////////////////////////////////////////////////
1010
1011    ////////////////////////////CPU Tests/////////////////////////////////
1012
1013    #[test]
1014    fn test_cpu_find_needle() {
1015        let data = b"                                                         n                    ";
1016        let expected = Some(57);
1017        let indx = cpu_find(data, b'n');
1018
1019        assert_eq!(indx, expected, "Could not find the needle in the haystack");
1020    }
1021
1022    #[test]
1023    fn test_cpu_find_needle_2mb() {
1024        let data = new_random_buffer::<2048>();
1025        let expected = 1000;
1026        let (found, time) = rumtk_benchmark_snippet!(||{
1027            cpu_find(&data, b'\n')
1028        });
1029
1030        assert!(time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", time);
1031    }
1032
1033    #[test]
1034    fn test_cpu_find_needle_2mb_4096() {
1035        let mut all_time = 0;
1036        let expected = 1000;
1037        for i in 0..4096 {
1038            let data = new_random_buffer::<2048>();
1039            let (found, time) = rumtk_benchmark_snippet!(||{
1040                    cpu_find(&data, b'\n')
1041            });
1042            all_time += time;
1043        }
1044
1045        assert!(all_time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", all_time);
1046    }
1047
1048    #[test]
1049    fn test_cpu_collect_needle() {
1050        let data = b"                                                         n                    ";
1051        let expected = vec![57];
1052        let indices = cpu_collect(data, b'n', 0);
1053
1054        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1055    }
1056
1057    #[test]
1058    fn test_cpu_collect_needle_3() {
1059        let data = b"                                                         nnn                    ";
1060        let expected = vec![57, 58, 59];
1061        let indices = cpu_collect(data, b'n', 0);
1062
1063        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1064    }
1065
1066    #[test]
1067    fn test_cpu_collect_needle_6() {
1068        let data = b"                 nnn                                        nnn                    ";
1069        let expected = vec![17, 18, 19, 60, 61, 62];
1070        let indices = cpu_collect(data, b'n', 0);
1071
1072        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1073    }
1074
1075    #[test]
1076    fn test_cpu_tokenize_needle_6() {
1077        let data = b"                 nnn                                        nnn                    ";
1078        let expected = vec![(110, 17), (110, 18), (110, 19), (110, 60), (110, 61), (110, 62)];
1079        let indices = cpu_tokenize::<CPU_SEARCH_WINDOW_16_SIZE>(data, b"n");
1080
1081        assert_eq!(indices, expected, "Could not find the needle in the haystack");
1082    }
1083
1084    #[test]
1085    fn test_cpu_tokenize_needle_6_benchmark() {
1086        let data = b"                 nnn                                        nnn                    ";
1087        let (indices, time) = rumtk_benchmark_snippet!(||{
1088            cpu_tokenize::<CPU_SEARCH_WINDOW_16_SIZE>(data, b"n")
1089        });
1090
1091        println!("Tokenized message in {} us", &time);
1092
1093        assert!(time <= 10000, "Buffer tokenization took {} microseconds [> 10000 us]!", time);
1094    }
1095
1096    #[test]
1097    fn test_cpu_replace_simd() {
1098        let mut data = b"                                                         n                    ".to_vec();
1099        let expected = b"                                                                              ".to_vec();
1100
1101        cpu_replace_byte(data.as_mut_slice(), b'n', b' ');
1102
1103        assert_eq!(data, expected, "Failed to replace in SIMD!");
1104    }
1105
1106    #[test]
1107    fn test_cpu_replace_simd_multi() {
1108        let mut data = b"              nnnnnnnn                  nnnn                         n    nn                ".to_vec();
1109        let expected = b"                                                                                            ".to_vec();
1110
1111        cpu_replace_byte(data.as_mut_slice(), b'n', b' ');
1112
1113        assert_eq!(data, expected, "Failed to replace in SIMD!");
1114    }
1115
1116    //////////////////////////////////////////////////////////////////////////////////////////////
1117
1118    ////////////////////////////Regex Tests/////////////////////////////////
1119    #[test]
1120    fn test_regex_expression_hash() {
1121        let expr = REGEX_ANSI_ESCAPE_SEQUENCES;
1122        let hash = hash_regex_expression(expr);
1123        let hash2 = hash_regex_expression(expr);
1124        let empty_hash = hash_data("") as usize;
1125        assert!(
1126            hash > 0 && hash != empty_hash && hash == hash2,
1127            "{}",
1128            rumtk_format!("Regex expression hash failed: expr={}, hash={}, hash2={}", expr, hash, hash2)
1129        );
1130    }
1131
1132    #[test]
1133    fn test_filter_ansi_sequence() {
1134        let data = "\x1b[31mHello, World!\x1b[0m";
1135        let expected = "Hello, World!";
1136        let filtered_data = filter_ansi_escape_sequences(data).unwrap();
1137        assert_eq!(filtered_data, expected);
1138    }
1139
1140    #[test]
1141    fn test_filter_ansi_sequence_mouse_tracking() {
1142        let data = "printf `\x1b[?1001h\x1b[?1002h\x1b[?1003h\x1b[?1004h\x1b[?1005hopen -a calculator;notify-send Hello World\x1b[?1006h\x1b[?1015h\x1b[?10016h`";
1143        let expected = "printf `open -a calculator;notify-send Hello World`";
1144        let filtered_data = filter_ansi_escape_sequences(data).unwrap();
1145        assert_eq!(filtered_data, expected);
1146    }
1147
1148    #[test]
1149    fn test_search_number() {
1150        let data = "2007";
1151        let regex = r"\d{4}";
1152        let expected = "2007";
1153        let filtered_data = string_search(data, regex).unwrap();
1154        assert_eq!(filtered_data, expected);
1155    }
1156
1157    #[test]
1158    fn test_search_float() {
1159        let data = "-5f";
1160        let regex = r"\+|\-|\d+\.\d+e\d+|\d+e\d+|\d+\.\d+|\d+";
1161        let expected = "-5";
1162        let filtered_data = string_search(data, regex).unwrap();
1163        assert_eq!(filtered_data, expected);
1164    }
1165
1166}