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};
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\'\"\\";
103        let expected = "\\r\\n\\'\\\"\\\\";
104        let result = strings::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 = "\\u2764";
119        let result = strings::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 = strings::escape(input);
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 \\u2764 my wife!";
209        let result = strings::escape(input);
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_autodecode_utf8() {
222        let input = "I ❤ my wife!";
223        let result = strings::try_decode(input.as_bytes()).unwrap();
224        println!(
225            "Input: {} Expected: {} Got: {}",
226            input,
227            input,
228            result.as_str()
229        );
230        assert_eq!(input, result, "Incorrect string decoding!");
231        println!("Passed!")
232    }
233
234    #[test]
235    fn test_autodecode_other() {
236        //TODO: Need an example of other encoding texts.
237        let input = "I ❤ my wife!";
238        let result = input;
239        println!("Input: {} Expected: {} Got: {}", input, input, result);
240        assert_eq!(input, result, "Incorrect string decoding!");
241        println!("Passed!")
242    }
243
244    #[test]
245    fn test_decode() {
246        let input = "I ❤ my wife!";
247        let result = strings::try_decode_with(input.as_bytes(), "utf-8").unwrap();
248        println!(
249            "Input: {} Expected: {} Got: {}",
250            input,
251            input,
252            result.as_str()
253        );
254        assert_eq!(input, result, "Incorrect string decoding!");
255        println!("Passed!")
256    }
257
258    #[test]
259    fn test_rumcache_insertion() {
260        let mut cache: RUMCache<&str, RUMString> = RUMCache::with_capacity(5);
261        cache.insert("❤", RUMString::from("I ❤ my wife!"));
262        println!("Contents: {:#?}", &cache);
263        assert_eq!(cache.len(), 1, "Incorrect number of items in cache!");
264        println!("Passed!")
265    }
266
267    #[test]
268    fn test_search_string_letters() {
269        let input = "Hello World!";
270        let expr = r"\w";
271        let result = string_search(input, expr).unwrap();
272        let expected: RUMString = RUMString::from("HelloWorld");
273        println!(
274            "Input: {:?} Expected: {:?} Got: {:?}",
275            input, expected, result
276        );
277        assert_eq!(expected, result, "String search results mismatch");
278        println!("Passed!")
279    }
280
281    #[test]
282    fn test_search_string_words() {
283        let input = "Hello World!";
284        let expr = r"\w+|\s+";
285        let result = string_search(input, expr).unwrap();
286        let expected: RUMString = RUMString::from("Hello World");
287        println!(
288            "Input: {:?} Expected: {:?} Got: {:?}",
289            input, expected, result
290        );
291        assert_eq!(expected, result, "String search results mismatch");
292        println!("Passed!")
293    }
294
295    #[test]
296    fn test_search_string_named_groups() {
297        let input = "Hello World!";
298        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
299        let result = string_search_named_captures(input, expr, "").unwrap();
300        let expected: RUMString = RUMString::from("World");
301        println!(
302            "Input: {:?} Expected: {:?} Got: {:?}",
303            input, expected, result
304        );
305        assert_eq!(expected, result["world"], "String search results mismatch");
306        println!("Passed!")
307    }
308
309    #[test]
310    fn test_search_string_all_groups() {
311        let input = "Hello World!";
312        let expr = r"(?<hello>\w{5}) (?<world>\w{5})";
313        let result = string_search_all_captures(input, expr).unwrap();
314        let expected: Vec<&str> = vec!["Hello", "World"];
315        println!(
316            "Input: {:?} Expected: {:?} Got: {:?}",
317            input, expected, result
318        );
319        assert_eq!(expected, result, "String search results mismatch");
320        println!("Passed!")
321    }
322
323    #[test]
324    fn test_find_value_in_string() {
325        let haystack = "Range (min \\xe2\\x80\\xa6 max):     0.6 ms \\xe2\\x80\\xa6   2.9 ms    1273 runs";
326        let patterns = ["\\d+ runs", "\\d+"];
327        let expected = 1273;
328        let result = string_find_value::<usize>(haystack, &patterns);
329
330        assert_eq!(result, Ok(expected), "Did not find the needle in the haystack or returned the wrong type!");
331    }
332
333    ///////////////////////////////////Threading Tests/////////////////////////////////////////////////
334    #[test]
335    fn test_default_num_threads() {
336        use num_cpus;
337        let threads = threading::threading_functions::get_default_system_thread_count();
338        assert_eq!(
339            threads >= num_cpus::get(),
340            true,
341            "Default thread count is incorrect! We got {}, but expected {}!",
342            threads,
343            num_cpus::get()
344        );
345    }
346
347    #[test]
348    fn test_execute_job() {
349        let expected = vec![1, 2, 3];
350        let task_processor = async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
351            let owned_args = Arc::clone(args);
352            let lock_future = owned_args.read();
353            let locked_args = lock_future.await;
354            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
355            print!("Contents: ");
356            for arg in locked_args.iter() {
357                results.push(arg.clone());
358                println!("{} ", &arg);
359            }
360            Ok(results)
361        };
362        let locked_args = RwLock::new(expected.clone());
363        let task_args = SafeTaskArgs::<i32>::new(locked_args);
364        let task_result = rumtk_wait_on_task!(task_processor, &task_args);
365        let result = task_result.unwrap();
366        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
367    }
368
369    #[test]
370    fn test_execute_job_macros() {
371        let expected = vec![1, 2, 3];
372        let task_processor = async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
373            let owned_args = Arc::clone(args);
374            let lock_future = owned_args.read();
375            let locked_args = lock_future.await;
376            let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
377            print!("Contents: ");
378            for arg in locked_args.iter() {
379                results.push(arg.clone());
380                println!("{} ", &arg);
381            }
382            Ok(results)
383        };
384        let task_args = rumtk_create_task_args!(1, 2, 3);
385        let task_result = rumtk_wait_on_task!(task_processor, &task_args);
386        let result = task_result.unwrap();
387        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
388    }
389
390    #[test]
391    fn test_execute_job_macros_one_line() {
392        let expected = vec![1, 2, 3];
393        let result = rumtk_exec_task!(
394            async |args: &SafeTaskArgs<i32>| -> RUMResult<Vec<i32>> {
395                let owned_args = Arc::clone(args);
396                let lock_future = owned_args.read();
397                let locked_args = lock_future.await;
398                let mut results = TaskItems::<i32>::with_capacity(locked_args.len());
399                print!("Contents: ");
400                for arg in locked_args.iter() {
401                    results.push(arg.clone());
402                    println!("{} ", &arg);
403                }
404                Ok(results)
405            },
406            vec![1, 2, 3]
407        )
408        .unwrap();
409        assert_eq!(&result, &expected, "{}", rumtk_format!("Task processing returned a different result than expected! Expected {:?} \nResults {:?}", &expected, &result));
410    }
411
412    #[test]
413    fn test_clamp_index_positive_index() {
414        let values = vec![1, 2, 3, 4];
415        let given_index = 3isize;
416        let max_size = values.len() as isize;
417        let index = clamp_index(&given_index, &max_size).unwrap();
418        assert_eq!(
419            index, 3,
420            "Index mismatch! Requested index {} but got {}",
421            &given_index, &index
422        );
423        assert_eq!(
424            values[index], 4,
425            "Value mismatch! Expected {} but got {}",
426            &values[3], &values[index]
427        );
428    }
429
430    #[test]
431    fn test_clamp_index_reverse_index() {
432        let values = vec![1, 2, 3, 4];
433        let given_index = -1isize;
434        let max_size = values.len() as isize;
435        let index = clamp_index(&given_index, &max_size).unwrap();
436        assert_eq!(
437            index, 4,
438            "Index mismatch! Requested index {} but got {}",
439            &given_index, &index
440        );
441        assert_eq!(
442            values[index - 1],
443            4,
444            "Value mismatch! Expected {} but got {}",
445            &values[3],
446            &values[index]
447        );
448    }
449
450    #[test]
451    fn test_block_on_task() {
452        let expect = 5;
453        let value = block_on_task(async move { 5 });
454        assert_eq!(
455            value, 5,
456            "Value mismatch from async task! Expected {} but got {}",
457            &expect, &value
458        );
459    }
460
461    ///////////////////////////////////Queue Tests/////////////////////////////////////////////////
462    #[test]
463    fn test_queue_data() {
464        let expected = vec![
465            RUMString::from("Hello"),
466            RUMString::from("World!"),
467            RUMString::from("Overcast"),
468            RUMString::from("and"),
469            RUMString::from("Sad"),
470        ];
471        type TestResult = RUMResult<Vec<RUMString>>;
472        let mut queue: TaskManager<TestResult> = TaskManager::new(&5).unwrap();
473        let locked_args = RwLock::new(expected.clone());
474        let task_args = SafeTaskArgs::<RUMString>::new(locked_args);
475        let processor = rumtk_create_task!(
476            async |args: &SafeTaskArgs<RUMString>| -> TestResult {
477                let owned_args = Arc::clone(args);
478                let lock_future = owned_args.read();
479                let locked_args = lock_future.await;
480                let mut results = TaskItems::<RUMString>::with_capacity(locked_args.len());
481                print!("Contents: ");
482                for arg in locked_args.iter() {
483                    print!("{} ", &arg);
484                    results.push(RUMString::from(arg));
485                }
486                Ok(results)
487            },
488            task_args
489        );
490
491        queue.add_task::<_>(processor);
492        let results = queue.wait();
493
494        let mut result_data = Vec::<RUMString>::with_capacity(5);
495        for r in results {
496            for v in r.unwrap().unwrap().iter() {
497                for value in v.iter() {
498                    result_data.push(value.clone());
499                }
500            }
501        }
502        assert_eq!(result_data, expected, "Results do not match expected!");
503    }
504
505    ///////////////////////////////////Net Tests/////////////////////////////////////////////////
506    #[test]
507    fn test_server_start() {
508        let server = match rumtk_create_server!("localhost", 0) {
509            Ok(server) => server,
510            Err(e) => panic!("Failed to create server because {}", e),
511        };
512    }
513
514    #[test]
515    fn test_server_send() {
516        let (t1, t2) = std::sync::mpsc::channel();
517        let (t3, t4) = std::sync::mpsc::channel();
518        let msg = RUMString::from("Hello World!");
519        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
520            Ok(server) => server,
521            Err(e) => panic!("Failed to create server because {}", e),
522        };
523        let address_info = server.get_address_info().unwrap();
524        let (ip, port) = rumtk_get_ip_port!(address_info);
525        
526        let connect_h = spawn(move || {
527            let mut client = match rumtk_connect!(port) {
528                Ok(client) => client,
529                Err(e) => panic!("Failed to create server because {}", e),
530            };
531            t1.send(client.get_address());
532
533            let mut received_message = client.receive().unwrap();
534
535            while (received_message.is_empty()) {
536                received_message = client.receive().unwrap();
537            }
538
539            t3.send(received_message);
540        });
541
542        let client_id = t2.recv().unwrap().unwrap();
543        match server.send(&client_id, &msg.to_raw()) {
544            Ok(_) => (),
545            Err(e) => panic!("Server failed to send message because {}", e),
546        };
547        let received_message = t4.recv().unwrap();
548        assert_eq!(
549            &msg.len(),
550            &received_message.len(),
551            "Received message does not match expected length!"
552        );
553        assert_eq!(
554            &msg.to_raw(),
555            &received_message,
556            "{}",
557            rumtk_format!(
558                "Received message does not match sent message by server {:?}",
559                &received_message
560            )
561        );
562    }
563
564    #[test]
565    fn test_server_receive() {
566        let (t1, t2) = std::sync::mpsc::channel();
567        let msg = RUMString::from("Hello World!");
568        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
569            Ok(server) => server,
570            Err(e) => panic!("Failed to create server because {}", e),
571        };
572        let address_info = server.get_address_info().unwrap();
573        let (ip, port) = rumtk_get_ip_port!(address_info);
574        println!("Sleeping");
575        rumtk_sleep!(1);
576        let connect_h = spawn(move || {
577            let mut client = match rumtk_connect!(port) {
578                Ok(client) => client,
579                Err(e) => panic!("Failed to create server because {}", e),
580            };
581            match client.send("Hello World!".to_raw()) {
582                Ok(_) => (),
583                Err(e) => panic!("Failed to send message because {}", e),
584            };
585            t1.send(client.get_address());
586        });
587
588        let client_id = t2.recv().unwrap().expect("Failed to get client id");
589        let incoming_message = server.receive(&client_id, true).unwrap().to_string().unwrap();
590        println!("Received message => {:?}", &incoming_message);
591        assert_eq!(incoming_message, msg, "Received message corruption!");
592    }
593
594    #[test]
595    fn test_server_get_clients() {
596        let (t1, t2) = std::sync::mpsc::channel();
597        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
598            Ok(server) => server,
599            Err(e) => panic!("Failed to create server because {}", e),
600        };
601        let address_info = server.get_address_info().unwrap();
602        let (ip, port) = rumtk_get_ip_port!(address_info);
603
604        let connect_h = spawn(move || {
605            let mut client = match rumtk_connect!(port) {
606                Ok(client) => client,
607                Err(e) => panic!("Failed to create client because {}", e),
608            };
609            t1.send(client.get_address());
610        });
611
612        let expected_client_id = t2.recv().unwrap().expect("Failed to get client id");
613        let mut clients = server.get_client_ids();
614
615        while clients.is_empty() {
616            clients = server.get_client_ids();
617            rumtk_sleep!(0.3);
618        }
619
620        let incoming_client_id = clients.get(0).expect("Expected client to have connected!");
621        println!("Connected client id => {}", &incoming_client_id);
622        assert_eq!(
623            incoming_client_id, &expected_client_id,
624            "Connected client does not match the connecting client! Client id => {}",
625            &incoming_client_id
626        );
627    }
628
629    #[test]
630    fn test_server_stop() {
631        let msg = RUMString::from("Hello World!");
632        let server = match rumtk_create_server!("localhost", 0) {
633            Ok(server) => server,
634            Err(e) => panic!("Failed to create server because {}", e),
635        };
636        println!("Sleeping");
637    }
638
639    #[test]
640    fn test_server_get_address_info() {
641        let msg = RUMString::from("Hello World!");
642        let mut server = match rumtk_create_server!("localhost", 0) {
643            Ok(server) => server,
644            Err(e) => panic!("Failed to create server because {}", e),
645        };
646        let addr = server.get_address_info().unwrap();
647        assert!(!addr.is_empty(), "No address returned....Got => {}", addr)
648    }
649
650    #[test]
651    fn test_client_send() {
652        let (t1, t2) = std::sync::mpsc::channel();
653        let msg = RUMString::from("Hello World!");
654        let mut server = match rumtk_create_server!(LOCALHOST, 0) {
655            Ok(server) => server,
656            Err(e) => panic!("Failed to create server because {}", e),
657        };
658        let address_info = server.get_address_info().unwrap();
659        let (ip, port) = rumtk_get_ip_port!(address_info);
660
661        let connect_h = spawn(move || {
662            let mut client = match rumtk_connect!(port) {
663                Ok(client) => client,
664                Err(e) => panic!("Failed to create server because {}", e),
665            };
666            match client.send("Hello World!".to_raw()) {
667                Ok(_) => (),
668                Err(e) => panic!("Failed to send message because {}", e),
669            };
670            t1.send(()).unwrap();
671        });
672        t2.recv().unwrap();
673        let mut clients = server.get_client_ids();
674
675        while clients.is_empty() {
676            clients = server.get_client_ids();
677        }
678
679        let incoming_client_id = clients.first().expect("Expected client to have connected!");
680        let mut received_message = server.receive(incoming_client_id, true).unwrap();
681        if received_message.is_empty() {
682            received_message = server.receive(incoming_client_id, true).unwrap();
683        }
684        assert_eq!(
685            &msg.to_raw(),
686            &received_message,
687            "{}",
688            rumtk_format!(
689                "Received message does not match sent message by client {:?}",
690                &received_message
691            )
692        );
693    }
694
695    ////////////////////////////JSON Tests/////////////////////////////////
696
697    #[test]
698    fn test_serialize_json() {
699        #[derive(RUMSerJson)]
700        struct MyStruct {
701            hello: RUMString,
702        }
703
704        let hw = MyStruct {
705            hello: RUMString::from("World"),
706        };
707        let hw_str = rumtk_serialize!(&hw).unwrap();
708
709        assert!(
710            !hw_str.is_empty(),
711            "Empty JSON string generated from the test struct!"
712        );
713    }
714
715    #[test]
716    fn test_deserialize_serde_json() {
717        #[derive(RUMSerJson, RUMDeJson, PartialEq, Debug, Clone)]
718        struct MyStruct {
719            hello: RUMString,
720        }
721
722        let hw = MyStruct {
723            hello: RUMString::from("World"),
724        };
725        let hw_str = to_json(&hw).unwrap();
726        let new_hw: MyStruct = from_json(&hw_str).unwrap();
727
728        assert_eq!(
729            new_hw, hw,
730            "Deserialized JSON does not match the expected value!"
731        );
732    }
733
734    #[test]
735    fn test_deserialize_buffer_serde_json() {
736        let hw = RUMBuffer::from(b"Hello World!");
737        let hw_str = to_json(&hw).unwrap();
738        let new_hw: RUMBuffer = from_json(&hw_str).unwrap();
739
740        assert_eq!(
741            new_hw, hw,
742            "Deserialized Buffer from JSON does not match the expected value!"
743        );
744    }
745
746    #[test]
747    fn test_deserialize_json() {
748        #[derive(RUMSerJson, RUMDeJson, PartialEq)]
749        struct MyStruct {
750            hello: RUMString,
751        }
752
753        let hw = MyStruct {
754            hello: RUMString::from("World"),
755        };
756        let hw_str = rumtk_serialize!(&hw).unwrap();
757        let new_hw: MyStruct = rumtk_deserialize!(&hw_str).unwrap();
758
759        assert!(
760            new_hw == hw,
761            "Deserialized JSON does not match the expected value!"
762        );
763    }
764
765
766    #[test]
767    fn test_escape_unescape_json() {
768        #[derive(RUMSerJson, RUMDeJson, PartialEq)]
769        struct MyStruct {
770            hello: RUMString,
771        }
772
773        let hw = MyStruct {
774            hello: RUMString::from("World"),
775        };
776
777        let hw_str = rumtk_serialize!(&hw).unwrap();
778        let hw_escaped_str = strings::basic_escape(&hw_str, None);
779        println!("Escaped => {}", hw_escaped_str);
780
781        let hw_unescaped_str = strings::unescape_string(&hw_escaped_str).unwrap();
782        println!("Unescaped => {}", hw_unescaped_str);
783        assert_eq!(
784            hw_str.to_string(),
785            hw_unescaped_str.to_string(),
786            "Unescaped serialized JSON mismatch!"
787        );
788
789        let new_hw: MyStruct = rumtk_deserialize!(&hw_unescaped_str).unwrap();
790
791        assert!(
792            new_hw == hw,
793            "Deserialized JSON does not match the expected value!"
794        );
795    }
796
797    ////////////////////////////CLI Tests/////////////////////////////////
798
799    #[test]
800    fn test_print_license_notice() {
801        print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
802    }
803
804    //////////////////////////////////////////////////////////////////////////////////////////////
805
806    ////////////////////////////Pipeline Tests/////////////////////////////////
807
808    #[test]
809    fn test_pipe_processes() {
810        let ls_name = "ls";
811        let mut ls_command = RUMCommand::default();
812        ls_command.path = RUMString::from(ls_name);
813        let mut sys_ls_command = pipeline_create_command(&ls_command);
814        sys_ls_command.stdin(Stdio::piped());
815        sys_ls_command.stdout(Stdio::piped());
816
817        let wc_name = "wc";
818        let mut wc_command = RUMCommand::default();
819        wc_command.path = RUMString::from(wc_name);
820        let mut sys_wc_command = pipeline_create_command(&wc_command);
821
822        let mut sys_ls_process = pipeline_spawn_process(&mut sys_ls_command).unwrap();
823        pipeline_pipe_processes(&mut sys_ls_process, &mut sys_wc_command).unwrap();
824        let mut sys_wc_process = pipeline_spawn_process(&mut sys_wc_command).unwrap();
825
826        sys_ls_process.wait();
827        sys_wc_process.wait();
828    }
829
830    #[test]
831    fn test_quick_pipe() {let data = RUMBuffer::from(b"Hello World");
832        let wc_name = "wc";
833        let mut wc_command = RUMCommand::default();
834        wc_command.path = RUMString::from(wc_name);
835        let mut pipeline = vec![
836            wc_command
837        ];
838
839        let processor = || -> RUMResult<RUMBuffer> {rumtk_pipeline_run!(&pipeline, &data)};
840        let result_string = buffer_to_string(&processor().unwrap()).unwrap();
841        let binding = result_string.as_str().replace('\n', "");
842        let result_items: Vec<&str> = binding.split("      ").collect();
843        let result = result_items.get(2).unwrap().trim().parse::<i32>().unwrap();
844
845        assert_eq!(result, 2, "Data was not piped properly!");
846    }
847
848    #[test]
849    fn test_patch_pipeline_arguments() {let data = RUMBuffer::from(b"Hello World");
850        let ls_name = "ls";
851        let mut ls_command = RUMCommand::default();
852        ls_command.path = RUMString::from(ls_name);
853        ls_command.args.push(RUMString::from("{options}"));
854        let mut pipeline = vec![
855            ls_command
856        ];
857        pipeline_patch_args(&mut pipeline, &[("{options}", "-la")]);
858
859        let processor = || -> RUMResult<RUMBuffer> {rumtk_pipeline_run!(&pipeline)};
860        let result_string = buffer_to_string(&processor().unwrap()).unwrap();
861        let results: Vec<&str> = result_string.as_str().split("\n").collect();
862        let dot_dir = results.get(1).unwrap().chars().last().unwrap();
863
864        assert_eq!(dot_dir, '.', "Incorrect options passed!");
865    }
866
867    //////////////////////////////////////////////////////////////////////////////////////////////
868
869    ////////////////////////////Buffer Tests/////////////////////////////////
870    #[test]
871    fn test_buffer_split() {
872        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
873        let mut splits = vec![];
874
875        let mut splitter = data.split_fast('|' as u8);
876        for split in &mut splitter {
877            splits.push(split);
878        }
879        splits.push(splitter.remainder);
880
881        assert_eq!(splits.len(), 22, "Bad buffer split! Got {:?}", splits);
882    }
883
884    #[test]
885    fn test_buffer_find() {
886        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
887        let indx = buffer_find(data.as_slice(), &['|' as u8]);
888
889        assert_eq!(indx, 5, "Bad buffer find! Got {:?}", indx);
890    }
891
892    #[test]
893    fn test_buffer_find_long() {
894        let pattern = "|Test";
895        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
896        let indx = buffer_find(data.as_slice(), pattern.as_bytes());
897
898        assert_eq!(indx, 11, "Bad buffer find! Got {:?}", indx);
899    }
900
901    #[test]
902    fn test_buffer_replace() {
903        let pattern = "|Test";
904        let replacement = "|Test123";
905        let data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
906        let expected = RUMBuffer::from(b"Hello|World|Test123|||||||||||||||||||");
907        let new = buffer_replace(data.as_slice(), pattern.as_bytes(), replacement.as_bytes());
908
909        assert_eq!(new, expected, "Bad buffer replace! Got {:?}", new);
910    }
911
912    #[test]
913    fn test_buffer_replace_in_place() {
914        let pattern = "|Test";
915        let replacement = "|Tes1";
916        let mut data = RUMBuffer::from(b"Hello|World|Test|||||||||||||||||||");
917        let expected = RUMBuffer::from(b"Hello|World|Tes1|||||||||||||||||||");
918
919        buffer_replace_in_place(&mut data, pattern.as_bytes(), replacement.as_bytes());
920
921        assert_eq!(data, expected, "Bad buffer replace! Got {:?}", data);
922    }
923
924    #[test]
925    fn test_buffer_trim() {
926        let data = RUMBuffer::from(b"\n Hello|World \n");
927        let expected = RUMBuffer::from(b"Hello|World");
928        let new = buffer_trim(&data);
929
930        assert_eq!(new, expected.as_slice(), "Bad buffer trim! Got {:?}", new);
931    }
932
933    #[test]
934    fn test_buffer_slice_trim() {
935        let data = b"\n Hello|World \n";
936        let expected = b"Hello|World";
937        let new = buffer_slice_trim(data);
938
939        assert_eq!(new, expected, "Bad buffer slice trim! Got {:?}", new);
940    }
941
942    #[test]
943    fn test_buffer_count() {
944        let data = b"\n Hello|World \n";
945        let expected = 2;
946        let found = buffer_count(data, b'\n');
947
948        assert_eq!(found, expected, "Incorrect number of occurrences of newline found! Got {:?}", found);
949    }
950
951    #[test]
952    fn test_buffer_count_2mb() {
953        let data = new_random_buffer::<2048>();
954        let expected = 1000;
955        let (found, time) = rumtk_benchmark_snippet!(||{
956            buffer_count(&data, b'\n')
957        });
958
959        assert!(time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", time);
960    }
961
962    #[test]
963    fn test_buffer_split_simple() {
964        let mut data = RUMBuffer::from(b"Hello|World");
965        let split = data.split_to(5);
966        let expected = RUMBuffer::from(b"Hello");
967
968        assert_eq!(split, Some(expected), "Bad buffer trim! Got {:?}", split);
969    }
970
971    #[test]
972    fn test_buffer_struct_size() {
973        let data = RUMBuffer::new();
974        let struct_size = size_of::<RUMBuffer>();
975
976        assert!(struct_size <= 16, "Empty RUMBuffer structure size is too large! Length is {} bytes.", struct_size);
977    }
978
979    //////////////////////////////////////////////////////////////////////////////////////////////
980
981    ////////////////////////////CPU Tests/////////////////////////////////
982
983    #[test]
984    fn test_cpu_find_needle() {
985        let data = b"                                                         n                    ";
986        let expected = Some(57);
987        let indx = cpu_find(data, b'n');
988
989        assert_eq!(indx, expected, "Could not find the needle in the haystack");
990    }
991
992    #[test]
993    fn test_cpu_find_needle_2mb() {
994        let data = new_random_buffer::<2048>();
995        let expected = 1000;
996        let (found, time) = rumtk_benchmark_snippet!(||{
997            cpu_find(&data, b'\n')
998        });
999
1000        assert!(time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", time);
1001    }
1002
1003    #[test]
1004    fn test_cpu_find_needle_2mb_4096() {
1005        let mut all_time = 0;
1006        let expected = 1000;
1007        for i in 0..4096 {
1008            let data = new_random_buffer::<2048>();
1009            let (found, time) = rumtk_benchmark_snippet!(||{
1010                    cpu_find(&data, b'\n')
1011            });
1012            all_time += time;
1013        }
1014
1015        assert!(all_time <= expected, "Counting of instances in buffer was too slow! Took {:?} us", all_time);
1016    }
1017
1018    #[test]
1019    fn test_cpu_collect_needle() {
1020        let data = b"                                                         n                    ";
1021        let expected = vec![57];
1022        let indices = cpu_collect(data, b'n', 0);
1023
1024        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1025    }
1026
1027    #[test]
1028    fn test_cpu_collect_needle_3() {
1029        let data = b"                                                         nnn                    ";
1030        let expected = vec![57, 58, 59];
1031        let indices = cpu_collect(data, b'n', 0);
1032
1033        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1034    }
1035
1036    #[test]
1037    fn test_cpu_collect_needle_6() {
1038        let data = b"                 nnn                                        nnn                    ";
1039        let expected = vec![17, 18, 19, 60, 61, 62];
1040        let indices = cpu_collect(data, b'n', 0);
1041
1042        assert_eq!(indices.1, expected, "Could not find the needle in the haystack");
1043    }
1044
1045    #[test]
1046    fn test_cpu_tokenize_needle_6() {
1047        let data = b"                 nnn                                        nnn                    ";
1048        let expected = vec![(110, 17), (110, 18), (110, 19), (110, 60), (110, 61), (110, 62)];
1049        let indices = cpu_tokenize::<CPU_SEARCH_WINDOW_16_SIZE>(data, b"n");
1050
1051        assert_eq!(indices, expected, "Could not find the needle in the haystack");
1052    }
1053
1054    #[test]
1055    fn test_cpu_tokenize_needle_6_benchmark() {
1056        let data = b"                 nnn                                        nnn                    ";
1057        let (indices, time) = rumtk_benchmark_snippet!(||{
1058            cpu_tokenize::<CPU_SEARCH_WINDOW_16_SIZE>(data, b"n")
1059        });
1060
1061        println!("Tokenized message in {} us", &time);
1062
1063        assert!(time <= 10000, "Buffer tokenization took {} microseconds [> 10000 us]!", time);
1064    }
1065
1066    #[test]
1067    fn test_cpu_replace_simd() {
1068        let mut data = b"                                                         n                    ".to_vec();
1069        let expected = b"                                                                              ".to_vec();
1070
1071        cpu_replace_byte(data.as_mut_slice(), b'n', b' ');
1072
1073        assert_eq!(data, expected, "Failed to replace in SIMD!");
1074    }
1075
1076    #[test]
1077    fn test_cpu_replace_simd_multi() {
1078        let mut data = b"              nnnnnnnn                  nnnn                         n    nn                ".to_vec();
1079        let expected = b"                                                                                            ".to_vec();
1080
1081        cpu_replace_byte(data.as_mut_slice(), b'n', b' ');
1082
1083        assert_eq!(data, expected, "Failed to replace in SIMD!");
1084    }
1085
1086    //////////////////////////////////////////////////////////////////////////////////////////////
1087
1088    ////////////////////////////Regex Tests/////////////////////////////////
1089    #[test]
1090    fn test_regex_expression_hash() {
1091        let expr = REGEX_ANSI_ESCAPE_SEQUENCES;
1092        let hash = hash_regex_expression(expr);
1093        let hash2 = hash_regex_expression(expr);
1094        let empty_hash = hash_data("") as usize;
1095        assert!(
1096            hash > 0 && hash != empty_hash && hash == hash2,
1097            "{}",
1098            rumtk_format!("Regex expression hash failed: expr={}, hash={}, hash2={}", expr, hash, hash2)
1099        );
1100    }
1101
1102    #[test]
1103    fn test_filter_ansi_sequence() {
1104        let data = "\x1b[31mHello, World!\x1b[0m";
1105        let expected = "Hello, World!";
1106        let filtered_data = filter_ansi_escape_sequences(data).unwrap();
1107        assert_eq!(filtered_data, expected);
1108    }
1109
1110    #[test]
1111    fn test_filter_ansi_sequence_mouse_tracking() {
1112        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`";
1113        let expected = "printf `open -a calculator;notify-send Hello World`";
1114        let filtered_data = filter_ansi_escape_sequences(data).unwrap();
1115        assert_eq!(filtered_data, expected);
1116    }
1117
1118    #[test]
1119    fn test_search_number() {
1120        let data = "2007";
1121        let regex = r"\d{4}";
1122        let expected = "2007";
1123        let filtered_data = string_search(data, regex).unwrap();
1124        assert_eq!(filtered_data, expected);
1125    }
1126
1127    #[test]
1128    fn test_search_float() {
1129        let data = "-5f";
1130        let regex = r"\+|\-|\d+\.\d+e\d+|\d+e\d+|\d+\.\d+|\d+";
1131        let expected = "-5";
1132        let filtered_data = string_search(data, regex).unwrap();
1133        assert_eq!(filtered_data, expected);
1134    }
1135
1136}