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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#![warn(missing_docs)]
#[macro_export]
macro_rules! with {
($with_expr:expr, |$var:ident| $bl:block) => {{
let $var = $with_expr;
$bl()
}};
}
#[macro_export]
macro_rules! bor_with {
($with_expr:expr, |$var:ident| $bl:block) => {{
let $var = &$with_expr;
$bl()
}};
}
#[macro_export]
macro_rules! mut_with {
($with_expr:expr, |$var:ident| $bl:block) => {{
let mut $var = $with_expr;
$bl()
}};
}
#[test]
fn tuple_access() {
fn get_tup() -> (String, usize) {
("meaning of life".to_string(), 42)
}
with!(get_tup(), |tup| {
let (description, value) = tup;
assert!(!description.is_empty() && value == 42);
});
}
#[test]
fn borrowed() {
use std::collections::HashMap;
use std::sync::Mutex;
let db: Mutex<HashMap<&str, String>> =
Mutex::new(vec![("key", "value".to_string())].into_iter().collect());
bor_with!(db.lock().unwrap(), |db| {
assert_eq!(db.get("key").unwrap(), &"value".to_string());
})
}
#[test]
fn mutated() {
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mut_with!(File::open(Path::new("test/hello.txt")).unwrap(), |file| {
let mut buf = String::new();
let len = file.read_to_string(&mut buf).unwrap();
assert_ne!(len, 0);
});
}