66use rustpython_compiler as compiler;
77use rustpython_vm as vm;
88// 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 } ;
1110// this needs to be in scope in order to insert things into scope.globals
1211use vm:: pyobject:: ItemProtocol ;
1312
@@ -53,27 +52,23 @@ macro_rules! add_python_function {
5352 } } ;
5453}
5554
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+ }
6160
61+ fn main ( ) -> vm:: pyobject:: PyResult < ( ) > {
6262 let mut input = String :: with_capacity ( 50 ) ;
6363 let stdin = std:: io:: stdin ( ) ;
6464
6565 let vm = vm:: VirtualMachine :: new ( vm:: PySettings :: default ( ) ) ;
6666 let scope: vm:: scope:: Scope = vm. new_scope_with_builtins ( ) ;
6767
6868 // 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) ?;
7772
7873 // let's include a fibonacci function, but let's be lazy and write it in Python
7974 add_python_function ! (
@@ -84,7 +79,7 @@ fn main() -> vm::pyobject::PyResult<()> {
8479 r#"def fib(n): return n if n <= 1 else fib(n - 1) + fib(n - 2)"#
8580 ) ?;
8681
87- while on . get ( ) {
82+ while ON . load ( Ordering :: Relaxed ) {
8883 input. clear ( ) ;
8984 stdin
9085 . read_line ( & mut input)
0 commit comments