-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstring.rs
More file actions
60 lines (52 loc) · 1.65 KB
/
string.rs
File metadata and controls
60 lines (52 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Run with `RUST_LOG=debug cargo run --example cstring --features=verbose`
use std::{ffi::CString, io::Write, mem::MaybeUninit};
use ::simple_parse::SpRead;
use env_logger::Builder;
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut builder = Builder::from_default_env();
builder
.format(|buf, record| writeln!(buf, "[{}] {}", record.level(), record.args()))
.init();
let mut v = MaybeUninit::uninit();
// Strings are encoded as : [str_len][str_bytes...]
// This format is efficient as only 2 read() calls are needed
let mut some_file: &[u8] = b"\x0B\x00\x00\x00Hello World";
/* STDOUT
* [DEBUG] Read(4)
* [DEBUG] (u32) 11
* [DEBUG] Read(11)
* [DEBUG] (u8) 72
* [DEBUG] (u8) 101
* [DEBUG] (u8) 108
* [DEBUG] (u8) 108
* [DEBUG] (u8) 111
* [DEBUG] (u8) 32
* [DEBUG] (u8) 87
* [DEBUG] (u8) 111
* [DEBUG] (u8) 114
* [DEBUG] (u8) 108
* [DEBUG] (u8) 100
* Ok("Hello World")
*/
println!("{:?}", String::from_reader(&mut some_file, &mut v));
// CStrings generate a read() call for every byte until the null terminator is reached
let mut recv_sock: &[u8] = b"Hello World\0";
/* STDOUT
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* [DEBUG] Read(1)
* Ok("Hello World")
*/
let mut v = MaybeUninit::uninit();
println!("{:?}", CString::from_reader(&mut recv_sock, &mut v));
Ok(())
}