Debian Codegraph @

third_party/rust/ringbuf/src/tests/message.rs

raw
1 use crate::RingBuffer;
2 use alloc::{string::String, vec::Vec};
3 use std::{
4 io::{self, Read, Write},
5 thread,
6 time::Duration,
7 };
8
9 const THE_BOOK_FOREWORD: &str = "
10 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.
11 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.
12 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.
13 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.
14 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.
15 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!
16
17 — Nicholas Matsakis and Aaron Turon
18 ";
19
20 #[test]
21 #[cfg_attr(miri, ignore)]
22 fn push_pop_slice() {
23 let buf = RingBuffer::<u8>::new(7);
24 let (mut prod, mut cons) = buf.split();
25
26 let smsg = THE_BOOK_FOREWORD;
27
28 let pjh = thread::spawn(move || {
29 let mut bytes = smsg.as_bytes();
30 while !bytes.is_empty() {
31 let n = prod.push_slice(bytes);
32 if n > 0 {
33 bytes = &bytes[n..bytes.len()]
34 } else {
35 thread::sleep(Duration::from_millis(1))
36 }
37 }
38 loop {
39 match prod.push(0) {
40 Ok(()) => break,
41 Err(_) => thread::sleep(Duration::from_millis(1)),
42 }
43 }
44 });
45
46 let cjh = thread::spawn(move || {
47 let mut bytes = Vec::<u8>::new();
48 let mut buffer = [0; 5];
49 loop {
50 let n = cons.pop_slice(&mut buffer);
51 if n > 0 {
52 bytes.extend_from_slice(&buffer[0..n])
53 } else if bytes.ends_with(&[0]) {
54 break;
55 } else {
56 thread::sleep(Duration::from_millis(1));
57 }
58 }
59
60 assert_eq!(bytes.pop().unwrap(), 0);
61 String::from_utf8(bytes).unwrap()
62 });
63
64 pjh.join().unwrap();
65 let rmsg = cjh.join().unwrap();
66
67 assert_eq!(smsg, rmsg);
68 }
69
70 #[test]
71 #[cfg_attr(miri, ignore)]
72 fn read_from_write_into() {
73 let buf = RingBuffer::<u8>::new(7);
74 let (mut prod, mut cons) = buf.split();
75
76 let smsg = THE_BOOK_FOREWORD;
77
78 let pjh = thread::spawn(move || {
79 let zero = [0];
80 let mut bytes = smsg.as_bytes().chain(&zero[..]);
81 loop {
82 if prod.is_full() {
83 thread::sleep(Duration::from_millis(1));
84 } else if prod.read_from(&mut bytes, None).unwrap() == 0 {
85 break;
86 }
87 }
88 });
89
90 let cjh = thread::spawn(move || {
91 let mut bytes = Vec::<u8>::new();
92 loop {
93 if cons.is_empty() {
94 if bytes.ends_with(&[0]) {
95 break;
96 } else {
97 thread::sleep(Duration::from_millis(1));
98 }
99 } else {
100 cons.write_into(&mut bytes, None).unwrap();
101 }
102 }
103
104 assert_eq!(bytes.pop().unwrap(), 0);
105 String::from_utf8(bytes).unwrap()
106 });
107
108 pjh.join().unwrap();
109 let rmsg = cjh.join().unwrap();
110
111 assert_eq!(smsg, rmsg);
112 }
113
114 #[test]
115 #[cfg_attr(miri, ignore)]
116 fn read_write() {
117 let buf = RingBuffer::<u8>::new(7);
118 let (mut prod, mut cons) = buf.split();
119
120 let smsg = THE_BOOK_FOREWORD;
121
122 let pjh = thread::spawn(move || {
123 let mut bytes = smsg.as_bytes();
124 while !bytes.is_empty() {
125 match prod.write(bytes) {
126 Ok(n) => bytes = &bytes[n..bytes.len()],
127 Err(err) => {
128 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
129 thread::sleep(Duration::from_millis(1));
130 }
131 }
132 }
133 loop {
134 match prod.push(0) {
135 Ok(()) => break,
136 Err(_) => thread::sleep(Duration::from_millis(1)),
137 }
138 }
139 });
140
141 let cjh = thread::spawn(move || {
142 let mut bytes = Vec::<u8>::new();
143 let mut buffer = [0; 5];
144 loop {
145 match cons.read(&mut buffer) {
146 Ok(n) => bytes.extend_from_slice(&buffer[0..n]),
147 Err(err) => {
148 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
149 if bytes.ends_with(&[0]) {
150 break;
151 } else {
152 thread::sleep(Duration::from_millis(1));
153 }
154 }
155 }
156 }
157
158 assert_eq!(bytes.pop().unwrap(), 0);
159 String::from_utf8(bytes).unwrap()
160 });
161
162 pjh.join().unwrap();
163 let rmsg = cjh.join().unwrap();
164
165 assert_eq!(smsg, rmsg);
166 }