Skip to main content

Root

Struct Root 

Source
pub struct Root { /* private fields */ }
Expand description

A value kept alive while this handle lives (values themselves do not keep objects alive; see Value).

Implementations§

Source§

impl Root

Source

pub fn value(&self) -> Value

The value.

Examples found in repository?
examples/secprobe.rs (line 35)
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29    let r0 = rss();
30    let mut lua = state(mem, fast);
31    lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32    lua.set_limits(lua.limits().fuel(fuel));
33    let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34    let t = Instant::now();
35    let r = lua.call(f.value(), &[]);
36    let el = t.elapsed().as_nanos() as f64;
37    let used = fuel - lua.fuel_left();
38    let mu = lua.memory_used();
39    let g = rss().saturating_sub(r0);
40    (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}
More examples
Hide additional examples
examples/seclat.rs (line 28)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    let setup = a.get(1).cloned().unwrap_or_default();
13    let body = a.get(2).cloned().unwrap_or_default();
14    let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15    let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17    let mut worst = Duration::ZERO;
18    let mut last = String::new();
19    for _ in 0..5 {
20        let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21        lua.set_print(|_| {});
22        lua.exec(&setup, "=setup").unwrap();
23        let t0 = Instant::now();
24        let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25        lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26        let f = lua.load(&body, "=body").unwrap();
27        let start = Instant::now();
28        let r = lua.call(f.value(), &[]);
29        let el = start.elapsed();
30        worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31        last = format!("{:?}", r.err());
32    }
33    println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}
examples/sechostsoak.rs (line 24)
14fn main() {
15    let a: Vec<String> = std::env::args().collect();
16    let n: u64 = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(200_000);
17    let step: u64 = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(20_000);
18    // `nocollect`: only the incremental collector runs (garbage builds up to the limit).
19    let collect = a.get(3).is_none_or(|s| s != "nocollect");
20    let token = Arc::new(());
21    let mut lua = Lua::new(Limits::default().memory(8 << 20), Libs::STANDARD);
22    let meta = lua.create_table().unwrap();
23    let meta = lua.root(Value::Table(meta));
24    let Value::Table(mt) = meta.value() else { unreachable!() };
25    lua.exec("function check(f, u) return f(u) == u end", "=setup").unwrap();
26    let mut prev: Vec<(&'static str, usize)> = Vec::new();
27    for i in 0..n {
28        let t = Arc::clone(&token);
29        let f = lua.create_function("echo", move |_, a| {
30            let _held = &t;
31            Ok(a.to_vec())
32        }).unwrap();
33        let rf = lua.root(f);
34        let ud = lua.create_userdata(Payload(Arc::clone(&token)), Some(mt)).unwrap();
35        let ru = lua.root(ud);
36        let r = lua.call_global("check", &[rf.value(), ru.value()]).unwrap().unwrap();
37        assert_eq!(r, vec![Value::Bool(true)]);
38        let t2 = Arc::clone(&token);
39        lua.register(&format!("lib.f{}", i % 8), move |_, _| {
40            let _held = &t2;
41            Ok(vec![Value::Int(1)])
42        }).unwrap();
43        let d = lua.from_data(&Data::Table(vec![(Data::Str(format!("k{i}")), Data::Int(i as i64))])).unwrap();
44        lua.set_global("last", d).unwrap();
45        drop((rf, ru));
46        if collect && i % 200 == 0 {
47            lua.collect_garbage().unwrap();
48        }
49        if i % step == 0 {
50            let sizes = lua.internal_sizes();
51            let changed: Vec<String> = sizes
52                .iter()
53                .filter(|(k, v)| prev.iter().find(|(pk, _)| pk == k).is_none_or(|(_, pv)| pv != v))
54                .map(|(k, v)| format!("{k}={v}"))
55                .collect();
56            println!("{i:>8}: rss {:>6} KiB, used {:>6} KiB | {}", rss() >> 10, lua.memory_used() >> 10, changed.join(" "));
57            prev = sizes;
58        }
59    }
60}
examples/fuelcal.rs (line 177)
155fn main() {
156    let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157    let only = std::env::var("FUELCAL_ONLY").ok();
158    let md = std::env::var_os("FUELCAL_MD").is_some();
159    let mut rows: Vec<(&str, f64, String)> = Vec::new();
160    for &(name, setup, body) in CASES {
161        if only.as_deref().is_some_and(|o| !name.contains(o)) {
162            continue;
163        }
164        let src = format!("{setup}\nwhile true do\n{body}\nend");
165        let mut best = f64::MAX;
166        let mut note = String::new();
167        for _ in 0..3 {
168            let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169            let f = match lua.load(&src, "=cal") {
170                Ok(f) => f,
171                Err(e) => {
172                    note = format!("load: {e:?}");
173                    break;
174                }
175            };
176            let t = std::time::Instant::now();
177            let r = lua.call(f.value(), &[]);
178            let el = t.elapsed().as_secs_f64();
179            let used = fuel - lua.fuel_left();
180            match r {
181                Err(Error::Limit(LimitKind::Fuel)) => {}
182                other => note = format!("{other:?}").chars().take(80).collect(),
183            }
184            best = best.min(el * 1e9 / used.max(1) as f64);
185        }
186        if !md {
187            println!("{best:9.1} ns/unit  {name} {note}");
188        }
189        rows.push((name, best, note));
190    }
191    let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192    v.sort_by(f64::total_cmp);
193    let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194    if md {
195        println!("| case | ns/unit | x median |\n|---|---:|---:|");
196        for (name, ns, note) in &rows {
197            println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198        }
199    }
200    println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201    let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202    worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203    for (name, ns, _) in worst {
204        println!("  over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205    }
206}
examples/interngap.rs (line 45)
32fn main() {
33    let a: Vec<String> = std::env::args().collect();
34    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35    let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36    let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37    // The table grows first (its array part's growth is not the interner's).
38    lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39    let (clock, st) = gap_clock();
40    lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41    let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42    let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43    st.lock().unwrap().0 = Instant::now();
44    let t = Instant::now();
45    lua.call(f.value(), &[]).unwrap();
46    let all = t.elapsed();
47    let g = *st.lock().unwrap();
48    println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49    println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50    let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51    println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52    println!(
53        "{:?}",
54        lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55    );
56    if k == 0 {
57        return;
58    }
59    // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60    // a load stops after it, at points along the load.
61    let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62    let full = {
63        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64        let t = Instant::now();
65        l.load(&src, "=t").unwrap();
66        t.elapsed()
67    };
68    let mut worst = Duration::ZERO;
69    for p in 1..=12u32 {
70        let at = full * p / 13;
71        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72        let h = l.interrupt_handle();
73        let th = std::thread::spawn(move || {
74            std::thread::sleep(at);
75            h.interrupt();
76            Instant::now()
77        });
78        let r = l.load(&src, "=t").map(|_| ());
79        let end = Instant::now();
80        let fired = th.join().unwrap();
81        if r.is_err() {
82            worst = worst.max(end.saturating_duration_since(fired));
83        }
84    }
85    println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}

Trait Implementations§

Source§

impl Clone for Root

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Root

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Root

§

impl Freeze for Root

§

impl Move for Root

§

impl RefUnwindSafe for Root

§

impl Send for Root

§

impl Sync for Root

§

impl Unpin for Root

§

impl UnsafeUnpin for Root

§

impl UnwindSafe for Root

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.