Debian Codegraph @

src/tests/message.rs

raw symbols SCIP
1 use crate::{HeapRb, Rb};
2 use alloc::{string::String, vec::Vec};
3 use std::{
4 io::{self, Read, Write},
5 sync::{Arc, Mutex},
6 thread,
7 time::Duration,
8 };
9
10 const THE_BOOK_FOREWORD: &str = r#"
11 It wasn't always so clear, but the Rust programming language is fundamentally about empowerment: no matter what kind of code you are writing now, Rust empowers you to reach farther, to program with confidence in a wider variety of domains than you did before.
12 Take, for example, "systems-level" work that deals with low-level details of memory management, data representation, and concurrency. Traditionally, this realm of programming is seen as arcane, accessible only to a select few who have devoted the necessary years learning to avoid its infamous pitfalls. And even those who practice it do so with caution, lest their code be open to exploits, crashes, or corruption.
13 Rust breaks down these barriers by eliminating the old pitfalls and providing a friendly, polished set of tools to help you along the way. Programmers who need to "dip down" into lower-level control can do so with Rust, without taking on the customary risk of crashes or security holes, and without having to learn the fine points of a fickle toolchain. Better yet, the language is designed to guide you naturally towards reliable code that is efficient in terms of speed and memory usage.
14 Programmers who are already working with low-level code can use Rust to raise their ambitions. For example, introducing parallelism in Rust is a relatively low-risk operation: the compiler will catch the classical mistakes for you. And you can tackle more aggressive optimizations in your code with the confidence that you won't accidentally introduce crashes or vulnerabilities.
15 But Rust isn't limited to low-level systems programming. It's expressive and ergonomic enough to make CLI apps, web servers, and many other kinds of code quite pleasant to write — you'll find simple examples of both later in the book. Working with Rust allows you to build skills that transfer from one domain to another; you can learn Rust by writing a web app, then apply those same skills to target your Raspberry Pi.
16 This book fully embraces the potential of Rust to empower its users. It's a friendly and approachable text intended to help you level up not just your knowledge of Rust, but also your reach and confidence as a programmer in general. So dive in, get ready to learn—and welcome to the Rust community!
17
18 — Nicholas Matsakis and Aaron Turon
19 "#;
20
21 #[test]
22 #[cfg_attr(miri, ignore)]
23 fn push_pop_slice() {
24 let buf = HeapRb::<u8>::new(7);
25 let (mut prod, mut cons) = buf.split();
26
27 let smsg = THE_BOOK_FOREWORD;
28
29 let pjh = thread::spawn(move || {
30 let mut bytes = smsg.as_bytes();
31 while !bytes.is_empty() {
32 let n = prod.push_slice(bytes);
33 if n > 0 {
34 bytes = &bytes[n..bytes.len()]
35 } else {
36 thread::sleep(Duration::from_millis(1))
37 }
38 }
39 loop {
40 match prod.push(0) {
41 Ok(()) => break,
42 Err(_) => thread::sleep(Duration::from_millis(1)),
43 }
44 }
45 });
46
47 let cjh = thread::spawn(move || {
48 let mut bytes = Vec::<u8>::new();
49 let mut buffer = [0; 5];
50 loop {
51 let n = cons.pop_slice(&mut buffer);
52 if n > 0 {
53 bytes.extend_from_slice(&buffer[0..n])
54 } else if bytes.ends_with(&[0]) {
55 break;
56 } else {
57 thread::sleep(Duration::from_millis(1));
58 }
59 }
60
61 assert_eq!(bytes.pop().unwrap(), 0);
62 String::from_utf8(bytes).unwrap()
63 });
64
65 pjh.join().unwrap();
66 let rmsg = cjh.join().unwrap();
67
68 assert_eq!(smsg, rmsg);
69 }
70
71 #[test]
72 #[cfg_attr(miri, ignore)]
73 fn read_from_write_into() {
74 let buf = HeapRb::<u8>::new(7);
75 let (mut prod, mut cons) = buf.split();
76
77 let smsg = THE_BOOK_FOREWORD;
78
79 let pjh = thread::spawn(move || {
80 let zero = [0];
81 let mut bytes = smsg.as_bytes().chain(&zero[..]);
82 loop {
83 if prod.is_full() {
84 thread::sleep(Duration::from_millis(1));
85 } else if prod.read_from(&mut bytes, None).unwrap() == 0 {
86 break;
87 }
88 }
89 });
90
91 let cjh = thread::spawn(move || {
92 let mut bytes = Vec::<u8>::new();
93 loop {
94 if cons.is_empty() {
95 if bytes.ends_with(&[0]) {
96 break;
97 } else {
98 thread::sleep(Duration::from_millis(1));
99 }
100 } else {
101 cons.write_into(&mut bytes, None).unwrap();
102 }
103 }
104
105 assert_eq!(bytes.pop().unwrap(), 0);
106 String::from_utf8(bytes).unwrap()
107 });
108
109 pjh.join().unwrap();
110 let rmsg = cjh.join().unwrap();
111
112 assert_eq!(smsg, rmsg);
113 }
114
115 #[test]
116 #[cfg_attr(miri, ignore)]
117 fn read_write() {
118 let buf = HeapRb::<u8>::new(7);
119 let (mut prod, mut cons) = buf.split();
120
121 let smsg = THE_BOOK_FOREWORD;
122
123 let pjh = thread::spawn(move || {
124 let mut bytes = smsg.as_bytes();
125 while !bytes.is_empty() {
126 match prod.write(bytes) {
127 Ok(n) => bytes = &bytes[n..bytes.len()],
128 Err(err) => {
129 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
130 thread::sleep(Duration::from_millis(1));
131 }
132 }
133 }
134 loop {
135 match prod.push(0) {
136 Ok(()) => break,
137 Err(_) => thread::sleep(Duration::from_millis(1)),
138 }
139 }
140 });
141
142 let cjh = thread::spawn(move || {
143 let mut bytes = Vec::<u8>::new();
144 let mut buffer = [0; 5];
145 loop {
146 match cons.read(&mut buffer) {
147 Ok(n) => bytes.extend_from_slice(&buffer[0..n]),
148 Err(err) => {
149 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
150 if bytes.ends_with(&[0]) {
151 break;
152 } else {
153 thread::sleep(Duration::from_millis(1));
154 }
155 }
156 }
157 }
158
159 assert_eq!(bytes.pop().unwrap(), 0);
160 String::from_utf8(bytes).unwrap()
161 });
162
163 pjh.join().unwrap();
164 let rmsg = cjh.join().unwrap();
165
166 assert_eq!(smsg, rmsg);
167 }
168
169 #[test]
170 #[cfg_attr(miri, ignore)]
171 fn blocking() {
172 let buf = Arc::new(Mutex::new(HeapRb::<u8>::new(7)));
173 let (prod, cons) = (buf.clone(), buf);
174
175 let smsg = THE_BOOK_FOREWORD;
176
177 let pjh = thread::spawn(move || {
178 let mut bytes = smsg.as_bytes().iter().copied();
179 while bytes.len() > 0 {
180 prod.lock().unwrap().push_iter(&mut bytes);
181 thread::sleep(Duration::from_millis(1))
182 }
183 loop {
184 match prod.lock().unwrap().push(0) {
185 Ok(()) => break,
186 Err(_) => thread::sleep(Duration::from_millis(1)),
187 }
188 }
189 });
190
191 let cjh = thread::spawn(move || {
192 let mut bytes = Vec::<u8>::new();
193 loop {
194 bytes.extend(cons.lock().unwrap().pop_iter());
195 if bytes.ends_with(&[0]) {
196 break;
197 } else {
198 thread::sleep(Duration::from_millis(1));
199 }
200 }
201
202 assert_eq!(bytes.pop().unwrap(), 0);
203 String::from_utf8(bytes).unwrap()
204 });
205
206 pjh.join().unwrap();
207 let rmsg = cjh.join().unwrap();
208
209 assert_eq!(smsg, rmsg);
210 }