Skip to content

Commit

Permalink
Merge pull request #448 from nickheyer/master
Browse files Browse the repository at this point in the history
Adding halt interupt to env
  • Loading branch information
sagiegurari authored Sep 28, 2024
2 parents 8acbcd7 + e3cfcd0 commit dd8adf1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
7 changes: 7 additions & 0 deletions duckscript/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ use crate::types::instruction::{
use crate::types::runtime::{Context, Runtime, StateValue};
use std::collections::HashMap;
use std::io::stdin;
use std::sync::atomic::Ordering;

#[derive(Debug)]
enum EndReason {
ExitCalled,
ReachedEnd,
Crash(ScriptError),
Halted
}

/// Executes the provided script with the given context
Expand Down Expand Up @@ -135,6 +137,11 @@ fn run_instructions(

let mut end_reason = EndReason::ReachedEnd;
loop {
if runtime.env.halt.load(Ordering::SeqCst) {
end_reason = EndReason::Halted;
break;
}

let (instruction, meta_info) = if instructions.len() > line {
let instruction = instructions[line].clone();
let meta_info = instruction.meta_info.clone();
Expand Down
18 changes: 9 additions & 9 deletions duckscript/src/types/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@
mod env_test;

use std::io::{stderr, stdout, Write};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;

/// The runtime env
pub struct Env {
/// The output writer
pub out: Box<dyn Write>,
/// The error writer
pub err: Box<dyn Write>,
/// The halt token - Set to true to exit after current instruction
pub halt: Arc<AtomicBool>,
}

impl Env {
Expand All @@ -23,20 +27,16 @@ impl Env {
Env {
out: Box::new(stdout()),
err: Box::new(stderr()),
halt: Arc::new(AtomicBool::new(false)),
}
}

/// Creates and returns a new instance.
pub fn new(out: Option<Box<dyn Write>>, err: Option<Box<dyn Write>>) -> Env {
pub fn new(out: Option<Box<dyn Write>>, err: Option<Box<dyn Write>>, halt: Option<Arc<AtomicBool>>) -> Env {
Env {
out: match out {
Some(value) => value,
None => Box::new(stdout()),
},
err: match err {
Some(value) => value,
None => Box::new(stderr()),
},
out: out.unwrap_or_else(|| Box::new(stdout())),
err: err.unwrap_or_else(|| Box::new(stderr())),
halt: halt.unwrap_or_else(|| Arc::new(AtomicBool::new(false))),
}
}
}
4 changes: 2 additions & 2 deletions duckscript/src/types/env_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ fn env_default() {

#[test]
fn env_new_none() {
let mut env = Env::new(None, None);
let mut env = Env::new(None, None, None);

validate_env(&mut env);
}

#[test]
fn env_new_with_values() {
let mut env = Env::new(Some(Box::new(stdout())), Some(Box::new(stdout())));
let mut env = Env::new(Some(Box::new(stdout())), Some(Box::new(stdout())), None);

validate_env(&mut env);
}

0 comments on commit dd8adf1

Please sign in to comment.