6
6
use rustpython_compiler as compiler;
7
7
use rustpython_vm as vm;
8
8
// these are needed for special memory shenanigans to let us share a variable with Python and Rust
9
- use std:: cell:: Cell ;
10
- use std:: rc:: Rc ;
9
+ use std:: sync:: atomic:: { AtomicBool , Ordering } ;
11
10
// this needs to be in scope in order to insert things into scope.globals
12
11
use vm:: pyobject:: ItemProtocol ;
13
12
@@ -53,27 +52,23 @@ macro_rules! add_python_function {
53
52
} } ;
54
53
}
55
54
56
- fn main ( ) -> vm :: pyobject :: PyResult < ( ) > {
57
- // you can also use a raw pointer instead of Rc<Cell<_>>, but that requires usage of unsafe.
58
- // both methods are ways of circumnavigating the fact that Python doesn't respect Rust's borrow
59
- // checking rules.
60
- let on : Rc < Cell < bool > > = Rc :: new ( Cell :: new ( true ) ) ;
55
+ static ON : AtomicBool = AtomicBool :: new ( false ) ;
56
+
57
+ fn on ( b : bool ) {
58
+ ON . store ( b , Ordering :: Relaxed ) ;
59
+ }
61
60
61
+ fn main ( ) -> vm:: pyobject:: PyResult < ( ) > {
62
62
let mut input = String :: with_capacity ( 50 ) ;
63
63
let stdin = std:: io:: stdin ( ) ;
64
64
65
65
let vm = vm:: VirtualMachine :: new ( vm:: PySettings :: default ( ) ) ;
66
66
let scope: vm:: scope:: Scope = vm. new_scope_with_builtins ( ) ;
67
67
68
68
// typing `quit()` is too long, let's make `on(False)` work instead.
69
- scope. globals . set_item (
70
- "on" ,
71
- vm. context ( ) . new_function ( {
72
- let on = Rc :: clone ( & on) ;
73
- move |b : bool | on. set ( b)
74
- } ) ,
75
- & vm,
76
- ) ?;
69
+ scope
70
+ . globals
71
+ . set_item ( "on" , vm. context ( ) . new_function ( on) , & vm) ?;
77
72
78
73
// let's include a fibonacci function, but let's be lazy and write it in Python
79
74
add_python_function ! (
@@ -84,7 +79,7 @@ fn main() -> vm::pyobject::PyResult<()> {
84
79
r#"def fib(n): return n if n <= 1 else fib(n - 1) + fib(n - 2)"#
85
80
) ?;
86
81
87
- while on . get ( ) {
82
+ while ON . load ( Ordering :: Relaxed ) {
88
83
input. clear ( ) ;
89
84
stdin
90
85
. read_line ( & mut input)
0 commit comments