repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/coupon.rs
debug_utils/sierra-emu/src/vm/coupon.rs
use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, coupon::CouponConcreteLibfunc, function_call::SignatureAndFunctionConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; use super::EvalAction; use crate::Value; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &CouponConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { CouponConcreteLibfunc::Buy(info) => eval_buy(registry, info, args), CouponConcreteLibfunc::Refund(info) => eval_refund(registry, info, args), } } fn eval_buy( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndFunctionConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Unit]) } fn eval_refund( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndFunctionConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/box.rs
debug_utils/sierra-emu/src/vm/box.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ boxing::BoxConcreteLibfunc, core::{CoreLibfunc, CoreType}, lib_func::SignatureAndTypeConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &BoxConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { BoxConcreteLibfunc::Into(info) => eval_into_box(registry, info, args), BoxConcreteLibfunc::Unbox(info) => eval_unbox(registry, info, args), BoxConcreteLibfunc::ForwardSnapshot(info) => eval_forward_snapshot(registry, info, args), BoxConcreteLibfunc::LocalInto(_) => todo!(), } } pub fn eval_unbox( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } pub fn eval_into_box( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } pub fn eval_forward_snapshot( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/dup.rs
debug_utils/sierra-emu/src/vm/dup.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value.clone(), value]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/branch_align.rs
debug_utils/sierra-emu/src/vm/branch_align.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/int_range.rs
debug_utils/sierra-emu/src/vm/int_range.rs
use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType, CoreTypeConcrete}, lib_func::SignatureOnlyConcreteLibfunc, range::IntRangeConcreteLibfunc, ConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_bigint::BigInt; use smallvec::smallvec; use crate::{ utils::{get_numeric_args_as_bigints, get_value_from_integer}, Value, }; use super::EvalAction; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &IntRangeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { IntRangeConcreteLibfunc::TryNew(info) => eval_try_new(registry, info, args), IntRangeConcreteLibfunc::PopFront(info) => eval_pop_front(registry, info, args), } } fn eval_try_new( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [x, y]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty_id = &info.param_signatures()[1].ty; // if x >= y then the range is not valid and we return [y, y) (empty range) if x < y { let x = get_value_from_integer(registry, int_ty_id, x); let y = get_value_from_integer(registry, int_ty_id, y); EvalAction::NormalBranch( 0, smallvec![ range_check, Value::IntRange { x: Box::new(x), y: Box::new(y), } ], ) } else { let y = get_value_from_integer(registry, int_ty_id, y); EvalAction::NormalBranch( 1, smallvec![ range_check, Value::IntRange { x: Box::new(y.clone()), y: Box::new(y), } ], ) } } fn eval_pop_front( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::IntRange { x, y }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let [x, y]: [BigInt; 2] = get_numeric_args_as_bigints(&[*x, *y]).try_into().unwrap(); let int_ty_id = match registry.get_type(&info.param_signatures()[0].ty).unwrap() { CoreTypeConcrete::IntRange(info) => &info.ty, _ => panic!(), }; if x < y { let x_plus_1 = get_value_from_integer(registry, int_ty_id, &x + 1); let x = get_value_from_integer(registry, int_ty_id, x); let y = get_value_from_integer(registry, int_ty_id, y); EvalAction::NormalBranch( 1, smallvec![ Value::IntRange { x: Box::new(x_plus_1), y: Box::new(y) }, x ], ) } else { EvalAction::NormalBranch(0, smallvec![]) } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/bounded_int.rs
debug_utils/sierra-emu/src/vm/bounded_int.rs
use super::EvalAction; use crate::{ utils::{get_numeric_args_as_bigints, get_value_from_integer}, Value, }; use cairo_lang_sierra::{ extensions::{ bounded_int::{ BoundedIntConcreteLibfunc, BoundedIntConstrainConcreteLibfunc, BoundedIntDivRemConcreteLibfunc, BoundedIntTrimConcreteLibfunc, }, core::{CoreLibfunc, CoreType, CoreTypeConcrete}, lib_func::SignatureOnlyConcreteLibfunc, ConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_bigint::BigInt; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &BoundedIntConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { BoundedIntConcreteLibfunc::Add(info) => eval_add(registry, info, args), BoundedIntConcreteLibfunc::Sub(info) => eval_sub(registry, info, args), BoundedIntConcreteLibfunc::Mul(info) => eval_mul(registry, info, args), BoundedIntConcreteLibfunc::DivRem(info) => eval_div_rem(registry, info, args), BoundedIntConcreteLibfunc::Constrain(info) => eval_constrain(registry, info, args), BoundedIntConcreteLibfunc::IsZero(info) => eval_is_zero(registry, info, args), BoundedIntConcreteLibfunc::WrapNonZero(info) => eval_wrap_non_zero(registry, info, args), BoundedIntConcreteLibfunc::TrimMin(info) | BoundedIntConcreteLibfunc::TrimMax(info) => { eval_trim(registry, info, args) } } } pub fn eval_add( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let range = match registry .get_type(&info.signature.branch_signatures[0].vars[0].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.lower.clone()..info.range.upper.clone(), CoreTypeConcrete::NonZero(info) => match registry.get_type(&info.ty).unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } _ => unreachable!(), }, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![Value::BoundedInt { range, value: lhs + rhs, }], ) } pub fn eval_sub( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let range = match registry .get_type(&info.signature.branch_signatures[0].vars[0].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.lower.clone()..info.range.upper.clone(), CoreTypeConcrete::NonZero(info) => match registry.get_type(&info.ty).unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } _ => unreachable!(), }, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![Value::BoundedInt { range, value: lhs - rhs, }], ) } pub fn eval_mul( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let range = match registry .get_type(&info.signature.branch_signatures[0].vars[0].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.lower.clone()..info.range.upper.clone(), CoreTypeConcrete::NonZero(info) => match registry.get_type(&info.ty).unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } _ => unreachable!(), }, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![Value::BoundedInt { range, value: lhs * rhs, }], ) } pub fn eval_div_rem( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &BoundedIntDivRemConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let quo = &lhs / &rhs; let rem = lhs % rhs; let quo_range = match registry .get_type(&info.branch_signatures()[0].vars[1].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.lower.clone()..info.range.upper.clone(), _ => unreachable!(), }; let rem_range = match registry .get_type(&info.branch_signatures()[0].vars[2].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.lower.clone()..info.range.upper.clone(), _ => unreachable!(), }; assert!(quo_range.contains(&quo)); assert!(rem_range.contains(&rem)); EvalAction::NormalBranch( 0, smallvec![ range_check, Value::BoundedInt { range: quo_range, value: quo, }, Value::BoundedInt { range: rem_range, value: rem, }, ], ) } pub fn eval_constrain( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &BoundedIntConstrainConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [value]: [BigInt; 1] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); if value < info.boundary { let range = match registry .get_type(&info.branch_signatures()[0].vars[1].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } CoreTypeConcrete::NonZero(info) => match registry.get_type(&info.ty).unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } _ => unreachable!(), }, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![range_check, Value::BoundedInt { range, value }], ) } else { let range = match registry .get_type(&info.branch_signatures()[1].vars[1].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } CoreTypeConcrete::NonZero(info) => match registry.get_type(&info.ty).unwrap() { CoreTypeConcrete::BoundedInt(info) => { info.range.lower.clone()..info.range.upper.clone() } _ => unreachable!(), }, _ => unreachable!(), }; EvalAction::NormalBranch( 1, smallvec![range_check, Value::BoundedInt { range, value }], ) } } pub fn eval_is_zero( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let is_zero = value == 0.into(); let int_ty = &info.branch_signatures()[1].vars[0].ty; if is_zero { EvalAction::NormalBranch(0, smallvec![]) } else { let value = get_value_from_integer(registry, int_ty, value); EvalAction::NormalBranch(1, smallvec![value]) } } pub fn eval_wrap_non_zero( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } pub fn eval_trim( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &BoundedIntTrimConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); let value = match value { Value::I8(v) => BigInt::from(v), Value::I16(v) => BigInt::from(v), Value::I32(v) => BigInt::from(v), Value::I64(v) => BigInt::from(v), Value::I128(v) => BigInt::from(v), Value::U8(v) => BigInt::from(v), Value::U16(v) => BigInt::from(v), Value::U32(v) => BigInt::from(v), Value::U64(v) => BigInt::from(v), Value::U128(v) => BigInt::from(v), Value::BoundedInt { value, .. } => value, _ => panic!("Not a valid integer type"), }; let is_invalid = value == info.trimmed_value; let int_range = match registry .get_type(&info.branch_signatures()[1].vars[0].ty) .unwrap() { CoreTypeConcrete::BoundedInt(info) => info.range.clone(), _ => panic!("should be bounded int"), }; if !is_invalid { let range = int_range.lower.clone()..int_range.upper.clone(); EvalAction::NormalBranch(1, smallvec![Value::BoundedInt { range, value }]) } else { EvalAction::NormalBranch(0, smallvec![]) } } #[cfg(test)] mod tests { use num_bigint::BigInt; use super::Value; use crate::{load_cairo, test_utils::run_test_program}; #[test] fn test_bounded_int_sub() { let (_, program) = load_cairo!( #[feature("bounded-int-utils")] use core::internal::bounded_int::{self, SubHelper, BoundedInt}; impl U8BISub of SubHelper<u8, u8> { type Result = BoundedInt<-255, 255>; } extern fn bounded_int_sub<Lhs, Rhs, impl H: SubHelper<Lhs, Rhs>>( lhs: Lhs, rhs: Rhs, ) -> H::Result nopanic; fn main() -> BoundedInt<-255, 255> { bounded_int_sub(0_u8, 255_u8) } ); run_test_program(program); } #[test] fn test_trim_i8() { let (_, program) = load_cairo!( #[feature("bounded-int-utils")] use core::internal::bounded_int::{self, BoundedInt}; use core::internal::OptionRev; fn main() -> BoundedInt<-127, 127> { let num = match bounded_int::trim_min::<i8>(1) { OptionRev::Some(n) => n, OptionRev::None => 1, }; num } ); let result = run_test_program(program); let result = result.last().unwrap(); let expected = Value::BoundedInt { range: BigInt::from(-127)..BigInt::from(128), value: BigInt::from(1u8), }; assert_eq!(*result, expected); } #[test] fn test_trim_u32() { let (_, program) = load_cairo!( #[feature("bounded-int-utils")] use core::internal::bounded_int::{self, BoundedInt}; use core::internal::OptionRev; fn main() -> BoundedInt<0, 4294967294> { let num = match bounded_int::trim_max::<u32>(0xfffffffe) { OptionRev::Some(n) => n, OptionRev::None => 0, }; num } ); let result = run_test_program(program); let result = result.last().unwrap(); let expected = Value::BoundedInt { range: BigInt::from(0)..BigInt::from(4294967295u32), value: BigInt::from(0xfffffffeu32), }; assert_eq!(*result, expected); } #[test] fn test_trim_none() { let (_, program) = load_cairo!( #[feature("bounded-int-utils")] use core::internal::bounded_int::{self, BoundedInt}; use core::internal::OptionRev; fn main() -> BoundedInt<-32767, 32767> { let num = match bounded_int::trim_min::<i16>(-0x8000) { OptionRev::Some(n) => n, OptionRev::None => 0, }; num } ); let result = run_test_program(program); let result = result.last().unwrap(); let expected = Value::BoundedInt { range: BigInt::from(-32767)..BigInt::from(32768), value: BigInt::from(0), }; assert_eq!(*result, expected); } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/snapshot_take.rs
debug_utils/sierra-emu/src/vm/snapshot_take.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value.clone(), value]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/pedersen.rs
debug_utils/sierra-emu/src/vm/pedersen.rs
use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, pedersen::PedersenConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; use crate::Value; use super::EvalAction; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &PedersenConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { PedersenConcreteLibfunc::PedersenHash(info) => eval_pedersen_hash(registry, info, args), } } fn eval_pedersen_hash( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [pedersen @ Value::Unit, Value::Felt(lhs), Value::Felt(rhs)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let res = starknet_crypto::pedersen_hash(&lhs, &rhs); EvalAction::NormalBranch(0, smallvec![pedersen, Value::Felt(res),]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/felt252_dict_entry.rs
debug_utils/sierra-emu/src/vm/felt252_dict_entry.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, felt252_dict::Felt252DictEntryConcreteLibfunc, lib_func::SignatureAndTypeConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Felt252DictEntryConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { Felt252DictEntryConcreteLibfunc::Get(info) => eval_get(registry, info, args), Felt252DictEntryConcreteLibfunc::Finalize(info) => eval_finalize(registry, info, args), } } pub fn eval_get( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::FeltDict { ty, mut data, mut count, }, Value::Felt(key)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; assert_eq!(info.ty, ty); let value = data .entry(key) .or_insert(Value::default_for_type(registry, &ty)) .clone(); count += 1; EvalAction::NormalBranch( 0, smallvec![ Value::FeltDictEntry { ty, data, count, key }, value ], ) } pub fn eval_finalize( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::FeltDictEntry { ty, mut data, count, key, }, value]: [Value; 2] = args.try_into().unwrap() else { panic!() }; assert_eq!(info.ty, ty); assert!(value.is(registry, &ty)); data.insert(key, value); EvalAction::NormalBranch(0, smallvec![Value::FeltDict { ty, data, count }]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/gas_reserve.rs
debug_utils/sierra-emu/src/vm/gas_reserve.rs
use cairo_lang_sierra::extensions::gas_reserve::GasReserveConcreteLibfunc; use smallvec::smallvec; use crate::{vm::EvalAction, Value}; pub fn eval(selector: &GasReserveConcreteLibfunc, args: Vec<Value>) -> EvalAction { match selector { GasReserveConcreteLibfunc::Create(_) => eval_gas_reserve_create(args), GasReserveConcreteLibfunc::Utilize(_) => eval_gas_reserve_utilize(args), } } fn eval_gas_reserve_create(args: Vec<Value>) -> EvalAction { let [range_check @ Value::Unit, Value::U64(gas), Value::U128(amount)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; if amount <= gas.into() { let spare_gas = gas - amount as u64; EvalAction::NormalBranch( 0, smallvec![range_check, Value::U64(spare_gas), Value::U128(amount)], ) } else { EvalAction::NormalBranch(1, smallvec![range_check, Value::U64(gas)]) } } fn eval_gas_reserve_utilize(args: Vec<Value>) -> EvalAction { let [Value::U64(gas), Value::U128(amount)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let updated_gas = gas + amount as u64; EvalAction::NormalBranch(0, smallvec![Value::U64(updated_gas)]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/jump.rs
debug_utils/sierra-emu/src/vm/jump.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/bool.rs
debug_utils/sierra-emu/src/vm/bool.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ boolean::BoolConcreteLibfunc, core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &BoolConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { BoolConcreteLibfunc::And(info) => eval_and(registry, info, args), BoolConcreteLibfunc::Not(info) => eval_not(registry, info, args), BoolConcreteLibfunc::Xor(info) => eval_xor(registry, info, args), BoolConcreteLibfunc::Or(info) => eval_or(registry, info, args), BoolConcreteLibfunc::ToFelt252(info) => eval_to_felt252(registry, info, args), } } pub fn eval_and( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index: lhs, payload, }, Value::Enum { self_ty: _, index: rhs, payload: _, }]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let lhs = lhs != 0; let rhs = rhs != 0; EvalAction::NormalBranch( 0, smallvec![Value::Enum { self_ty, index: (lhs && rhs) as usize, payload }], ) } pub fn eval_not( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index: lhs, payload, }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch( 0, smallvec![Value::Enum { self_ty, index: (lhs == 0) as usize, payload }], ) } pub fn eval_xor( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index: lhs, payload, }, Value::Enum { self_ty: _, index: rhs, payload: _, }]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let lhs = lhs != 0; let rhs = rhs != 0; EvalAction::NormalBranch( 0, smallvec![Value::Enum { self_ty, index: (lhs ^ rhs) as usize, payload }], ) } pub fn eval_or( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index: lhs, payload, }, Value::Enum { self_ty: _, index: rhs, payload: _, }]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let lhs = lhs != 0; let rhs = rhs != 0; EvalAction::NormalBranch( 0, smallvec![Value::Enum { self_ty, index: (lhs || rhs) as usize, payload }], ) } pub fn eval_to_felt252( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty: _, index: lhs, payload: _, }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch(0, smallvec![Value::Felt(lhs.into())]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/nullable.rs
debug_utils/sierra-emu/src/vm/nullable.rs
use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::{SignatureAndTypeConcreteLibfunc, SignatureOnlyConcreteLibfunc}, nullable::NullableConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; use crate::Value; use super::EvalAction; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &NullableConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { NullableConcreteLibfunc::Null(info) => eval_null(registry, info, args), NullableConcreteLibfunc::NullableFromBox(info) => { eval_nullable_from_box(registry, info, args) } NullableConcreteLibfunc::MatchNullable(info) => eval_match_nullable(registry, info, args), NullableConcreteLibfunc::ForwardSnapshot(info) => { eval_forward_snapshot(registry, info, args) } } } fn eval_null( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![Value::Null]) } fn eval_nullable_from_box( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value]: [Value; 1] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } fn eval_match_nullable( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value]: [Value; 1] = args.try_into().unwrap(); if matches!(value, Value::Null) { EvalAction::NormalBranch(0, smallvec![]) } else { EvalAction::NormalBranch(1, smallvec![value]) } } fn eval_forward_snapshot( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value]: [Value; 1] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/starknet.rs
debug_utils/sierra-emu/src/vm/starknet.rs
use super::EvalAction; use crate::{ starknet::{Secp256k1Point, Secp256r1Point, StarknetSyscallHandler, U256}, Value, }; use cairo_lang_sierra::{ extensions::{ consts::SignatureAndConstConcreteLibfunc, core::{CoreLibfunc, CoreType, CoreTypeConcrete}, lib_func::SignatureOnlyConcreteLibfunc, starknet::StarknetConcreteLibfunc, ConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_traits::One; use smallvec::smallvec; use starknet_types_core::felt::Felt; enum SecpPointType { K1, R1, } pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &StarknetConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { match selector { StarknetConcreteLibfunc::CallContract(info) => { self::eval_call_contract(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::ClassHashConst(info) => { eval_class_hash_const(registry, info, args) } StarknetConcreteLibfunc::ClassHashTryFromFelt252(info) => { eval_class_hash_try_from_felt(registry, info, args) } StarknetConcreteLibfunc::ClassHashToFelt252(info) => { eval_class_hash_to_felt(registry, info, args) } StarknetConcreteLibfunc::ContractAddressConst(info) => { eval_contract_address_const(registry, info, args) } StarknetConcreteLibfunc::ContractAddressTryFromFelt252(info) => { eval_contract_address_try_from_felt(registry, info, args) } StarknetConcreteLibfunc::ContractAddressToFelt252(info) => { eval_contract_address_to_felt(registry, info, args) } StarknetConcreteLibfunc::StorageRead(info) => { eval_storage_read(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::StorageWrite(info) => { eval_storage_write(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::StorageBaseAddressConst(info) => { eval_storage_base_address_const(registry, info, args) } StarknetConcreteLibfunc::StorageBaseAddressFromFelt252(info) => { eval_storage_base_address_from_felt(registry, info, args) } StarknetConcreteLibfunc::StorageAddressFromBase(info) => { eval_storage_address_from_base(registry, info, args) } StarknetConcreteLibfunc::StorageAddressFromBaseAndOffset(info) => { eval_storage_address_from_base_and_offset(registry, info, args) } StarknetConcreteLibfunc::StorageAddressToFelt252(info) => { eval_storage_address_to_felt(registry, info, args) } StarknetConcreteLibfunc::StorageAddressTryFromFelt252(info) => { eval_storage_address_try_from_felt(registry, info, args) } StarknetConcreteLibfunc::EmitEvent(info) => { eval_emit_event(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::GetBlockHash(info) => { eval_get_block_hash(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::GetExecutionInfo(info) => { eval_get_execution_info(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::GetExecutionInfoV2(info) => { eval_get_execution_info_v2(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::Deploy(info) => eval_deploy(registry, info, args, syscall_handler), StarknetConcreteLibfunc::Keccak(info) => eval_keccak(registry, info, args, syscall_handler), StarknetConcreteLibfunc::Sha256ProcessBlock(info) => { eval_sha256_process_block(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::Sha256StateHandleInit(info) => { eval_sha256_state_handle_init(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::Sha256StateHandleDigest(info) => { eval_sha256_state_handle_digest(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::LibraryCall(info) => { eval_library_call(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::ReplaceClass(info) => { eval_replace_class(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::SendMessageToL1(info) => { eval_send_message_to_l1(registry, info, args, syscall_handler) } StarknetConcreteLibfunc::Testing(_) => todo!(), StarknetConcreteLibfunc::Secp256(info) => match info { cairo_lang_sierra::extensions::starknet::secp256::Secp256ConcreteLibfunc::K1(info) => { match info { cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::New(info) => eval_secp256_new(registry, info, args, syscall_handler, SecpPointType::K1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::Add(info) => eval_secp256_add(registry, info, args, syscall_handler, SecpPointType::K1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::Mul(info) => eval_secp256_mul(registry, info, args, syscall_handler, SecpPointType::K1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::GetPointFromX(info) => eval_secp256_get_point_from_x(registry, info, args, syscall_handler, SecpPointType::K1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::GetXy(info) => eval_secp256_get_xy(registry, info, args, syscall_handler, SecpPointType::K1), } } cairo_lang_sierra::extensions::starknet::secp256::Secp256ConcreteLibfunc::R1(info) => { match info { cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::New(info) => eval_secp256_new(registry, info, args, syscall_handler, SecpPointType::R1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::Add(info) => eval_secp256_add(registry, info, args, syscall_handler, SecpPointType::R1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::Mul(info) => eval_secp256_mul(registry, info, args, syscall_handler, SecpPointType::R1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::GetPointFromX(info) => eval_secp256_get_point_from_x(registry, info, args, syscall_handler, SecpPointType::R1), cairo_lang_sierra::extensions::starknet::secp256::Secp256OpConcreteLibfunc::GetXy(info) => eval_secp256_get_xy(registry, info, args, syscall_handler, SecpPointType::R1), } } }, StarknetConcreteLibfunc::GetClassHashAt(info) => eval_get_class_hash_at(registry, info, args, syscall_handler), StarknetConcreteLibfunc::MetaTxV0(info) => eval_meta_tx_v0(registry, info, args, syscall_handler), StarknetConcreteLibfunc::GetExecutionInfoV3(_) => todo!(), } } fn eval_secp256_new( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, secp_type: SecpPointType, ) -> EvalAction { let [Value::U64(mut gas), system @ Value::Unit, Value::Struct(x), Value::Struct(y)]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let Value::U128(x_lo) = x[0] else { panic!() }; let Value::U128(x_hi) = x[1] else { panic!() }; let x = U256 { lo: x_lo, hi: x_hi }; let Value::U128(y_lo) = y[0] else { panic!() }; let Value::U128(y_hi) = y[1] else { panic!() }; let y = U256 { lo: y_lo, hi: y_hi }; let syscall_result = match secp_type { SecpPointType::K1 => syscall_handler .secp256k1_new(x, y, &mut gas) .map(|res| res.map(|op| op.into_value())), SecpPointType::R1 => syscall_handler .secp256r1_new(x, y, &mut gas) .map(|res| res.map(|op| op.into_value())), }; match syscall_result { Ok(p) => { let enum_ty = &info.branch_signatures()[0].vars[2].ty; let value = match p { Some(p) => Value::Enum { self_ty: enum_ty.clone(), index: 0, payload: Box::new(p), }, None => Value::Enum { self_ty: enum_ty.clone(), index: 1, payload: Box::new(Value::Struct(vec![])), }, }; EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, value]) } Err(payload) => { // get felt type from the error branch array let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let value = payload.into_iter().map(Value::Felt).collect::<Vec<_>>(); EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: value } ], ) } } } fn eval_secp256_add( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, secp_type: SecpPointType, ) -> EvalAction { let [Value::U64(mut gas), system @ Value::Unit, x, y]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let syscall_result = match secp_type { SecpPointType::K1 => { let x = Secp256k1Point::from_value(x); let y = Secp256k1Point::from_value(y); syscall_handler .secp256k1_add(x, y, &mut gas) .map(|res| res.into_value()) } SecpPointType::R1 => { let x = Secp256r1Point::from_value(x); let y = Secp256r1Point::from_value(y); syscall_handler .secp256r1_add(x, y, &mut gas) .map(|res| res.into_value()) } }; match syscall_result { Ok(x) => EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, x]), Err(r) => { let r = Value::Struct(r.into_iter().map(Value::Felt).collect::<Vec<_>>()); EvalAction::NormalBranch(1, smallvec![Value::U64(gas), system, r]) } } } fn eval_secp256_mul( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, secp_type: SecpPointType, ) -> EvalAction { let [Value::U64(mut gas), system @ Value::Unit, x, n]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let n = U256::from_value(n); let syscall_result = match secp_type { SecpPointType::K1 => { let x = Secp256k1Point::from_value(x); syscall_handler .secp256k1_mul(x, n, &mut gas) .map(|res| res.into_value()) } SecpPointType::R1 => { let x = Secp256r1Point::from_value(x); syscall_handler .secp256r1_mul(x, n, &mut gas) .map(|res| res.into_value()) } }; match syscall_result { Ok(x) => EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, x]), Err(r) => { let r = Value::Struct(r.into_iter().map(Value::Felt).collect::<Vec<_>>()); EvalAction::NormalBranch(1, smallvec![Value::U64(gas), system, r]) } } } fn eval_secp256_get_point_from_x( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, secp_type: SecpPointType, ) -> EvalAction { let [Value::U64(mut gas), system @ Value::Unit, Value::Struct(x), Value::Enum { index: y_parity, .. }]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let Value::U128(x_lo) = x[0] else { panic!() }; let Value::U128(x_hi) = x[1] else { panic!() }; let x = U256 { lo: x_lo, hi: x_hi }; let y_parity = y_parity.is_one(); let syscall_result = match secp_type { SecpPointType::K1 => syscall_handler .secp256k1_get_point_from_x(x, y_parity, &mut gas) .map(|res| res.map(|op| op.into_value())), SecpPointType::R1 => syscall_handler .secp256r1_get_point_from_x(x, y_parity, &mut gas) .map(|res| res.map(|op| op.into_value())), }; match syscall_result { Ok(p) => { let enum_ty = &info.branch_signatures()[0].vars[2].ty; let value = match p { Some(p) => Value::Enum { self_ty: enum_ty.clone(), index: 0, payload: Box::new(p), }, None => Value::Enum { self_ty: enum_ty.clone(), index: 1, payload: Box::new(Value::Struct(vec![])), }, }; EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, value]) } Err(payload) => { // get felt type from the error branch array let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let value = payload.into_iter().map(Value::Felt).collect::<Vec<_>>(); EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: value } ], ) } } } fn eval_secp256_get_xy( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, secp_type: SecpPointType, ) -> EvalAction { let [Value::U64(mut gas), system @ Value::Unit, secp_value]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let syscall_result = match secp_type { SecpPointType::K1 => { let secp_value = Secp256k1Point::from_value(secp_value); syscall_handler .secp256k1_get_xy(secp_value, &mut gas) .map(|res| (res.0, res.1)) } SecpPointType::R1 => { let secp_value = Secp256r1Point::from_value(secp_value); syscall_handler .secp256r1_get_xy(secp_value, &mut gas) .map(|res| (res.0, res.1)) } }; match syscall_result { Ok(payload) => { let (x, y) = (payload.0.into_value(), payload.1.into_value()); EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, x, y]) } Err(payload) => { let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let payload = payload.into_iter().map(Value::Felt).collect::<Vec<_>>(); EvalAction::NormalBranch( 0, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: payload } ], ) } } } fn eval_class_hash_const( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndConstConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Felt(info.c.clone().into())]) } fn eval_storage_base_address_const( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndConstConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Felt(info.c.clone().into())]) } fn eval_contract_address_const( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndConstConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Felt(info.c.clone().into())]) } fn eval_class_hash_try_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { // 2 ** 251 = 3618502788666131106986593281521497120414687020801267626233049500247285301248 let [range_check @ Value::Unit, Value::Felt(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; if value < Felt::from_dec_str( "3618502788666131106986593281521497120414687020801267626233049500247285301248", ) .unwrap() { EvalAction::NormalBranch(0, smallvec![range_check, Value::Felt(value)]) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } fn eval_contract_address_try_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { // 2 ** 251 = 3618502788666131106986593281521497120414687020801267626233049500247285301248 let [range_check @ Value::Unit, Value::Felt(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; if value < Felt::from_dec_str( "3618502788666131106986593281521497120414687020801267626233049500247285301248", ) .unwrap() { EvalAction::NormalBranch(0, smallvec![range_check, Value::Felt(value)]) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } fn eval_storage_address_try_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { // 2 ** 251 = 3618502788666131106986593281521497120414687020801267626233049500247285301248 let [range_check @ Value::Unit, Value::Felt(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; if value < Felt::from_dec_str( "3618502788666131106986593281521497120414687020801267626233049500247285301248", ) .unwrap() { EvalAction::NormalBranch(0, smallvec![range_check, Value::Felt(value)]) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } fn eval_storage_base_address_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check, value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![range_check, value]) } fn eval_storage_address_to_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } fn eval_contract_address_to_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } fn eval_class_hash_to_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } fn eval_storage_address_from_base( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } fn eval_storage_address_from_base_and_offset( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Felt(value), Value::U8(offset)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch(0, smallvec![Value::Felt(value + Felt::from(offset))]) } fn eval_call_contract( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::Felt(address), Value::Felt(entry_point_selector), Value::Struct(calldata)]: [Value; 5] = args.try_into().unwrap() else { panic!() }; let [Value::Array { ty: _, data: calldata, }]: [Value; 1] = calldata.try_into().unwrap() else { panic!() }; let calldata = calldata .into_iter() .map(|x| match x { Value::Felt(x) => x, _ => unreachable!(), }) .collect(); // get felt type from the error branch array let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.call_contract(address, entry_point_selector, calldata, &mut gas); match result { Ok(return_values) => EvalAction::NormalBranch( 0, smallvec![ Value::U64(gas), system, Value::Struct(vec![Value::Array { ty: felt_ty, data: return_values .into_iter() .map(Value::Felt) .collect::<Vec<_>>(), }]) ], ), Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_storage_read( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::U32(address_domain), Value::Felt(storage_key)]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let error_felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.storage_read(address_domain, storage_key, &mut gas); match result { Ok(value) => { EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, Value::Felt(value)]) } Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: error_felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_storage_write( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::U32(address_domain), Value::Felt(storage_key), Value::Felt(value)]: [Value; 5] = args.try_into().unwrap() else { panic!() }; let error_felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.storage_write(address_domain, storage_key, value, &mut gas); match result { Ok(_) => EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system]), Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: error_felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_emit_event( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::Struct(key_arr), Value::Struct(data_arr)]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let [Value::Array { ty: _, data: keys }]: [Value; 1] = key_arr.try_into().unwrap() else { panic!() }; let [Value::Array { ty: _, data }]: [Value; 1] = data_arr.try_into().unwrap() else { panic!() }; let error_felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let keys = keys .into_iter() .map(|x| match x { Value::Felt(x) => x, _ => unreachable!(), }) .collect(); let data = data .into_iter() .map(|x| match x { Value::Felt(x) => x, _ => unreachable!(), }) .collect(); let result = syscall_handler.emit_event(keys, data, &mut gas); match result { Ok(_) => EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system]), Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: error_felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_get_block_hash( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::U64(block_number)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let error_felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.get_block_hash(block_number, &mut gas); match result { Ok(res) => { EvalAction::NormalBranch(0, smallvec![Value::U64(gas), system, Value::Felt(res)]) } Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: error_felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_get_execution_info( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system]: [Value; 2] = args.try_into().unwrap() else { panic!() }; // get felt type from the error branch array let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.get_execution_info(&mut gas); match result { Ok(res) => EvalAction::NormalBranch( 0, smallvec![Value::U64(gas), system, res.into_value(felt_ty)], ), Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_get_execution_info_v2( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system]: [Value; 2] = args.try_into().unwrap() else { panic!() }; // get felt type from the error branch array let felt_ty = { match registry .get_type(&info.branch_signatures()[1].vars[2].ty) .unwrap() { CoreTypeConcrete::Array(info) => info.ty.clone(), _ => unreachable!(), } }; let result = syscall_handler.get_execution_info_v2(&mut gas); let mut out_ty = registry .get_type(&info.branch_signatures()[0].vars[2].ty) .unwrap(); let mut out_ty_id = &info.branch_signatures()[0].vars[2].ty; if let CoreTypeConcrete::Box(inner) = out_ty { out_ty_id = &inner.ty; out_ty = registry.get_type(&inner.ty).unwrap(); }; if let CoreTypeConcrete::Struct(inner) = out_ty { out_ty_id = &inner.members[1]; out_ty = registry.get_type(&inner.members[1]).unwrap(); }; if let CoreTypeConcrete::Box(inner) = out_ty { out_ty_id = &inner.ty; out_ty = registry.get_type(&inner.ty).unwrap(); }; if let CoreTypeConcrete::Struct(inner) = out_ty { out_ty_id = &inner.members[7]; out_ty = registry.get_type(&inner.members[7]).unwrap(); }; if let CoreTypeConcrete::Struct(inner) = out_ty { out_ty_id = &inner.members[0]; out_ty = registry.get_type(&inner.members[0]).unwrap(); }; if let CoreTypeConcrete::Snapshot(inner) = out_ty { out_ty_id = &inner.ty; out_ty = registry.get_type(&inner.ty).unwrap(); }; if let CoreTypeConcrete::Array(inner) = out_ty { out_ty_id = &inner.ty; }; match result { Ok(res) => EvalAction::NormalBranch( 0, smallvec![ Value::U64(gas), system, res.into_value(felt_ty, out_ty_id.clone()) ], ), Err(e) => EvalAction::NormalBranch( 1, smallvec![ Value::U64(gas), system, Value::Array { ty: felt_ty, data: e.into_iter().map(Value::Felt).collect::<Vec<_>>(), } ], ), } } fn eval_deploy( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, syscall_handler: &mut impl StarknetSyscallHandler, ) -> EvalAction { let [Value::U64(mut gas), system, Value::Felt(class_hash), Value::Felt(contract_address_salt), Value::Struct(calldata), Value::Enum { self_ty: _, index: deploy_from_zero, payload: _, }]: [Value; 6] = args.try_into().unwrap() else { panic!() }; let deploy_from_zero = deploy_from_zero != 0;
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
true
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/drop.rs
debug_utils/sierra-emu/src/vm/drop.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [_value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/gas.rs
debug_utils/sierra-emu/src/vm/gas.rs
use super::EvalAction; use crate::{ gas::{BuiltinCosts, GasMetadata}, Value, }; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, gas::{CostTokenType, GasConcreteLibfunc}, lib_func::SignatureOnlyConcreteLibfunc, }, program::StatementIdx, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &GasConcreteLibfunc, args: Vec<Value>, gas: &GasMetadata, statement_idx: StatementIdx, builtin_costs: BuiltinCosts, ) -> EvalAction { match selector { GasConcreteLibfunc::WithdrawGas(info) => { eval_withdraw_gas(registry, info, args, gas, statement_idx, builtin_costs) } GasConcreteLibfunc::RedepositGas(info) => { eval_redeposit_gas(registry, info, args, gas, statement_idx, builtin_costs) } GasConcreteLibfunc::GetAvailableGas(info) => eval_get_available_gas(registry, info, args), GasConcreteLibfunc::BuiltinWithdrawGas(info) => { eval_builtin_withdraw_gas(registry, info, args, gas, statement_idx) } GasConcreteLibfunc::GetBuiltinCosts(info) => { eval_get_builtin_costs(registry, info, args, builtin_costs) } GasConcreteLibfunc::GetUnspentGas(_) => todo!(), } } fn eval_builtin_withdraw_gas( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, gas_meta: &GasMetadata, statement_idx: StatementIdx, ) -> EvalAction { let [range_check @ Value::Unit, Value::U64(gas), Value::BuiltinCosts(builtin_costs)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let builtin_costs: [u64; 7] = builtin_costs.into(); let gas_cost = gas_meta.get_gas_costs_for_statement(statement_idx); let mut total_gas_cost = 0; for (cost_count, token_type) in &gas_cost { if *cost_count == 0 { continue; } let builtin_costs_index = match token_type { CostTokenType::Const => 0, CostTokenType::Pedersen => 1, CostTokenType::Bitwise => 2, CostTokenType::EcOp => 3, CostTokenType::Poseidon => 4, CostTokenType::AddMod => 5, CostTokenType::MulMod => 6, _ => panic!(), }; let cost_value = cost_count * builtin_costs[builtin_costs_index as usize]; total_gas_cost += cost_value; } let new_gas = gas.saturating_sub(total_gas_cost); if gas >= total_gas_cost { EvalAction::NormalBranch(0, smallvec![range_check, Value::U64(new_gas)]) } else { EvalAction::NormalBranch(1, smallvec![range_check, Value::U64(gas)]) } } fn eval_withdraw_gas( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, gas_meta: &GasMetadata, statement_idx: StatementIdx, builtin_costs: BuiltinCosts, ) -> EvalAction { let [range_check @ Value::Unit, Value::U64(gas)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let builtin_costs: [u64; 7] = builtin_costs.into(); let gas_cost = gas_meta.get_gas_costs_for_statement(statement_idx); let mut total_gas_cost = 0; for (cost_count, token_type) in &gas_cost { if *cost_count == 0 { continue; } let builtin_costs_index = match token_type { CostTokenType::Const => 0, CostTokenType::Pedersen => 1, CostTokenType::Bitwise => 2, CostTokenType::EcOp => 3, CostTokenType::Poseidon => 4, CostTokenType::AddMod => 5, CostTokenType::MulMod => 6, _ => panic!(), }; let cost_value = cost_count * builtin_costs[builtin_costs_index as usize]; total_gas_cost += cost_value; } let new_gas = gas.saturating_sub(total_gas_cost); if gas >= total_gas_cost { EvalAction::NormalBranch(0, smallvec![range_check, Value::U64(new_gas)]) } else { EvalAction::NormalBranch(1, smallvec![range_check, Value::U64(gas)]) } } fn eval_redeposit_gas( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, gas_meta: &GasMetadata, statement_idx: StatementIdx, builtin_costs: BuiltinCosts, ) -> EvalAction { let [Value::U64(gas)]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let builtin_costs: [u64; 7] = builtin_costs.into(); let gas_cost = gas_meta.get_gas_costs_for_statement(statement_idx); let mut total_gas_cost = 0; for (cost_count, token_type) in &gas_cost { if *cost_count == 0 { continue; } let builtin_costs_index = match token_type { CostTokenType::Const => 0, CostTokenType::Pedersen => 1, CostTokenType::Bitwise => 2, CostTokenType::EcOp => 3, CostTokenType::Poseidon => 4, CostTokenType::AddMod => 5, CostTokenType::MulMod => 6, _ => panic!(), }; let cost_value = cost_count * builtin_costs[builtin_costs_index as usize]; total_gas_cost += cost_value; } let new_gas = gas.saturating_add(total_gas_cost); EvalAction::NormalBranch(0, smallvec![Value::U64(new_gas)]) } fn eval_get_available_gas( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [gas_val @ Value::U64(gas)]: [Value; 1] = args.try_into().unwrap() else { panic!(); }; EvalAction::NormalBranch(0, smallvec![gas_val, Value::U128(gas as u128)]) } fn eval_get_builtin_costs( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, _args: Vec<Value>, builtin_costs: BuiltinCosts, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::BuiltinCosts(builtin_costs)]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/mem.rs
debug_utils/sierra-emu/src/vm/mem.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::{SignatureAndTypeConcreteLibfunc, SignatureOnlyConcreteLibfunc}, mem::MemConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &MemConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { MemConcreteLibfunc::StoreTemp(info) => eval_store_temp(registry, info, args), MemConcreteLibfunc::StoreLocal(info) => eval_store_local(registry, info, args), MemConcreteLibfunc::FinalizeLocals(info) => eval_finalize_locals(registry, info, args), MemConcreteLibfunc::AllocLocal(info) => eval_alloc_local(registry, info, args), MemConcreteLibfunc::Rename(info) => eval_rename(registry, info, args), } } pub fn eval_store_temp( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) } pub fn eval_store_local( registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Uninitialized { ty }, value]: [Value; 2] = args.try_into().unwrap() else { panic!() }; assert!(value.is(registry, &ty)); EvalAction::NormalBranch(0, smallvec![value]) } pub fn eval_finalize_locals( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) } pub fn eval_alloc_local( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndTypeConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch( 0, smallvec![Value::Uninitialized { ty: info.ty.clone() }], ) } pub fn eval_rename( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![value]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/uint256.rs
debug_utils/sierra-emu/src/vm/uint256.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, int::unsigned256::Uint256Concrete, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_bigint::BigUint; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Uint256Concrete, args: Vec<Value>, ) -> EvalAction { match selector { Uint256Concrete::IsZero(info) => eval_is_zero(registry, info, args), Uint256Concrete::Divmod(info) => eval_divmod(registry, info, args), Uint256Concrete::SquareRoot(info) => eval_square_root(registry, info, args), Uint256Concrete::InvModN(info) => eval_inv_mod_n(registry, info, args), } } fn eval_inv_mod_n( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Struct(x), Value::Struct(modulo)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let [Value::U128(x_lo), Value::U128(x_hi)]: [Value; 2] = x.clone().try_into().unwrap() else { panic!() }; let [Value::U128(mod_lo), Value::U128(mod_hi)]: [Value; 2] = modulo.clone().try_into().unwrap() else { panic!() }; let x = u256_to_biguint(x_lo, x_hi); let modulo = u256_to_biguint(mod_lo, mod_hi); match x.modinv(&modulo) { None => EvalAction::NormalBranch(1, smallvec![range_check, Value::Unit, Value::Unit]), Some(r) if r == 0u8.into() => { EvalAction::NormalBranch(1, smallvec![range_check, Value::Unit, Value::Unit]) } Some(r) => EvalAction::NormalBranch( 0, smallvec![ range_check, u256_to_value(r), Value::Unit, Value::Unit, Value::Unit, Value::Unit, Value::Unit, Value::Unit, Value::Unit, Value::Unit ], ), } } pub fn eval_is_zero( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Struct(fields)]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let [Value::U128(lo), Value::U128(hi)]: [Value; 2] = fields.clone().try_into().unwrap() else { panic!() }; if lo == 0 && hi == 0 { EvalAction::NormalBranch(0, smallvec![]) } else { EvalAction::NormalBranch(1, smallvec![Value::Struct(fields)]) } } #[inline] pub fn u256_to_biguint(lo: u128, hi: u128) -> BigUint { BigUint::from(lo) + (BigUint::from(hi) << 128) } #[inline] pub fn u256_to_value(value: BigUint) -> Value { let hi: u128 = (&value >> 128u32).try_into().unwrap(); let lo: u128 = (value & BigUint::from(u128::MAX)).try_into().unwrap(); Value::Struct(vec![Value::U128(lo), Value::U128(hi)]) } #[inline] pub fn u516_to_value(value: BigUint) -> Value { let upper_u256: BigUint = &value >> 256u32; let hi1: u128 = (&upper_u256 >> 128u32).try_into().unwrap(); let lo1: u128 = (upper_u256 & BigUint::from(u128::MAX)).try_into().unwrap(); let lower_mask = BigUint::from_bytes_le(&[0xFF; 32]); let lower_u256: BigUint = value & lower_mask; let hi: u128 = (&lower_u256 >> 128u32).try_into().unwrap(); let lo: u128 = (lower_u256 & BigUint::from(u128::MAX)).try_into().unwrap(); Value::Struct(vec![ Value::U128(lo), Value::U128(hi), Value::U128(lo1), Value::U128(hi1), ]) } pub fn eval_divmod( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Struct(lhs), Value::Struct(rhs)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let [Value::U128(lhs_lo), Value::U128(lhs_hi)]: [Value; 2] = lhs.try_into().unwrap() else { panic!() }; let lhs = u256_to_biguint(lhs_lo, lhs_hi); let [Value::U128(rhs_lo), Value::U128(rhs_hi)]: [Value; 2] = rhs.try_into().unwrap() else { panic!() }; let rhs = u256_to_biguint(rhs_lo, rhs_hi); let div = &lhs / &rhs; let modulo = lhs % rhs; EvalAction::NormalBranch( 0, smallvec![ range_check, u256_to_value(div), u256_to_value(modulo), Value::Unit ], ) } pub fn eval_square_root( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Struct(lhs)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let [Value::U128(lhs_lo), Value::U128(lhs_hi)]: [Value; 2] = lhs.try_into().unwrap() else { panic!() }; let lhs = u256_to_biguint(lhs_lo, lhs_hi); let sqrt = lhs.sqrt(); let sqrt_lo: u128 = sqrt.clone().try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![range_check, Value::U128(sqrt_lo)]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/cast.rs
debug_utils/sierra-emu/src/vm/cast.rs
use super::EvalAction; use crate::{ utils::{get_numeric_args_as_bigints, get_value_from_integer}, Value, }; use cairo_lang_sierra::{ extensions::{ casts::{CastConcreteLibfunc, DowncastConcreteLibfunc}, core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, ConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &CastConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { CastConcreteLibfunc::Downcast(info) => eval_downcast(registry, info, args), CastConcreteLibfunc::Upcast(info) => eval_upcast(registry, info, args), } } fn eval_downcast( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &DowncastConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [value] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let range = info.to_range.lower.clone()..info.to_range.upper.clone(); if range.contains(&value) { EvalAction::NormalBranch( 0, smallvec![ range_check, get_value_from_integer(registry, &info.to_ty, value) ], ) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } fn eval_upcast( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let int_ty_id = &info.branch_signatures()[0].vars[0].ty; EvalAction::NormalBranch( 0, smallvec![get_value_from_integer(registry, int_ty_id, value)], ) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/felt252.rs
debug_utils/sierra-emu/src/vm/felt252.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, felt252::{ Felt252BinaryOperationConcrete, Felt252BinaryOperator, Felt252Concrete, Felt252ConstConcreteLibfunc, }, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; use starknet_crypto::Felt; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Felt252Concrete, args: Vec<Value>, ) -> EvalAction { match selector { Felt252Concrete::BinaryOperation(info) => eval_operation(registry, info, args), Felt252Concrete::Const(info) => eval_const(registry, info, args), Felt252Concrete::IsZero(info) => eval_felt_is_zero(registry, info, args), } } pub fn eval_operation( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &Felt252BinaryOperationConcrete, args: Vec<Value>, ) -> EvalAction { let res = match info { Felt252BinaryOperationConcrete::WithVar(info) => { let [Value::Felt(lhs), Value::Felt(rhs)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; match info.operator { Felt252BinaryOperator::Add => lhs + rhs, Felt252BinaryOperator::Sub => lhs - rhs, Felt252BinaryOperator::Mul => lhs * rhs, Felt252BinaryOperator::Div => lhs.field_div(&rhs.try_into().unwrap()), } } Felt252BinaryOperationConcrete::WithConst(_info) => todo!(), }; EvalAction::NormalBranch(0, smallvec![Value::Felt(res)]) } pub fn eval_const( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &Felt252ConstConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Felt(info.c.clone().into())]) } pub fn eval_felt_is_zero( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Felt(value)]: [Value; 1] = args.try_into().unwrap() else { panic!() }; if value == Felt::ZERO { EvalAction::NormalBranch(0, smallvec![]) } else { EvalAction::NormalBranch(1, smallvec![Value::Felt(value)]) } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/const.rs
debug_utils/sierra-emu/src/vm/const.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ const_type::{ ConstAsBoxConcreteLibfunc, ConstAsImmediateConcreteLibfunc, ConstConcreteLibfunc, }, core::{CoreLibfunc, CoreType, CoreTypeConcrete}, starknet::StarknetTypeConcrete, }, ids::ConcreteTypeId, program::GenericArg, program_registry::ProgramRegistry, }; use num_traits::ToPrimitive; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &ConstConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { ConstConcreteLibfunc::AsBox(info) => eval_as_box(registry, info, args), ConstConcreteLibfunc::AsImmediate(info) => eval_as_immediate(registry, info, args), } } fn eval_as_immediate( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &ConstAsImmediateConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); let const_ty = match registry.get_type(&info.const_type).unwrap() { CoreTypeConcrete::Const(x) => x, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![inner(registry, &const_ty.inner_ty, &const_ty.inner_data)], ) } fn eval_as_box( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &ConstAsBoxConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); let const_ty = match registry.get_type(&info.const_type).unwrap() { CoreTypeConcrete::Const(x) => x, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![inner(registry, &const_ty.inner_ty, &const_ty.inner_data)], ) } fn inner( registry: &ProgramRegistry<CoreType, CoreLibfunc>, type_id: &ConcreteTypeId, inner_data: &[GenericArg], ) -> Value { match registry.get_type(type_id).unwrap() { CoreTypeConcrete::BoundedInt(info) => match inner_data { [GenericArg::Type(type_id)] => match registry.get_type(type_id).unwrap() { CoreTypeConcrete::Const(info) => inner(registry, &info.inner_ty, &info.inner_data), _ => unreachable!(), }, [GenericArg::Value(value)] => { assert!(value >= &info.range.lower && value < &info.range.upper); Value::BoundedInt { range: info.range.lower.clone()..info.range.upper.clone(), value: value.clone(), } } _ => unreachable!(), }, CoreTypeConcrete::Felt252(_) => match inner_data { [GenericArg::Value(value)] => Value::Felt(value.into()), _ => unreachable!(), }, CoreTypeConcrete::NonZero(_) => match inner_data { [GenericArg::Type(type_id)] => match registry.get_type(type_id).unwrap() { CoreTypeConcrete::Const(info) => inner(registry, &info.inner_ty, &info.inner_data), _ => unreachable!(), }, _ => unreachable!(), }, CoreTypeConcrete::Bytes31(_) => match inner_data { [GenericArg::Value(value)] => Value::Bytes31(value.into()), _ => unreachable!(), }, CoreTypeConcrete::Sint128(_) => match inner_data { [GenericArg::Value(value)] => Value::I128(value.to_i128().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Sint64(_) => match inner_data { [GenericArg::Value(value)] => Value::I64(value.to_i64().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Sint32(_) => match inner_data { [GenericArg::Value(value)] => Value::I32(value.to_i32().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Sint16(_) => match inner_data { [GenericArg::Value(value)] => Value::I16(value.to_i16().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Sint8(_) => match inner_data { [GenericArg::Value(value)] => Value::I8(value.to_i8().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Uint128(_) => match inner_data { [GenericArg::Value(value)] => Value::U128(value.to_u128().unwrap()), [GenericArg::Type(type_id)] => match registry.get_type(type_id).unwrap() { CoreTypeConcrete::Const(info) => inner(registry, &info.inner_ty, &info.inner_data), _ => unreachable!(), }, _ => unreachable!(), }, CoreTypeConcrete::Uint64(_) => match inner_data { [GenericArg::Value(value)] => Value::U64(value.to_u64().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Uint32(_) => match inner_data { [GenericArg::Value(value)] => Value::U32(value.to_u32().unwrap()), [GenericArg::Type(type_id)] => match registry.get_type(type_id).unwrap() { CoreTypeConcrete::Const(info) => inner(registry, &info.inner_ty, &info.inner_data), _ => unreachable!(), }, _ => unreachable!(), }, CoreTypeConcrete::Uint16(_) => match inner_data { [GenericArg::Value(value)] => Value::U16(value.to_u16().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Uint8(_) => match inner_data { [GenericArg::Value(value)] => Value::U8(value.to_u8().unwrap()), _ => unreachable!(), }, CoreTypeConcrete::Struct(_) => { let mut fields = Vec::new(); for field in inner_data { match field { GenericArg::Type(const_field_ty) => { let field_type = registry.get_type(const_field_ty).unwrap(); match &field_type { CoreTypeConcrete::Const(const_ty) => { let field_value = inner(registry, &const_ty.inner_ty, &const_ty.inner_data); fields.push(field_value); } _ => unreachable!(), }; } _ => unreachable!(), } } Value::Struct(fields) } CoreTypeConcrete::Enum(_) => match inner_data { [GenericArg::Value(value_idx), GenericArg::Type(payload_ty)] => { let payload_type = registry.get_type(payload_ty).unwrap(); let const_payload_type = match payload_type { CoreTypeConcrete::Const(inner) => inner, _ => { panic!("matched an unexpected CoreTypeConcrete that is not a Const") } }; let payload = inner(registry, payload_ty, &const_payload_type.inner_data); let index: usize = value_idx.to_usize().unwrap(); Value::Enum { self_ty: type_id.clone(), index, payload: Box::new(payload), } } _ => panic!("const data mismatch"), }, CoreTypeConcrete::Const(info) => inner(registry, &info.inner_ty, &info.inner_data), CoreTypeConcrete::Starknet(selector) => match selector { StarknetTypeConcrete::ClassHash(_) | StarknetTypeConcrete::ContractAddress(_) | StarknetTypeConcrete::StorageAddress(_) | StarknetTypeConcrete::StorageBaseAddress(_) => match inner_data { [GenericArg::Value(value)] => Value::Felt(value.into()), _ => unreachable!(), }, _ => todo!(""), }, _ => todo!("{}", type_id), } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/ec.rs
debug_utils/sierra-emu/src/vm/ec.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, ec::EcConcreteLibfunc, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_traits::identities::Zero; use rand::Rng; use smallvec::smallvec; use starknet_crypto::Felt; use starknet_curve::curve_params::BETA; use starknet_types_core::curve::{AffinePoint, ProjectivePoint}; use std::ops::Mul; use std::ops::Neg; // todo: verify these are correct. pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &EcConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { EcConcreteLibfunc::IsZero(info) => eval_is_zero(registry, info, args), EcConcreteLibfunc::Neg(info) => eval_neg(registry, info, args), EcConcreteLibfunc::StateAdd(info) => eval_state_add(registry, info, args), EcConcreteLibfunc::TryNew(info) => eval_new(registry, info, args), EcConcreteLibfunc::StateFinalize(info) => eval_state_finalize(registry, info, args), EcConcreteLibfunc::StateInit(info) => eval_state_init(registry, info, args), EcConcreteLibfunc::StateAddMul(info) => eval_state_add_mul(registry, info, args), EcConcreteLibfunc::PointFromX(info) => eval_point_from_x(registry, info, args), EcConcreteLibfunc::UnwrapPoint(info) => eval_unwrap_point(registry, info, args), EcConcreteLibfunc::Zero(info) => eval_zero(registry, info, args), EcConcreteLibfunc::NegNz(_) => todo!(), } } fn eval_is_zero( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value @ Value::EcPoint { x: _, y }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; // To check whether `(x, y) = (0, 0)` (the zero point), it is enough to check // whether `y = 0`, since there is no point on the curve with y = 0. if y.is_zero() { EvalAction::NormalBranch(0, smallvec![]) } else { EvalAction::NormalBranch(1, smallvec![value]) } } fn eval_unwrap_point( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::EcPoint { x, y }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch(0, smallvec![Value::Felt(x), Value::Felt(y)]) } fn eval_neg( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::EcPoint { x, y }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let point = AffinePoint::new(x, y).unwrap().neg(); EvalAction::NormalBranch( 0, smallvec![Value::EcPoint { x: point.x(), y: point.y(), }], ) } fn eval_new( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Felt(x), Value::Felt(y)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; match AffinePoint::new(x, y) { Ok(point) => EvalAction::NormalBranch( 0, smallvec![Value::EcPoint { x: point.x(), y: point.y(), }], ), Err(_) => EvalAction::NormalBranch(1, smallvec![]), } } fn eval_state_init( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { let state = random_ec_point(); EvalAction::NormalBranch( 0, smallvec![Value::EcState { x0: state.x(), y0: state.y(), x1: state.x(), y1: state.y(), }], ) } fn eval_state_add( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::EcState { x0, y0, x1, y1 }, Value::EcPoint { x, y }]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let mut state = ProjectivePoint::from_affine(x0, y0).unwrap(); let point = AffinePoint::new(x, y).unwrap(); state += &point; let state = state.to_affine().unwrap(); EvalAction::NormalBranch( 0, smallvec![Value::EcState { x0: state.x(), y0: state.y(), x1, y1 }], ) } fn eval_state_add_mul( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [ec @ Value::Unit, Value::EcState { x0, y0, x1, y1 }, Value::Felt(scalar), Value::EcPoint { x, y }]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let mut state = ProjectivePoint::from_affine(x0, y0).unwrap(); let point = ProjectivePoint::from_affine(x, y).unwrap(); state += &point.mul(scalar); let state = state.to_affine().unwrap(); EvalAction::NormalBranch( 0, smallvec![ ec, Value::EcState { x0: state.x(), y0: state.y(), x1, y1 } ], ) } fn eval_state_finalize( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::EcState { x0, y0, x1, y1 }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let state = ProjectivePoint::from_affine(x0, y0).unwrap(); let random_point = ProjectivePoint::from_affine(x1, y1).unwrap(); if state.x() == random_point.x() && state.y() == random_point.y() { EvalAction::NormalBranch(1, smallvec![]) } else { let point = &state - &random_point; let point = point.to_affine().unwrap(); EvalAction::NormalBranch( 0, smallvec![Value::EcPoint { x: point.x(), y: point.y(), }], ) } } fn eval_point_from_x( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Felt(x)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; // https://github.com/starkware-libs/cairo/blob/aaad921bba52e729dc24ece07fab2edf09ccfa15/crates/cairo-lang-sierra-to-casm/src/invocations/ec.rs#L63 let x2 = x * x; let x3 = x2 * x; let alpha_x_plus_beta = x + BETA; let rhs = x3 + alpha_x_plus_beta; let y = rhs.sqrt().unwrap_or_else(|| Felt::from(3) * rhs); match AffinePoint::new(x, y) { Ok(point) => EvalAction::NormalBranch( 0, smallvec![ range_check, Value::EcPoint { x: point.x(), y: point.y(), } ], ), Err(_) => EvalAction::NormalBranch(1, smallvec![range_check]), } } fn random_ec_point() -> AffinePoint { // https://github.com/starkware-libs/cairo/blob/aaad921bba52e729dc24ece07fab2edf09ccfa15/crates/cairo-lang-runner/src/casm_run/mod.rs#L1802 let mut rng = rand::rng(); let (random_x, random_y) = loop { // Randominzing 31 bytes to make sure is in range. let x_bytes: [u8; 31] = rng.random(); let random_x = Felt::from_bytes_be_slice(&x_bytes); let random_y_squared = random_x * random_x * random_x + random_x + BETA; if let Some(random_y) = random_y_squared.sqrt() { break (random_x, random_y); } }; AffinePoint::new(random_x, random_y).unwrap() } fn eval_zero( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch( 0, smallvec![Value::EcPoint { x: 0.into(), y: 0.into() }], ) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/bytes31.rs
debug_utils/sierra-emu/src/vm/bytes31.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ bytes31::Bytes31ConcreteLibfunc, consts::SignatureAndConstConcreteLibfunc, core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use num_bigint::BigInt; use smallvec::smallvec; use starknet_crypto::Felt; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Bytes31ConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { Bytes31ConcreteLibfunc::Const(info) => eval_const(registry, info, args), Bytes31ConcreteLibfunc::ToFelt252(info) => eval_to_felt252(registry, info, args), Bytes31ConcreteLibfunc::TryFromFelt252(info) => eval_from_felt(registry, info, args), } } pub fn eval_const( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndConstConcreteLibfunc, _args: Vec<Value>, ) -> EvalAction { EvalAction::NormalBranch(0, smallvec![Value::Bytes31(info.c.clone().into())]) } pub fn eval_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Felt(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let max = Felt::from(BigInt::from(2).pow(248) - 1); if value <= max { EvalAction::NormalBranch(0, smallvec![range_check, Value::Bytes31(value)]) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } pub fn eval_to_felt252( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Bytes31(value)]: [Value; 1] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch(0, smallvec![Value::Felt(value)]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/function_call.rs
debug_utils/sierra-emu/src/vm/function_call.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, function_call::SignatureAndFunctionConcreteLibfunc, }, program_registry::ProgramRegistry, }; pub fn eval_function_call( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndFunctionConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { assert_eq!(args.len(), info.function.params.len()); assert!(args .iter() .zip(&info.function.params) .all(|(value, param)| value.is(registry, &param.ty))); EvalAction::FunctionCall(info.function.id.clone(), args.into_iter().collect()) } pub fn eval_coupon_call( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureAndFunctionConcreteLibfunc, mut args: Vec<Value>, ) -> EvalAction { // Don't check the last arg since it is not actually an argument for the function call itself assert_eq!(args.len() - 1, info.function.params.len()); assert!(args .iter() .zip(&info.function.params) .all(|(value, param)| value.is(registry, &param.ty))); args.pop(); EvalAction::FunctionCall(info.function.id.clone(), args.into_iter().collect()) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/int.rs
debug_utils/sierra-emu/src/vm/int.rs
use std::fmt::Debug; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType, CoreTypeConcrete}, int::{ signed::{SintConcrete, SintTraits}, signed128::Sint128Concrete, unsigned::{UintConcrete, UintTraits}, unsigned128::Uint128Concrete, IntConstConcreteLibfunc, IntMulTraits, IntOperationConcreteLibfunc, IntOperator, IntTraits, }, is_zero::IsZeroTraits, lib_func::SignatureOnlyConcreteLibfunc, ConcreteLibfunc, }, ids::ConcreteTypeId, program_registry::ProgramRegistry, }; use num_bigint::{BigInt, BigUint, ToBigInt}; use num_traits::ops::overflowing::{OverflowingAdd, OverflowingSub}; use smallvec::smallvec; use starknet_crypto::Felt; use starknet_types_core::felt::NonZeroFelt; use crate::{ utils::{get_numeric_args_as_bigints, get_value_from_integer, integer_range}, Value, }; use super::EvalAction; fn apply_overflowing_op_for_type( registry: &ProgramRegistry<CoreType, CoreLibfunc>, ty: &ConcreteTypeId, lhs: BigInt, rhs: BigInt, op: IntOperator, ) -> (BigInt, bool) { fn overflowing_op<T>(lhs: BigInt, rhs: BigInt, op: IntOperator) -> (BigInt, bool) where T: OverflowingAdd + OverflowingSub + Into<BigInt> + TryFrom<BigInt>, <T as TryFrom<BigInt>>::Error: Debug, { let lhs: T = lhs.try_into().unwrap(); let rhs: T = rhs.try_into().unwrap(); let (result, had_overflow) = match op { IntOperator::OverflowingAdd => OverflowingAdd::overflowing_add(&lhs, &rhs), IntOperator::OverflowingSub => OverflowingSub::overflowing_sub(&lhs, &rhs), }; (result.into(), had_overflow) } let ty = registry.get_type(ty).unwrap(); match ty { CoreTypeConcrete::Sint8(_) => overflowing_op::<i8>(lhs, rhs, op), CoreTypeConcrete::Sint16(_) => overflowing_op::<i16>(lhs, rhs, op), CoreTypeConcrete::Sint32(_) => overflowing_op::<i32>(lhs, rhs, op), CoreTypeConcrete::Sint64(_) => overflowing_op::<i64>(lhs, rhs, op), CoreTypeConcrete::Sint128(_) => overflowing_op::<i128>(lhs, rhs, op), CoreTypeConcrete::Uint8(_) => overflowing_op::<u8>(lhs, rhs, op), CoreTypeConcrete::Uint16(_) => overflowing_op::<u16>(lhs, rhs, op), CoreTypeConcrete::Uint32(_) => overflowing_op::<u32>(lhs, rhs, op), CoreTypeConcrete::Uint64(_) => overflowing_op::<u64>(lhs, rhs, op), CoreTypeConcrete::Uint128(_) => overflowing_op::<u128>(lhs, rhs, op), _ => panic!("cannot apply integer operation to non-integer type"), } } pub fn eval_signed<T>( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &SintConcrete<T>, args: Vec<Value>, ) -> EvalAction where T: IntMulTraits + SintTraits, { match selector { SintConcrete::Const(info) => eval_const(registry, info, args), SintConcrete::Diff(info) => eval_diff(registry, info, args), SintConcrete::Equal(info) => eval_equal(registry, info, args), SintConcrete::FromFelt252(info) => eval_from_felt(registry, info, args), SintConcrete::Operation(info) => eval_operation(registry, info, args), SintConcrete::ToFelt252(info) => eval_to_felt(registry, info, args), SintConcrete::WideMul(info) => eval_widemul(registry, info, args), } } pub fn eval_i128( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Sint128Concrete, args: Vec<Value>, ) -> EvalAction { match selector { Sint128Concrete::Const(info) => eval_const(registry, info, args), Sint128Concrete::Diff(info) => eval_diff(registry, info, args), Sint128Concrete::Equal(info) => eval_equal(registry, info, args), Sint128Concrete::FromFelt252(info) => eval_from_felt(registry, info, args), Sint128Concrete::Operation(info) => eval_operation(registry, info, args), Sint128Concrete::ToFelt252(info) => eval_to_felt(registry, info, args), } } pub fn eval_unsigned<T>( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &UintConcrete<T>, args: Vec<Value>, ) -> EvalAction where T: IntMulTraits + IsZeroTraits + UintTraits, { match selector { UintConcrete::Const(info) => eval_const(registry, info, args), UintConcrete::Bitwise(info) => eval_bitwise(registry, info, args), UintConcrete::Divmod(info) => eval_divmod(registry, info, args), UintConcrete::Equal(info) => eval_equal(registry, info, args), UintConcrete::FromFelt252(info) => eval_from_felt(registry, info, args), UintConcrete::Operation(info) => eval_operation(registry, info, args), UintConcrete::IsZero(info) => eval_is_zero(registry, info, args), UintConcrete::SquareRoot(info) => eval_square_root(registry, info, args), UintConcrete::ToFelt252(info) => eval_to_felt(registry, info, args), UintConcrete::WideMul(info) => eval_widemul(registry, info, args), } } pub fn eval_uint128( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Uint128Concrete, args: Vec<Value>, ) -> EvalAction { match selector { Uint128Concrete::Const(info) => eval_const(registry, info, args), Uint128Concrete::Operation(info) => eval_operation(registry, info, args), Uint128Concrete::SquareRoot(info) => eval_square_root(registry, info, args), Uint128Concrete::Equal(info) => eval_equal(registry, info, args), Uint128Concrete::ToFelt252(info) => eval_to_felt(registry, info, args), Uint128Concrete::FromFelt252(info) => eval_u128_from_felt(registry, info, args), Uint128Concrete::IsZero(info) => eval_is_zero(registry, info, args), Uint128Concrete::Divmod(info) => eval_divmod(registry, info, args), Uint128Concrete::Bitwise(info) => eval_bitwise(registry, info, args), Uint128Concrete::GuaranteeMul(info) => eval_guarantee_mul(registry, info, args), Uint128Concrete::MulGuaranteeVerify(info) => eval_guarantee_verify(registry, info, args), Uint128Concrete::ByteReverse(info) => eval_byte_reverse(registry, info, args), } } fn eval_const<T: IntTraits>( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &IntConstConcreteLibfunc<T>, _args: Vec<Value>, ) -> EvalAction { let int_ty = &info.signature.branch_signatures[0].vars[0].ty; EvalAction::NormalBranch( 0, smallvec![get_value_from_integer(registry, int_ty, info.c.into())], ) } fn eval_bitwise( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let bitwise @ Value::Unit: Value = args[0].clone() else { panic!() }; let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty = &info.signature.branch_signatures[0].vars[1].ty; let and = get_value_from_integer(registry, int_ty, &lhs & &rhs); let or = get_value_from_integer(registry, int_ty, &lhs | &rhs); let xor = get_value_from_integer(registry, int_ty, &lhs ^ &rhs); EvalAction::NormalBranch(0, smallvec![bitwise, and, xor, or]) } fn eval_diff( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty = &info.branch_signatures()[0].vars[1].ty; let res = lhs - rhs; // Since this libfunc returns an unsigned value, If lhs >= rhs then just // return Ok(lhs - rhs). Otherwise, we need to wrap around the value, returning // Err(2**n + lhs - rhs), where n is the amount of bits for that integer type. if res < BigInt::ZERO { let max_integer = integer_range(int_ty, registry).upper; EvalAction::NormalBranch( 1, smallvec![ range_check, get_value_from_integer(registry, int_ty, max_integer + res) ], ) } else { EvalAction::NormalBranch( 0, smallvec![range_check, get_value_from_integer(registry, int_ty, res)], ) } } fn eval_divmod( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty = &info.signature.branch_signatures[0].vars[1].ty; let res = &lhs / &rhs; let rem = lhs % rhs; let res = get_value_from_integer(registry, int_ty, res); let rem = get_value_from_integer(registry, int_ty, rem); EvalAction::NormalBranch(0, smallvec![range_check, res, rem]) } fn eval_equal( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [lhs, rhs] = args.try_into().unwrap(); EvalAction::NormalBranch((lhs == rhs) as usize, smallvec![]) } fn eval_from_felt( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Felt(value_felt)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let prime = Felt::prime(); let half_prime = &prime / BigUint::from(2u8); let int_ty = &info.signature.branch_signatures[0].vars[1].ty; let range = integer_range(int_ty, registry); let value = { let value_bigint = value_felt.to_biguint(); if value_bigint > half_prime { (prime - value_bigint).to_bigint().unwrap() * BigInt::from(-1) } else { value_felt.to_bigint() } }; if value >= range.lower && value < range.upper { let value = get_value_from_integer(registry, int_ty, value); EvalAction::NormalBranch(0, smallvec![range_check, value]) } else { EvalAction::NormalBranch(1, smallvec![range_check]) } } pub fn eval_u128_from_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Felt(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let bound = Felt::from(u128::MAX) + 1; if value < bound { let value: u128 = value.to_biguint().try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![range_check, Value::U128(value)]) } else { let (new_value, overflow) = value.div_rem(&NonZeroFelt::try_from(bound).unwrap()); let overflow: u128 = overflow.to_biguint().try_into().unwrap(); let new_value: u128 = new_value.to_biguint().try_into().unwrap(); EvalAction::NormalBranch( 1, smallvec![range_check, Value::U128(new_value), Value::U128(overflow)], ) } } fn eval_is_zero( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value]: [BigInt; 1] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let int_ty = &info.signature.branch_signatures[1].vars[0].ty; if value == 0.into() { EvalAction::NormalBranch(0, smallvec![]) } else { EvalAction::NormalBranch( 1, smallvec![get_value_from_integer(registry, int_ty, value)], ) } } fn eval_operation( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &IntOperationConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty = &info.signature.param_signatures[1].ty; let (res, had_overflow) = apply_overflowing_op_for_type(registry, int_ty, lhs, rhs, info.operator); let res = get_value_from_integer(registry, int_ty, res); EvalAction::NormalBranch(had_overflow as usize, smallvec![range_check, res]) } fn eval_square_root( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let range_check @ Value::Unit: Value = args[0].clone() else { panic!() }; let [value]: [BigInt; 1] = get_numeric_args_as_bigints(&args[1..]).try_into().unwrap(); let int_ty = &info.signature.branch_signatures[0].vars[1].ty; let res = value.sqrt(); EvalAction::NormalBranch( 0, smallvec![range_check, get_value_from_integer(registry, int_ty, res)], ) } fn eval_to_felt( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [val]: [BigInt; 1] = get_numeric_args_as_bigints(&args).try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![Value::Felt(Felt::from(val))]) } fn eval_widemul( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [lhs, rhs]: [BigInt; 2] = get_numeric_args_as_bigints(&args).try_into().unwrap(); let int_ty = &info.signature.branch_signatures[0].vars[0].ty; let res = lhs * rhs; EvalAction::NormalBranch(0, smallvec![get_value_from_integer(registry, int_ty, res)]) } fn eval_guarantee_mul( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::U128(lhs), Value::U128(rhs)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let mask128 = BigUint::from(u128::MAX); let result = BigUint::from(lhs) * BigUint::from(rhs); let high = Value::U128((&result >> 128u32).try_into().unwrap()); let low = Value::U128((result & mask128).try_into().unwrap()); EvalAction::NormalBranch(0, smallvec![high, low, Value::Unit]) } fn eval_guarantee_verify( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, _verify @ Value::Unit]: [Value; 2] = args.try_into().unwrap() else { panic!() }; EvalAction::NormalBranch(0, smallvec![range_check]) } fn eval_byte_reverse( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [bitwise @ Value::Unit, Value::U128(value)]: [Value; 2] = args.try_into().unwrap() else { panic!() }; let value = value.swap_bytes(); EvalAction::NormalBranch(0, smallvec![bitwise, Value::U128(value)]) } #[cfg(test)] mod test { use crate::{load_cairo, test_utils::run_test_program, Value}; #[test] fn test_diff_14_m2() { let (_, program) = load_cairo!( pub extern fn i8_diff(lhs: i8, rhs: i8) -> Result<u8, u8> implicits(RangeCheck) nopanic; fn main() -> Result<u8, u8> { i8_diff(14, -2) } ); let result = run_test_program(program); let result = result.last().unwrap(); let Value::Enum { payload, .. } = result else { panic!() }; assert_eq!(**payload, Value::U8(16)) } #[test] fn test_diff_m14_m2() { let (_, program) = load_cairo!( pub extern fn i8_diff(lhs: i8, rhs: i8) -> Result<u8, u8> implicits(RangeCheck) nopanic; fn main() -> Result<u8, u8> { i8_diff(-14, -2) } ); let result = run_test_program(program); let result = result.last().unwrap(); let Value::Enum { payload, .. } = result else { panic!() }; assert_eq!(**payload, Value::U8(244)) } #[test] fn test_diff_m2_0() { let (_, program) = load_cairo!( pub extern fn i8_diff(lhs: i8, rhs: i8) -> Result<u8, u8> implicits(RangeCheck) nopanic; fn main() -> Result<u8, u8> { i8_diff(-2, 0) } ); let result = run_test_program(program); let result = result.last().unwrap(); let Value::Enum { payload, .. } = result else { panic!() }; assert_eq!(**payload, Value::U8(254)) } #[test] fn test_diff_2_10() { let (_, program) = load_cairo!( pub extern fn i8_diff(lhs: i8, rhs: i8) -> Result<u8, u8> implicits(RangeCheck) nopanic; fn main() -> Result<u8, u8> { i8_diff(2, 10) } ); let result = run_test_program(program); let result = result.last().unwrap(); let Value::Enum { payload, .. } = result else { panic!() }; assert_eq!(**payload, Value::U8(248)) } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/felt252_dict.rs
debug_utils/sierra-emu/src/vm/felt252_dict.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType, CoreTypeConcrete}, felt252_dict::Felt252DictConcreteLibfunc, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use cairo_lang_sierra_gas::core_libfunc_cost::{ DICT_SQUASH_REPEATED_ACCESS_COST, DICT_SQUASH_UNIQUE_KEY_COST, }; use smallvec::smallvec; use std::collections::HashMap; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Felt252DictConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { Felt252DictConcreteLibfunc::New(info) => eval_new(registry, info, args), Felt252DictConcreteLibfunc::Squash(info) => eval_squash(registry, info, args), } } pub fn eval_new( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [segment_arena @ Value::Unit]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let type_info = registry .get_type(&info.signature.branch_signatures[0].vars[1].ty) .unwrap(); let ty = match type_info { CoreTypeConcrete::Felt252Dict(info) => &info.ty, _ => unreachable!(), }; EvalAction::NormalBranch( 0, smallvec![ segment_arena, Value::FeltDict { ty: ty.clone(), data: HashMap::new(), count: 0 }, ], ) } pub fn eval_squash( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::U64(gas_builtin), segment_arena @ Value::Unit, Value::FeltDict { ty, data, count }]: [Value; 4] = args.try_into().unwrap() else { panic!(); }; const DICT_GAS_REFUND_PER_ACCESS: u64 = (DICT_SQUASH_UNIQUE_KEY_COST.cost() - DICT_SQUASH_REPEATED_ACCESS_COST.cost()) as u64; let refund = count.saturating_sub(data.len() as u64) * DICT_GAS_REFUND_PER_ACCESS; let new_gas_builtin = gas_builtin + refund; EvalAction::NormalBranch( 0, smallvec![ range_check, Value::U64(new_gas_builtin), segment_arena, Value::FeltDict { ty, data, count } ], ) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/ap_tracking.rs
debug_utils/sierra-emu/src/vm/ap_tracking.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ ap_tracking::ApTrackingConcreteLibfunc, core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &ApTrackingConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { ApTrackingConcreteLibfunc::Revoke(info) => eval_revoke(registry, info, args), ApTrackingConcreteLibfunc::Enable(info) => eval_enable(registry, info, args), ApTrackingConcreteLibfunc::Disable(info) => eval_disable(registry, info, args), } } pub fn eval_revoke( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) } pub fn eval_enable( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) } pub fn eval_disable( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [] = args.try_into().unwrap(); EvalAction::NormalBranch(0, smallvec![]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/poseidon.rs
debug_utils/sierra-emu/src/vm/poseidon.rs
use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, lib_func::SignatureOnlyConcreteLibfunc, poseidon::PoseidonConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; use crate::Value; use super::EvalAction; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &PoseidonConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { PoseidonConcreteLibfunc::HadesPermutation(info) => { eval_hades_permutation(registry, info, args) } } } fn eval_hades_permutation( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [poseidon @ Value::Unit, Value::Felt(p1), Value::Felt(p2), Value::Felt(p3)]: [Value; 4] = args.try_into().unwrap() else { panic!() }; let mut state = [p1, p2, p3]; starknet_crypto::poseidon_permute_comp(&mut state); EvalAction::NormalBranch( 0, smallvec![ poseidon, Value::Felt(state[0]), Value::Felt(state[1]), Value::Felt(state[2]) ], ) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/uint512.rs
debug_utils/sierra-emu/src/vm/uint512.rs
use super::EvalAction; use crate::{ vm::uint256::{u256_to_biguint, u256_to_value, u516_to_value}, Value, }; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType}, int::unsigned512::Uint512Concrete, lib_func::SignatureOnlyConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &Uint512Concrete, args: Vec<Value>, ) -> EvalAction { match selector { Uint512Concrete::DivModU256(info) => eval_divmod(registry, info, args), } } pub fn eval_divmod( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, _info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [range_check @ Value::Unit, Value::Struct(lhs), Value::Struct(rhs)]: [Value; 3] = args.try_into().unwrap() else { panic!() }; let [Value::U128(div_0), Value::U128(div_1), Value::U128(div_2), Value::U128(div_3)]: [Value; 4] = lhs.try_into().unwrap() else { panic!() }; let lhs = u256_to_biguint(div_0, div_1) | (u256_to_biguint(div_2, div_3) << 256); let [Value::U128(divisor_0), Value::U128(divisor_1)]: [Value; 2] = rhs.try_into().unwrap() else { panic!() }; let rhs = u256_to_biguint(divisor_0, divisor_1); let div = &lhs / &rhs; let modulo = lhs % rhs; EvalAction::NormalBranch( 0, smallvec![ range_check, u516_to_value(div), u256_to_value(modulo), Value::Unit, Value::Unit, Value::Unit, Value::Unit, Value::Unit, ], ) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/src/vm/enum.rs
debug_utils/sierra-emu/src/vm/enum.rs
use super::EvalAction; use crate::Value; use cairo_lang_sierra::{ extensions::{ core::{CoreLibfunc, CoreType, CoreTypeConcrete}, enm::{ EnumConcreteLibfunc, EnumConcreteType, EnumFromBoundedIntConcreteLibfunc, EnumInitConcreteLibfunc, }, lib_func::SignatureOnlyConcreteLibfunc, ConcreteLibfunc, }, program_registry::ProgramRegistry, }; use smallvec::smallvec; pub fn eval( registry: &ProgramRegistry<CoreType, CoreLibfunc>, selector: &EnumConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { match selector { EnumConcreteLibfunc::Init(info) => eval_init(registry, info, args), EnumConcreteLibfunc::FromBoundedInt(info) => eval_from_bounded_int(registry, info, args), EnumConcreteLibfunc::Match(info) => eval_match(registry, info, args), EnumConcreteLibfunc::SnapshotMatch(info) => eval_snapshot_match(registry, info, args), } } pub fn eval_init( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &EnumInitConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [value] = args.try_into().unwrap(); let self_ty = &info.signature.branch_signatures[0].vars[0].ty; let CoreTypeConcrete::Enum(EnumConcreteType { variants, .. }) = registry.get_type(self_ty).unwrap() else { panic!() }; assert_eq!(info.n_variants, variants.len()); assert!(info.index < info.n_variants); assert!(value.is(registry, &variants[info.index])); EvalAction::NormalBranch( 0, smallvec![Value::Enum { self_ty: self_ty.clone(), index: info.index, payload: Box::new(value), }], ) } pub fn eval_from_bounded_int( _registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &EnumFromBoundedIntConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::BoundedInt { range: _, value }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let enm = Value::Enum { self_ty: info.branch_signatures()[0].vars[0].ty.clone(), index: value.try_into().unwrap(), payload: Box::new(Value::Struct(vec![])), }; EvalAction::NormalBranch(0, smallvec![enm]) } pub fn eval_match( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index, payload, }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; assert_eq!(self_ty, info.signature.param_signatures[0].ty); assert!(payload.is( registry, &info.signature.branch_signatures[index].vars[0].ty )); EvalAction::NormalBranch(index, smallvec![*payload]) } pub fn eval_snapshot_match( registry: &ProgramRegistry<CoreType, CoreLibfunc>, info: &SignatureOnlyConcreteLibfunc, args: Vec<Value>, ) -> EvalAction { let [Value::Enum { self_ty, index, payload, }]: [Value; 1] = args.try_into().unwrap() else { panic!() }; let ty = registry .get_type(&info.signature.param_signatures[0].ty) .unwrap(); if let CoreTypeConcrete::Snapshot(inner) = ty { assert_eq!(inner.ty, self_ty); } else { panic!("expected snapshot type") } assert!(payload.is( registry, &info.signature.branch_signatures[index].vars[0].ty )); EvalAction::NormalBranch(index, smallvec![*payload]) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/tests/corelib.rs
debug_utils/sierra-emu/tests/corelib.rs
use std::{path::Path, sync::Arc}; use cairo_lang_compiler::{ db::RootDatabase, diagnostics::DiagnosticsReporter, project::{check_compiler_path, setup_project}, }; use cairo_lang_filesystem::{ cfg::{Cfg, CfgSet}, ids::CrateInput, }; use cairo_lang_runner::{casm_run::format_for_panic, RunResultValue}; use cairo_lang_sierra_generator::replace_ids::replace_sierra_ids_in_program; use cairo_lang_starknet::starknet_plugin_suite; use cairo_lang_test_plugin::{ compile_test_prepared_db, test_config::{PanicExpectation, TestExpectation}, test_plugin_suite, TestCompilation, TestsCompilationConfig, }; use common::value_to_felt; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use sierra_emu::{run_program, EntryPoint, ProgramTrace, Value}; mod common; enum TestStatus { Passed, Failed(String), Ignored, } #[test] fn test_corelib() { let compiler_path = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("corelib"); check_compiler_path(false, &compiler_path) .expect("Couldn't find the corelib in the given path"); let db = &mut { let mut b = RootDatabase::builder(); b.detect_corelib(); b.with_cfg(CfgSet::from_iter([Cfg::name("test")])); b.with_default_plugin_suite(test_plugin_suite()); b.with_default_plugin_suite(starknet_plugin_suite()); b.build().unwrap() }; let main_crate_inputs = setup_project(db, &compiler_path).unwrap(); let db = db.snapshot(); let test_crate_ids = main_crate_inputs.clone(); let test_config = TestsCompilationConfig { starknet: false, add_statements_functions: false, add_statements_code_locations: false, contract_declarations: None, contract_crate_ids: None, executable_crate_ids: None, add_functions_debug_info: false, }; let diag_reporter = DiagnosticsReporter::stderr().with_crates(&main_crate_inputs); let filtered_tests = vec![ "core::test::dict_test::test_array_from_squash_dict", "core::test::hash_test::test_blake2s", "core::test::testing_test::test_get_unspent_gas", "core::test::qm31_test::", ]; let compiled = compile_tests( &db, test_config, test_crate_ids, diag_reporter, Some(&filtered_tests), ); let results = run_tests(compiled); display_results(&results); assert!(results .iter() .all(|s| matches!(s, TestStatus::Passed | TestStatus::Ignored)),); } /// Runs the tests and process the results for a summary. fn run_tests(compiled: TestCompilation) -> Vec<TestStatus> { let program = Arc::new(compiled.sierra_program.program); compiled .metadata .named_tests .into_par_iter() .map(|(name, test)| { if test.ignored { println!("test {} ... Ignored", name); return TestStatus::Ignored; } // catch any panic during the test run let res = std::panic::catch_unwind(|| { run_program( program.clone(), EntryPoint::String(name.clone()), vec![], test.available_gas.map(|g| g as u64).unwrap_or_default(), ) }); let status = match res { Ok(trace) => { let run_result = trace_to_run_result(trace); assert_test_expectation(test.expectation, run_result) } Err(panic) => { TestStatus::Failed(format!("PANIC: {:?}", panic.downcast_ref::<String>())) } }; match &status { TestStatus::Passed => println!("test {} ... OK", name), TestStatus::Failed(err) => println!("test {} ... FAILED: {}", name, err), TestStatus::Ignored => {} // already handled before }; status }) .collect::<Vec<TestStatus>>() } fn trace_to_run_result(trace: ProgramTrace) -> RunResultValue { let return_value = trace.return_value(); let mut felts = Vec::new(); let is_success = match &return_value { outer_value @ Value::Enum { self_ty, index, payload, .. } => { let debug_name = self_ty.debug_name.as_ref().expect("missing debug name"); if debug_name.starts_with("core::panics::PanicResult::") || debug_name.starts_with("Enum<ut@core::panics::PanicResult::") { let is_success = *index == 0; if !is_success { match &**payload { Value::Struct(fields) => { for field in fields { let felt = value_to_felt(field); felts.extend(felt); } } _ => panic!("unsuported return value in cairo-native"), } } else { felts.extend(value_to_felt(payload)); } is_success } else { felts.extend(value_to_felt(outer_value)); true } } x => { felts.extend(value_to_felt(x)); true } }; let return_values = felts.into_iter().map(|x| x.to_bigint().into()).collect(); match is_success { true => RunResultValue::Success(return_values), false => RunResultValue::Panic(return_values), } } fn assert_test_expectation(expectation: TestExpectation, result: RunResultValue) -> TestStatus { match result { RunResultValue::Success(r) => { if let TestExpectation::Panics(_) = expectation { let err_msg = format_for_panic(r.into_iter()); return TestStatus::Failed(err_msg); } TestStatus::Passed } RunResultValue::Panic(e) => match expectation { TestExpectation::Success => { let err_msg = format_for_panic(e.into_iter()); TestStatus::Failed(err_msg) } TestExpectation::Panics(panic_expect) => match panic_expect { PanicExpectation::Exact(expected) => { if expected != e { let err_msg = format_for_panic(e.into_iter()); return TestStatus::Failed(err_msg); } TestStatus::Passed } PanicExpectation::Any => TestStatus::Passed, }, }, } } fn display_results(results: &[TestStatus]) { let mut passed = 0; let mut failed = 0; let mut ignored = 0; for status in results { match &status { TestStatus::Passed => passed += 1, TestStatus::Failed(_) => failed += 1, TestStatus::Ignored => ignored += 1, } } if failed > 0 { println!( "\n\ntest result: FAILED. {} PASSED; {} FAILED; {} FILTERED OUT;", passed, failed, ignored ); } else { println!( "\n\ntest result: OK. {} PASSED; {} FAILED; {} FILTERED OUT;", passed, failed, ignored ); } } fn compile_tests<'a>( db: &'a RootDatabase, test_config: TestsCompilationConfig<'a>, test_crate_inputs: Vec<CrateInput>, diag_reporter: DiagnosticsReporter<'_>, with_filtered_tests: Option<&[&str]>, ) -> TestCompilation<'a> { let mut compiled = compile_test_prepared_db(db, test_config, test_crate_inputs, diag_reporter).unwrap(); // replace ids to have debug_names compiled.sierra_program.program = replace_sierra_ids_in_program(db, &compiled.sierra_program.program); if let Some(compilation_filter) = with_filtered_tests { let should_skip_test = |name: &str| -> bool { compilation_filter .iter() .any(|filter| name.contains(filter)) }; // Ignore matching test cases. compiled .metadata .named_tests .iter_mut() .for_each(|(test, case)| { if should_skip_test(test) { case.ignored = true } }); } compiled }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/tests/syscalls.rs
debug_utils/sierra-emu/tests/syscalls.rs
use std::{path::Path, sync::Arc}; use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; use cairo_lang_lowering::utils::InliningStrategy; use cairo_lang_sierra::program::{GenFunction, Program, StatementIdx}; use sierra_emu::{starknet::StubSyscallHandler, ProgramTrace, VirtualMachine}; fn run_syscall(func_name: &str) -> ProgramTrace { let path = Path::new("programs/syscalls.cairo"); let sierra_program = Arc::new( compile_cairo_project_at_path( path, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, ) .unwrap(), ); let function = find_entry_point_by_name(&sierra_program, func_name).unwrap(); let mut vm = VirtualMachine::new(sierra_program.clone()); let calldata = []; let initial_gas = 1000000; vm.call_program(function, initial_gas, calldata); let syscall_handler = &mut StubSyscallHandler::default(); vm.run_with_trace(syscall_handler) } #[test] fn test_contract_constructor() { run_syscall("syscalls::syscalls::get_execution_info_v2"); } pub fn find_entry_point_by_idx( program: &Program, entry_point_idx: usize, ) -> Option<&GenFunction<StatementIdx>> { program .funcs .iter() .find(|x| x.id.id == entry_point_idx as u64) } pub fn find_entry_point_by_name<'a>( program: &'a Program, name: &str, ) -> Option<&'a GenFunction<StatementIdx>> { program .funcs .iter() .find(|x| x.id.debug_name.as_ref().map(|x| x.as_str()) == Some(name)) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/tests/libfuncs.rs
debug_utils/sierra-emu/tests/libfuncs.rs
use std::{path::Path, sync::Arc}; use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; use cairo_lang_lowering::utils::InliningStrategy; use cairo_lang_sierra::program::{GenFunction, Program, StatementIdx}; use num_bigint::BigInt; use sierra_emu::{starknet::StubSyscallHandler, Value, VirtualMachine}; fn run_program(path: &str, func_name: &str, args: &[Value]) -> Vec<Value> { let path = Path::new(path); let sierra_program = Arc::new( compile_cairo_project_at_path( path, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, ) .unwrap(), ); let function = find_entry_point_by_name(&sierra_program, func_name).unwrap(); let mut vm = VirtualMachine::new(sierra_program.clone()); let args = args.iter().cloned(); let initial_gas = 1000000; vm.call_program(function, initial_gas, args); let syscall_handler = &mut StubSyscallHandler::default(); let trace = vm.run_with_trace(syscall_handler); trace .states .last() .unwrap() .items .values() .cloned() .collect() } #[test] fn test_u32_overflow() { let r = run_program( "tests/tests/test_u32.cairo", "test_u32::test_u32::run_test", &[Value::U32(2), Value::U32(2)], ); assert!(matches!( r[1], Value::Enum { self_ty: _, index: 0, payload: _ } )); let r = run_program( "tests/tests/test_u32.cairo", "test_u32::test_u32::run_test", &[Value::U32(2), Value::U32(3)], ); assert!(matches!( r[1], Value::Enum { self_ty: _, index: 1, payload: _ } )); let r = run_program( "tests/tests/test_u32.cairo", "test_u32::test_u32::run_test", &[Value::U32(0), Value::U32(0)], ); assert!(matches!( r[1], Value::Enum { self_ty: _, index: 0, payload: _ } )); } pub fn find_entry_point_by_idx( program: &Program, entry_point_idx: usize, ) -> Option<&GenFunction<StatementIdx>> { program .funcs .iter() .find(|x| x.id.id == entry_point_idx as u64) } pub fn find_entry_point_by_name<'a>( program: &'a Program, name: &str, ) -> Option<&'a GenFunction<StatementIdx>> { program .funcs .iter() .find(|x| x.id.debug_name.as_ref().map(|x| x.as_str()) == Some(name)) } // CIRCUITS #[test] fn test_run_full_circuit() { let range96 = BigInt::ZERO..(BigInt::from(1) << 96); let limb0 = Value::BoundedInt { range: range96.clone(), value: 36699840570117848377038274035_u128.into(), }; let limb1 = Value::BoundedInt { range: range96.clone(), value: 72042528776886984408017100026_u128.into(), }; let limb2 = Value::BoundedInt { range: range96.clone(), value: 54251667697617050795983757117_u128.into(), }; let limb3 = Value::BoundedInt { range: range96, value: 7.into(), }; let output = run_program( "tests/tests/circuits.cairo", "circuits::circuits::main", &[], ); let expected_output = Value::Struct(vec![Value::Struct(vec![limb0, limb1, limb2, limb3])]); let Value::Enum { self_ty: _, index: _, payload, } = output.last().unwrap() else { panic!("No output"); }; assert_eq!(**payload, expected_output); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/tests/common/mod.rs
debug_utils/sierra-emu/tests/common/mod.rs
use sierra_emu::Value; use starknet_crypto::Felt; /// Convert a Value to a felt. pub fn value_to_felt(value: &Value) -> Vec<Felt> { let mut felts = Vec::new(); match value { Value::Array { data, .. } | Value::Struct(data) => { data.iter().flat_map(value_to_felt).collect() } Value::BoundedInt { value, .. } => vec![value.into()], Value::Bytes31(bytes) => vec![*bytes], Value::BuiltinCosts(costs) => vec![ costs.r#const.into(), costs.pedersen.into(), costs.bitwise.into(), costs.ecop.into(), costs.poseidon.into(), costs.add_mod.into(), costs.mul_mod.into(), ], Value::CircuitModulus(value) => vec![value.into()], Value::Circuit(data) => data.iter().map(Felt::from).collect(), Value::CircuitOutputs { circuits: data, modulus, } => { let mut felts = data.iter().map(Felt::from).collect::<Vec<_>>(); felts.push(modulus.into()); felts } Value::EcPoint { x, y } => { vec![*x, *y] } Value::EcState { x0, y0, x1, y1 } => { vec![*x0, *y0, *x1, *y1] } Value::Enum { self_ty, index, payload, } => { if let Some(debug_name) = &self_ty.debug_name { if debug_name == "core::bool" { vec![(*index == 1).into()] } else { let mut felts = vec![(*index).into()]; felts.extend(value_to_felt(payload)); felts } } else { // Assume its a regular enum. let mut felts = vec![(*index).into()]; felts.extend(value_to_felt(payload)); felts } } Value::Felt(felt) => vec![*felt], Value::FeltDict { data, .. } => { for (key, value) in data { felts.push(*key); let felt = value_to_felt(value); felts.extend(felt); } felts } Value::FeltDictEntry { key: data_key, data, .. } => { felts.push(*data_key); for (key, value) in data { felts.push(*key); let felt = value_to_felt(value); felts.extend(felt); } felts } Value::I8(x) => vec![(*x).into()], Value::I16(x) => vec![(*x).into()], Value::I32(x) => vec![(*x).into()], Value::I64(x) => vec![(*x).into()], Value::I128(x) => vec![(*x).into()], Value::U8(x) => vec![(*x).into()], Value::U16(x) => vec![(*x).into()], Value::U32(x) => vec![(*x).into()], Value::U64(x) => vec![(*x).into()], Value::U128(x) => vec![(*x).into()], Value::U256(x, y) => vec![(*x).into(), (*y).into()], Value::IntRange { x, y } => { let felt = value_to_felt(x); felts.extend(felt); let felt = value_to_felt(y); felts.extend(felt); felts } Value::Unit | Value::Null | Value::Uninitialized { .. } => vec![0.into()], } }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/examples/contract.rs
debug_utils/sierra-emu/examples/contract.rs
use std::{error::Error, sync::Arc}; use std::path::Path; use cairo_lang_compiler::CompilerConfig; use cairo_lang_lowering::utils::InliningStrategy; use cairo_lang_starknet::compile::compile_path; use cairo_lang_starknet_classes::contract_class::version_id_from_serialized_sierra_program; use sierra_emu::{starknet::StubSyscallHandler, ContractExecutionResult, VirtualMachine}; use starknet_crypto::Felt; fn main() -> Result<(), Box<dyn Error>> { // INPUT ARGUMENTS let cairo_path = Path::new("programs/fibonacci_contract.cairo"); let arguments: [Felt; 1] = [Felt::from(10)]; let initial_gas = 100000; // Compile cairo to sierra let contract = compile_path( cairo_path, None, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, )?; let program = contract.extract_sierra_program()?; let (version_id, _) = version_id_from_serialized_sierra_program(&contract.sierra_program)?; // Find entrypoint to execute let entrypoint = contract .entry_points_by_type .external .first() .ok_or("contract should contain at least one external entrypoint")? .clone(); // Build virtual machine let mut vm = VirtualMachine::new_starknet( Arc::new(program), &contract.entry_points_by_type, version_id, ); vm.call_contract(entrypoint.selector.into(), initial_gas, arguments, None); // Execute the virtual machine. let syscall_handler = &mut StubSyscallHandler::default(); let trace = vm.run_with_trace(syscall_handler); // Obtain execution result from last frame let result = ContractExecutionResult::from_trace(&trace).ok_or("failed to obtain execution result")?; println!("{result:?}"); Ok(()) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/sierra-emu/examples/program.rs
debug_utils/sierra-emu/examples/program.rs
use std::{error::Error, path::Path, sync::Arc}; use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; use cairo_lang_lowering::utils::InliningStrategy; use sierra_emu::{ find_entry_point_by_name, starknet::StubSyscallHandler, ContractExecutionResult, Value, VirtualMachine, }; fn main() -> Result<(), Box<dyn Error>> { // INPUT ARGUMENTS let cairo_path = Path::new("programs/fibonacci.cairo"); let entrypoint = "fibonacci::fibonacci::main"; let arguments: [Value; 0] = []; let initial_gas = 100000; // Compile cairo to sierra let program = compile_cairo_project_at_path( cairo_path, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, )?; // Find entrypoint to execute let function = find_entry_point_by_name(&program, entrypoint) .ok_or("failed to find main entrypoint")? .clone(); // Build virtual machine let mut vm = VirtualMachine::new(Arc::new(program)); vm.call_program(&function, initial_gas, arguments); // Execute the virtual machine. let syscall_handler = &mut StubSyscallHandler::default(); let trace = vm.run_with_trace(syscall_handler); // Obtain execution result from last frame let result = ContractExecutionResult::from_trace(&trace).ok_or("failed to obtain execution result")?; println!("{result:?}"); Ok(()) }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/debug_utils/cairo-native-stress/src/main.rs
debug_utils/cairo-native-stress/src/main.rs
//! A stress tester for Cairo Native //! //! See `StressTestCommand` for documentation on the CLI. //! //! ## Walkthrough //! //! Iterates through N rounds (specified as an argument), and in each round: //! - Generates an unique dummy starknet contract. //! - Compiles the program and inserts the compiled program into the cache. //! - Executes the program. //! //! The cache is dropped at the end of the whole execution. //! //! For documentation on the specific cache used, see `NaiveAotCache`. use cairo_lang_sierra::{ ids::FunctionId, program::{GenericArg, Program}, program_registry::ProgramRegistry, }; use cairo_lang_starknet::compile::compile_path; use cairo_native::{ context::NativeContext, executor::AotNativeExecutor, metadata::gas::GasMetadata, module_to_object, object_to_shared_lib, starknet::DummySyscallHandler, utils::{find_entry_point_by_idx, SHARED_LIBRARY_EXT}, OptLevel, }; use clap::Parser; use libloading::Library; use num_bigint::BigInt; use stats_alloc::{Region, StatsAlloc, INSTRUMENTED_SYSTEM}; use std::{ alloc::System, collections::HashMap, fmt::{Debug, Display}, fs::{self, create_dir_all, read_dir, OpenOptions}, hash::Hash, io, path::{Path, PathBuf}, sync::Arc, time::Instant, }; use tracing::{debug, info, info_span, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer}; #[global_allocator] static GLOBAL_ALLOC: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM; /// The directory used to store compiled native programs const AOT_CACHE_DIR: &str = ".aot-cache"; /// An unique value hardcoded into the initial contract that it's /// used as an anchor point to safely modify it. /// It can be any value as long as it's unique in the contract. const UNIQUE_CONTRACT_VALUE: u32 = 835; /// A stress tester for Cairo Native /// /// It compiles Sierra programs with Cairo Native, caches, and executes them with AOT runner. /// The compiled dynamic libraries are stored in `AOT_CACHE_DIR` relative to the current working directory. #[derive(Parser, Debug)] struct StressTestCommand { /// Amount of rounds to execute rounds: u32, /// Output file for JSON formatted logs #[arg(short, long)] output: Option<PathBuf>, } fn main() { let args = StressTestCommand::parse(); set_global_subscriber(&args); if !directory_is_empty(AOT_CACHE_DIR).expect("failed to open aot cache dir") { warn!("{AOT_CACHE_DIR} directory is not empty") } // Generate initial program let (entry_point, program) = { let before_generate = Instant::now(); let initial_program = generate_starknet_contract(UNIQUE_CONTRACT_VALUE); let elapsed = before_generate.elapsed().as_millis(); debug!(time = elapsed, "generated test program"); initial_program }; let global_region = Region::new(GLOBAL_ALLOC); let before_stress_test = Instant::now(); // Initialize context and cache let native_context = NativeContext::new(); let mut cache = NaiveAotCache::new(&native_context); info!("starting stress test"); for round in 0..args.rounds { let _enter_round_span = info_span!("round", number = round).entered(); let before_round = Instant::now(); let program = modify_starknet_contract(program.clone(), UNIQUE_CONTRACT_VALUE, round); let hash = round; debug!(hash, "obtained test program"); if cache.get(&hash).is_some() { panic!("all program keys should be different") } // Compiles and caches the program let executor = { let before_compile = Instant::now(); let executor = cache.compile_and_insert(hash, &program, cairo_native::OptLevel::None); let elapsed = before_compile.elapsed().as_millis(); debug!(time = elapsed, "compiled test program"); executor }; // Executes the program let execution_result = { let now = Instant::now(); let execution_result = executor .invoke_contract_dynamic(&entry_point, &[], Some(u64::MAX), DummySyscallHandler) .expect("failed to execute contract"); let elapsed = now.elapsed().as_millis(); let result = execution_result.return_values[0]; debug!(time = elapsed, result = %result, "executed test program"); execution_result }; assert!( !execution_result.failure_flag, "contract execution had failure flag set" ); // Logs end of round let elapsed = before_round.elapsed().as_millis(); let cache_disk_size = directory_get_size(AOT_CACHE_DIR).expect("failed to calculate cache disk size"); let global_stats = global_region.change(); let memory_used = global_stats.bytes_allocated - global_stats.bytes_deallocated; info!( time = elapsed, memory_used = memory_used, cache_disk_size = cache_disk_size, "finished round" ); } let elapsed = before_stress_test.elapsed().as_millis(); info!(time = elapsed, "finished stress test"); } /// Generate a dummy starknet contract /// /// The contract contains an external main function that returns `return_value` fn generate_starknet_contract( return_value: u32, ) -> (FunctionId, cairo_lang_sierra::program::Program) { let program_str = format!( "\ #[starknet::contract] mod Contract {{ #[storage] struct Storage {{}} #[external(v0)] fn main(self: @ContractState) -> felt252 {{ return {return_value}; }} }} " ); let mut program_file = tempfile::Builder::new() .prefix("test_") .suffix(".cairo") .tempfile() .expect("failed to create temporary file for cairo test program"); fs::write(&mut program_file, program_str).expect("failed to write cairo test file"); let contract_class = compile_path( program_file.path(), None, Default::default(), Default::default(), ) .expect("failed to compile cairo contract"); let program = contract_class .extract_sierra_program() .expect("failed to extract sierra program"); let entry_point_idx = contract_class .entry_points_by_type .external .first() .expect("contract should have at least one entrypoint") .function_idx; let entry_point = find_entry_point_by_idx(&program, entry_point_idx) .expect("failed to find entrypoint") .id .clone(); (entry_point, program) } /// Modifies the given contract by replacing the `old_value` with `new_value` in any type declaration /// /// The contract must only contain the value `old_value` once fn modify_starknet_contract(mut program: Program, old_value: u32, new_value: u32) -> Program { let mut old_value_counter = 0; for type_declaration in &mut program.type_declarations { for generic_arg in &mut type_declaration.long_id.generic_args { let anchor = BigInt::from(old_value); match generic_arg { GenericArg::Value(return_value) if *return_value == anchor => { *return_value = BigInt::from(new_value); old_value_counter += 1; } _ => {} }; } } assert!( old_value_counter == 1, "old_value was not found exactly once" ); program } /// A naive implementation of an AOT Program Cache /// /// For each contract: /// - Compiles it to a shared library and stores it on disk (`AOT_CACHE_DIR`) /// - Loads the shared library into an executor and stores it on a hashmap with the given key. /// /// The shared libraries are unloaded when the executor gets drop, AKA: when the cache gets dropped. /// The shared libraries on disk are never deleted /// /// Possible improvements include: /// - Keeping only some executors on memory, while storing the remaining compiled shared libraries only on disk. /// - When restarting the program, reutilize already compiled programs from `AOT_CACHE_DIR` struct NaiveAotCache<'a, K> where K: PartialEq + Eq + Hash + Display, { context: &'a NativeContext, cache: HashMap<K, Arc<AotNativeExecutor>>, } impl<'a, K> NaiveAotCache<'a, K> where K: PartialEq + Eq + Hash + Display, { pub fn new(context: &'a NativeContext) -> Self { Self { context, cache: Default::default(), } } pub fn get(&self, key: &K) -> Option<Arc<AotNativeExecutor>> { self.cache.get(key).cloned() } /// Compiles and inserts a given program into the cache /// /// The dynamic library is stored in `AOT_CACHE_DIR` directory pub fn compile_and_insert( &mut self, key: K, program: &Program, opt_level: OptLevel, ) -> Arc<AotNativeExecutor> { let native_module = self .context .compile(program, false, Some(Default::default()), None) .expect("failed to compile program"); let registry = ProgramRegistry::new(program).expect("failed to get program registry"); let metadata = native_module .metadata() .get::<GasMetadata>() .cloned() .expect("module should have gas metadata"); let shared_library = { let object_data = module_to_object(native_module.module(), opt_level, None) .expect("failed to convert MLIR to object"); let shared_library_dir = Path::new(AOT_CACHE_DIR); create_dir_all(shared_library_dir).expect("failed to create shared library directory"); let shared_library_name = format!("lib{key}{SHARED_LIBRARY_EXT}"); let shared_library_path = shared_library_dir.join(shared_library_name); object_to_shared_lib(&object_data, &shared_library_path, None) .expect("failed to link object into shared library"); unsafe { Library::new(shared_library_path).expect("failed to load dynamic shared library") } }; let executor = AotNativeExecutor::new( shared_library, registry, metadata, native_module.metadata().get().cloned().unwrap_or_default(), ); let executor = Arc::new(executor); self.cache.insert(key, executor.clone()); executor } } /// Returns the size of a directory in bytes fn directory_get_size(path: impl AsRef<Path>) -> io::Result<u64> { let mut dir = read_dir(path)?; dir.try_fold(0, |total_size, entry| { let entry = entry?; let size = match entry.metadata()? { data if data.is_dir() => directory_get_size(entry.path())?, data => data.len(), }; Ok(total_size + size) }) } fn directory_is_empty(path: impl AsRef<Path>) -> io::Result<bool> { let is_empty = match read_dir(path) { Ok(mut directory) => directory.next().is_none(), Err(error) => match error.kind() { io::ErrorKind::NotFound => true, _ => return Err(error), }, }; Ok(is_empty) } fn set_global_subscriber(args: &StressTestCommand) { let stdout = tracing_subscriber::fmt::layer().with_filter(EnvFilter::from_default_env()); // Enables file logging conditionally, as Option<Layer> also implements Layer let file = args.output.as_ref().map(|path| { let file = OpenOptions::new() .create(true) .append(true) .open(path) .expect("failed to open output file"); tracing_subscriber::fmt::layer() .json() .with_writer(file) .with_filter(EnvFilter::from_default_env()) }); tracing_subscriber::Registry::default() .with(stdout) .with(file) .init(); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/examples/easy_api.rs
examples/easy_api.rs
use cairo_native::{ context::NativeContext, executor::JitNativeExecutor, utils::testing::cairo_to_sierra, Value, }; use starknet_types_core::felt::Felt; use std::path::Path; fn main() { let program_path = Path::new("programs/examples/hello.cairo"); // Instantiate a Cairo Native MLIR context. This data structure is responsible for the MLIR // initialization and compilation of sierra programs into a MLIR module. let native_context = NativeContext::new(); // Compile the cairo program to sierra. let sierra_program = cairo_to_sierra(program_path).unwrap(); // Compile the sierra program into a MLIR module. let native_program = native_context .compile(&sierra_program, false, Some(Default::default()), None) .unwrap(); // The parameters of the entry point. let params = &[Value::Felt252(Felt::from_bytes_be_slice(b"user"))]; // Find the entry point id by its name. let entry_point = "hello::hello::greet"; let entry_point_id = cairo_native::utils::find_function_id(&sierra_program, entry_point) .expect("entry point not found"); // Instantiate the executor. let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default()).unwrap(); // Execute the program. let result = native_executor .invoke_dynamic(entry_point_id, params, None) .unwrap(); println!("Cairo program was compiled and executed successfully."); println!("{:?}", result); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/examples/invoke.rs
examples/invoke.rs
use cairo_native::{ context::NativeContext, executor::JitNativeExecutor, utils::find_entry_point, Value, }; use std::path::Path; use tracing_subscriber::{EnvFilter, FmtSubscriber}; fn main() { // Configure logging and error handling. tracing::subscriber::set_global_default( FmtSubscriber::builder() .with_env_filter(EnvFilter::from_default_env()) .finish(), ) .unwrap(); let program_path = Path::new("programs/echo.cairo"); // Compile the cairo program to sierra. let sierra_program = cairo_native::utils::testing::cairo_to_sierra(program_path).unwrap(); let native_context = NativeContext::new(); let native_program = native_context .compile(&sierra_program, false, Some(Default::default()), None) .unwrap(); // Call the echo function from the contract using the generated wrapper. let entry_point_fn = find_entry_point(&sierra_program, "echo::echo::main").unwrap(); let fn_id = &entry_point_fn.id; let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default()).unwrap(); let output = native_executor.invoke_dynamic(fn_id, &[Value::Felt252(1.into())], None); println!(); println!("Cairo program was compiled and executed successfully."); println!("{output:#?}"); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/examples/starknet.rs
examples/starknet.rs
use cairo_lang_compiler::CompilerConfig; use cairo_lang_lowering::utils::InliningStrategy; use cairo_lang_starknet::compile::compile_path; use cairo_native::{ context::NativeContext, executor::JitNativeExecutor, starknet::{ BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point, StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256, }, utils::find_entry_point_by_idx, }; use starknet_types_core::felt::Felt; use std::{ collections::{HashMap, VecDeque}, path::Path, }; use tracing_subscriber::{EnvFilter, FmtSubscriber}; type Log = (Vec<Felt>, Vec<Felt>); type L2ToL1Message = (Felt, Vec<Felt>); #[derive(Debug, Default)] #[allow(dead_code)] struct ContractLogs { events: VecDeque<Log>, l2_to_l1_messages: VecDeque<L2ToL1Message>, } #[derive(Debug, Default)] #[allow(dead_code)] struct TestingState { sequencer_address: Felt, caller_address: Felt, contract_address: Felt, account_contract_address: Felt, transaction_hash: Felt, nonce: Felt, chain_id: Felt, version: Felt, max_fee: u64, block_number: u64, block_timestamp: u64, signature: Vec<Felt>, logs: HashMap<Felt, ContractLogs>, } #[derive(Debug, Default)] #[allow(dead_code)] struct SyscallHandler { testing_state: TestingState, } impl SyscallHandler { pub fn new() -> Self { Self { testing_state: TestingState::default(), } } } impl StarknetSyscallHandler for SyscallHandler { fn get_block_hash(&mut self, block_number: u64, _gas: &mut u64) -> SyscallResult<Felt> { println!("Called `get_block_hash({block_number})` from MLIR."); Ok(Felt::from_bytes_be_slice(b"get_block_hash ok")) } fn get_execution_info( &mut self, _gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfo> { println!("Called `get_execution_info()` from MLIR."); Ok(ExecutionInfo { block_info: BlockInfo { block_number: 1234, block_timestamp: 2345, sequencer_address: 3456.into(), }, tx_info: TxInfo { version: 4567.into(), account_contract_address: 5678.into(), max_fee: 6789, signature: vec![1248.into(), 2486.into()], transaction_hash: 9876.into(), chain_id: 8765.into(), nonce: 7654.into(), }, caller_address: 6543.into(), contract_address: 5432.into(), entry_point_selector: 4321.into(), }) } fn get_execution_info_v2( &mut self, _remaining_gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfoV2> { println!("Called `get_execution_info_v2()` from MLIR."); Ok(ExecutionInfoV2 { block_info: BlockInfo { block_number: 1234, block_timestamp: 2345, sequencer_address: 3456.into(), }, tx_info: TxV2Info { version: 1.into(), account_contract_address: 1.into(), max_fee: 0, signature: vec![1.into()], transaction_hash: 1.into(), chain_id: 1.into(), nonce: 1.into(), tip: 1, paymaster_data: vec![1.into()], nonce_data_availability_mode: 0, fee_data_availability_mode: 0, account_deployment_data: vec![1.into()], resource_bounds: vec![ResourceBounds { resource: 2.into(), max_amount: 10, max_price_per_unit: 20, }], }, caller_address: 6543.into(), contract_address: 5432.into(), entry_point_selector: 4321.into(), }) } fn get_execution_info_v3( &mut self, _remaining_gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfoV3> { println!("Called `get_execution_info_v3()` from MLIR."); todo!(); } fn deploy( &mut self, class_hash: Felt, contract_address_salt: Felt, calldata: &[Felt], deploy_from_zero: bool, _gas: &mut u64, ) -> SyscallResult<(Felt, Vec<Felt>)> { println!("Called `deploy({class_hash}, {contract_address_salt}, {calldata:?}, {deploy_from_zero})` from MLIR."); Ok(( class_hash + contract_address_salt, calldata.iter().map(|x| x + Felt::ONE).collect(), )) } fn replace_class(&mut self, class_hash: Felt, _gas: &mut u64) -> SyscallResult<()> { println!("Called `replace_class({class_hash})` from MLIR."); Ok(()) } fn library_call( &mut self, class_hash: Felt, function_selector: Felt, calldata: &[Felt], _gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { println!( "Called `library_call({class_hash}, {function_selector}, {calldata:?})` from MLIR." ); Ok(calldata.iter().map(|x| x * Felt::from(3)).collect()) } fn call_contract( &mut self, address: Felt, entry_point_selector: Felt, calldata: &[Felt], _gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { println!( "Called `call_contract({address}, {entry_point_selector}, {calldata:?})` from MLIR." ); Ok(calldata.iter().map(|x| x * Felt::from(3)).collect()) } fn storage_read( &mut self, address_domain: u32, address: Felt, _gas: &mut u64, ) -> SyscallResult<Felt> { println!("Called `storage_read({address_domain}, {address})` from MLIR."); Ok(address * Felt::from(3)) } fn storage_write( &mut self, address_domain: u32, address: Felt, value: Felt, _gas: &mut u64, ) -> SyscallResult<()> { println!("Called `storage_write({address_domain}, {address}, {value})` from MLIR."); Ok(()) } fn emit_event(&mut self, keys: &[Felt], data: &[Felt], _gas: &mut u64) -> SyscallResult<()> { println!("Called `emit_event({keys:?}, {data:?})` from MLIR."); Ok(()) } fn send_message_to_l1( &mut self, to_address: Felt, payload: &[Felt], _gas: &mut u64, ) -> SyscallResult<()> { println!("Called `send_message_to_l1({to_address}, {payload:?})` from MLIR."); Ok(()) } fn keccak( &mut self, input: &[u64], _gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::U256> { println!("Called `keccak({input:?})` from MLIR."); Ok(U256 { hi: 0, lo: 1234567890, }) } fn secp256k1_new( &mut self, _x: U256, _y: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256k1Point>> { unimplemented!() } fn secp256k1_add( &mut self, _p0: Secp256k1Point, _p1: Secp256k1Point, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256k1Point> { unimplemented!() } fn secp256k1_mul( &mut self, _p: Secp256k1Point, _m: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256k1Point> { unimplemented!() } fn secp256k1_get_point_from_x( &mut self, _x: U256, _y_parity: bool, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256k1Point>> { unimplemented!() } fn secp256k1_get_xy( &mut self, _p: Secp256k1Point, _remaining_gas: &mut u64, ) -> SyscallResult<(U256, U256)> { unimplemented!() } fn secp256r1_new( &mut self, _x: U256, _y: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256r1Point>> { unimplemented!() } fn secp256r1_add( &mut self, _p0: Secp256r1Point, _p1: Secp256r1Point, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256r1Point> { unimplemented!() } fn secp256r1_mul( &mut self, _p: Secp256r1Point, _m: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256r1Point> { unimplemented!() } fn secp256r1_get_point_from_x( &mut self, _x: U256, _y_parity: bool, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256r1Point>> { unimplemented!() } fn secp256r1_get_xy( &mut self, _p: Secp256r1Point, _remaining_gas: &mut u64, ) -> SyscallResult<(U256, U256)> { unimplemented!() } fn sha256_process_block( &mut self, _state: &mut [u32; 8], _block: &[u32; 16], _remaining_gas: &mut u64, ) -> SyscallResult<()> { unimplemented!() } fn get_class_hash_at( &mut self, _contract_address: Felt, _remaining_gas: &mut u64, ) -> SyscallResult<Felt> { unimplemented!() } fn meta_tx_v0( &mut self, _address: Felt, _entry_point_selector: Felt, _calldata: &[Felt], _signature: &[Felt], _remaining_gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { unimplemented!() } #[cfg(feature = "with-cheatcode")] fn cheatcode(&mut self, selector: Felt, input: &[Felt]) -> Vec<Felt> { let selector_bytes = selector.to_bytes_be(); let selector = match std::str::from_utf8(&selector_bytes) { Ok(selector) => selector.trim_start_matches('\0'), Err(_) => return Vec::new(), }; match selector { "set_sequencer_address" => { self.testing_state.sequencer_address = input[0]; vec![] } "set_caller_address" => { self.testing_state.caller_address = input[0]; vec![] } "set_contract_address" => { self.testing_state.contract_address = input[0]; vec![] } "set_account_contract_address" => { self.testing_state.account_contract_address = input[0]; vec![] } "set_transaction_hash" => { self.testing_state.transaction_hash = input[0]; vec![] } "set_nonce" => { self.testing_state.nonce = input[0]; vec![] } "set_version" => { self.testing_state.version = input[0]; vec![] } "set_chain_id" => { self.testing_state.chain_id = input[0]; vec![] } "set_max_fee" => { let max_fee = input[0].to_biguint().try_into().unwrap(); self.testing_state.max_fee = max_fee; vec![] } "set_block_number" => { let block_number = input[0].to_biguint().try_into().unwrap(); self.testing_state.block_number = block_number; vec![] } "set_block_timestamp" => { let block_timestamp = input[0].to_biguint().try_into().unwrap(); self.testing_state.block_timestamp = block_timestamp; vec![] } "set_signature" => { self.testing_state.signature = input.to_vec(); vec![] } "pop_log" => self .testing_state .logs .get_mut(&input[0]) .and_then(|logs| logs.events.pop_front()) .map(|mut log| { let mut serialized_log = Vec::new(); serialized_log.push(log.0.len().into()); serialized_log.append(&mut log.0); serialized_log.push(log.1.len().into()); serialized_log.append(&mut log.1); serialized_log }) .unwrap_or_default(), "pop_l2_to_l1_message" => self .testing_state .logs .get_mut(&input[0]) .and_then(|logs| logs.l2_to_l1_messages.pop_front()) .map(|mut log| { let mut serialized_log = Vec::new(); serialized_log.push(log.0); serialized_log.push(log.1.len().into()); serialized_log.append(&mut log.1); serialized_log }) .unwrap_or_default(), _ => vec![], } } } fn main() { // Configure logging and error handling. tracing::subscriber::set_global_default( FmtSubscriber::builder() .with_env_filter(EnvFilter::from_default_env()) .finish(), ) .unwrap(); let path = Path::new("programs/examples/hello_starknet.cairo"); let contract = compile_path( path, None, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, ) .unwrap(); let entry_point = contract.entry_points_by_type.external.first().unwrap(); let sierra_program = contract.extract_sierra_program().unwrap(); let native_context = NativeContext::new(); let native_program = native_context .compile(&sierra_program, false, Some(Default::default()), None) .unwrap(); // Call the echo function from the contract using the generated wrapper. let entry_point_fn = find_entry_point_by_idx(&sierra_program, entry_point.function_idx).unwrap(); let fn_id = &entry_point_fn.id; let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default()).unwrap(); let result = native_executor .invoke_contract_dynamic(fn_id, &[Felt::ONE], Some(u64::MAX), SyscallHandler::new()) .expect("failed to execute the given contract"); println!(); println!("Cairo program was compiled and executed successfully."); println!("{result:#?}"); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
lambdaclass/cairo_native
https://github.com/lambdaclass/cairo_native/blob/f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce/examples/erc20.rs
examples/erc20.rs
use cairo_lang_compiler::CompilerConfig; use cairo_lang_lowering::utils::InliningStrategy; use cairo_lang_starknet::compile::compile_path; use cairo_native::{ context::NativeContext, executor::JitNativeExecutor, starknet::{ BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point, StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256, }, utils::find_entry_point_by_idx, }; use starknet_types_core::felt::Felt; use std::path::Path; use tracing_subscriber::{EnvFilter, FmtSubscriber}; #[derive(Debug)] struct SyscallHandler; impl StarknetSyscallHandler for SyscallHandler { fn get_block_hash(&mut self, block_number: u64, _gas: &mut u64) -> SyscallResult<Felt> { println!("Called `get_block_hash({block_number})` from MLIR."); Ok(Felt::from_bytes_be_slice(b"get_block_hash ok")) } fn get_execution_info( &mut self, _gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfo> { println!("Called `get_execution_info()` from MLIR."); Ok(ExecutionInfo { block_info: BlockInfo { block_number: 1234, block_timestamp: 2345, sequencer_address: 3456.into(), }, tx_info: TxInfo { version: 4567.into(), account_contract_address: 5678.into(), max_fee: 6789, signature: vec![1248.into(), 2486.into()], transaction_hash: 9876.into(), chain_id: 8765.into(), nonce: 7654.into(), }, caller_address: 6543.into(), contract_address: 5432.into(), entry_point_selector: 4321.into(), }) } fn get_execution_info_v2( &mut self, _remaining_gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfoV2> { println!("Called `get_execution_info_v2()` from MLIR."); Ok(ExecutionInfoV2 { block_info: BlockInfo { block_number: 1234, block_timestamp: 2345, sequencer_address: 3456.into(), }, tx_info: TxV2Info { version: 1.into(), account_contract_address: 1.into(), max_fee: 0, signature: vec![1.into()], transaction_hash: 1.into(), chain_id: 1.into(), nonce: 1.into(), tip: 1, paymaster_data: vec![1.into()], nonce_data_availability_mode: 0, fee_data_availability_mode: 0, account_deployment_data: vec![1.into()], resource_bounds: vec![ResourceBounds { resource: 2.into(), max_amount: 10, max_price_per_unit: 20, }], }, caller_address: 6543.into(), contract_address: 5432.into(), entry_point_selector: 4321.into(), }) } fn get_execution_info_v3( &mut self, _remaining_gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::ExecutionInfoV3> { println!("Called `get_execution_info_v3()` from MLIR."); todo!(); } fn deploy( &mut self, class_hash: Felt, contract_address_salt: Felt, calldata: &[Felt], deploy_from_zero: bool, _gas: &mut u64, ) -> SyscallResult<(Felt, Vec<Felt>)> { println!("Called `deploy({class_hash}, {contract_address_salt}, {calldata:?}, {deploy_from_zero})` from MLIR."); Ok(( class_hash + contract_address_salt, calldata.iter().map(|x| x + Felt::ONE).collect(), )) } fn replace_class(&mut self, class_hash: Felt, _gas: &mut u64) -> SyscallResult<()> { println!("Called `replace_class({class_hash})` from MLIR."); Ok(()) } fn library_call( &mut self, class_hash: Felt, function_selector: Felt, calldata: &[Felt], _gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { println!( "Called `library_call({class_hash}, {function_selector}, {calldata:?})` from MLIR." ); Ok(calldata.iter().map(|x| x * Felt::from(3)).collect()) } fn call_contract( &mut self, address: Felt, entry_point_selector: Felt, calldata: &[Felt], _gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { println!( "Called `call_contract({address}, {entry_point_selector}, {calldata:?})` from MLIR." ); Ok(calldata.iter().map(|x| x * Felt::from(3)).collect()) } fn storage_read( &mut self, address_domain: u32, address: Felt, _gas: &mut u64, ) -> SyscallResult<Felt> { println!("Called `storage_read({address_domain}, {address})` from MLIR."); Ok(address * Felt::from(3)) } fn storage_write( &mut self, address_domain: u32, address: Felt, value: Felt, _gas: &mut u64, ) -> SyscallResult<()> { println!("Called `storage_write({address_domain}, {address}, {value})` from MLIR."); Ok(()) } fn emit_event(&mut self, keys: &[Felt], data: &[Felt], _gas: &mut u64) -> SyscallResult<()> { println!("Called `emit_event({keys:?}, {data:?})` from MLIR."); Ok(()) } fn send_message_to_l1( &mut self, to_address: Felt, payload: &[Felt], _gas: &mut u64, ) -> SyscallResult<()> { println!("Called `send_message_to_l1({to_address}, {payload:?})` from MLIR."); Ok(()) } fn keccak( &mut self, input: &[u64], _gas: &mut u64, ) -> SyscallResult<cairo_native::starknet::U256> { println!("Called `keccak({input:?})` from MLIR."); Ok(U256 { hi: 0, lo: 1234567890, }) } fn secp256k1_new( &mut self, _x: U256, _y: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256k1Point>> { unimplemented!() } fn secp256k1_add( &mut self, _p0: Secp256k1Point, _p1: Secp256k1Point, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256k1Point> { unimplemented!() } fn secp256k1_mul( &mut self, _p: Secp256k1Point, _m: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256k1Point> { unimplemented!() } fn secp256k1_get_point_from_x( &mut self, _x: U256, _y_parity: bool, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256k1Point>> { unimplemented!() } fn secp256k1_get_xy( &mut self, _p: Secp256k1Point, _remaining_gas: &mut u64, ) -> SyscallResult<(U256, U256)> { unimplemented!() } fn secp256r1_new( &mut self, _x: U256, _y: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256r1Point>> { unimplemented!() } fn secp256r1_add( &mut self, _p0: Secp256r1Point, _p1: Secp256r1Point, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256r1Point> { unimplemented!() } fn secp256r1_mul( &mut self, _p: Secp256r1Point, _m: U256, _remaining_gas: &mut u64, ) -> SyscallResult<Secp256r1Point> { unimplemented!() } fn secp256r1_get_point_from_x( &mut self, _x: U256, _y_parity: bool, _remaining_gas: &mut u64, ) -> SyscallResult<Option<Secp256r1Point>> { unimplemented!() } fn secp256r1_get_xy( &mut self, _p: Secp256r1Point, _remaining_gas: &mut u64, ) -> SyscallResult<(U256, U256)> { unimplemented!() } fn sha256_process_block( &mut self, _state: &mut [u32; 8], _block: &[u32; 16], _remaining_gas: &mut u64, ) -> SyscallResult<()> { unimplemented!() } fn get_class_hash_at( &mut self, _contract_address: Felt, _remaining_gas: &mut u64, ) -> SyscallResult<Felt> { unimplemented!() } fn meta_tx_v0( &mut self, _address: Felt, _entry_point_selector: Felt, _calldata: &[Felt], _signature: &[Felt], _remaining_gas: &mut u64, ) -> SyscallResult<Vec<Felt>> { unimplemented!() } } fn main() { // Configure logging and error handling. tracing::subscriber::set_global_default( FmtSubscriber::builder() .with_env_filter(EnvFilter::from_default_env()) .finish(), ) .unwrap(); let path = Path::new("programs/erc20.cairo"); let contract = compile_path( path, None, CompilerConfig { replace_ids: true, ..Default::default() }, InliningStrategy::Default, ) .unwrap(); let entry_point = contract.entry_points_by_type.constructor.first().unwrap(); let sierra_program = contract.extract_sierra_program().unwrap(); let native_context = NativeContext::new(); let native_program = native_context .compile(&sierra_program, false, Some(Default::default()), None) .unwrap(); let entry_point_fn = find_entry_point_by_idx(&sierra_program, entry_point.function_idx).unwrap(); let fn_id = &entry_point_fn.id; let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default()).unwrap(); let result = native_executor .invoke_contract_dynamic( fn_id, &[ Felt::from_bytes_be_slice(b"name"), Felt::from_bytes_be_slice(b"symbol"), Felt::ZERO, Felt::from(i64::MAX), Felt::from(4), Felt::from(6), ], Some(u64::MAX), SyscallHandler, ) .expect("failed to execute the given contract"); println!(); println!("Cairo program was compiled and executed successfully."); println!("{result:#?}"); }
rust
Apache-2.0
f0a4fdbbad8a1730dea3b20c0b2ea140b9b853ce
2026-01-04T20:20:54.031924Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/build.rs
build.rs
#[cfg(feature = "serialization-protobuf")] extern crate protoc_rust; #[cfg(feature = "serialization-protobuf")] fn has_right_protoc_version(version: &str) -> bool { use std::process::{Command, Stdio}; let protoc = Command::new("protoc") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .args(&["--version"]) .spawn() .unwrap(); let version_output = protoc.wait_with_output().unwrap(); assert!(version_output.status.success()); let full_version = String::from_utf8(version_output.stdout).unwrap(); full_version.trim() == format!("libprotoc {}", version.trim()) } #[cfg(feature = "serialization-protobuf")] fn build_protobuf(out_dir: &str, input: &[&str], includes: &[&str]) { protoc_rust::Codegen::new() .out_dir(out_dir) .inputs(input) .includes(includes) .run() .expect("Running protoc failed"); } #[cfg(feature = "serialization-protobuf")] fn build_protobuf_schemata() { use std::fs::File; use std::io::Read; let mut version_string = String::new(); let mut version_pin = File::open("PROTOC_VERSION").expect("protoc version pin `PROTOC_VERSION` file is missing"); version_pin .read_to_string(&mut version_string) .expect("cannot read protoc pin file"); if !has_right_protoc_version(&version_string) { eprintln!( "Build failed because merkle.rs could not find protobuf version {}", version_string ); std::process::exit(1); } build_protobuf("src/proto", &["protobuf/proof.proto"], &[]); } fn main() { #[cfg(feature = "serialization-protobuf")] build_protobuf_schemata(); }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/proof.rs
src/proof.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::HashUtils; use crate::tree::Tree; /// An inclusion proof represent the fact that a `value` is a member /// of a `MerkleTree` with root hash `root_hash`, and hash function `algorithm`. #[cfg_attr(feature = "serialization-serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub struct Proof<T> { /// The hashing algorithm used in the original `MerkleTree` #[cfg_attr(feature = "serialization-serde", serde(with = "algorithm_serde"))] pub algorithm: &'static Algorithm, /// The hash of the root of the original `MerkleTree` pub root_hash: Vec<u8>, /// The first `Lemma` of the `Proof` pub lemma: Lemma, /// The value concerned by this `Proof` pub value: T, } #[cfg(feature = "serialization-serde")] mod algorithm_serde { use ring::digest::{self, Algorithm}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub fn serialize<S: Serializer>( algorithm: &'static Algorithm, se: S, ) -> Result<S::Ok, S::Error> { // The `Debug` implementation of `Algorithm` prints its ID. format!("{:?}", algorithm).serialize(se) } pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<&'static Algorithm, D::Error> { let alg_str: String = Deserialize::deserialize(de)?; match &*alg_str { "SHA1" => Ok(&digest::SHA1_FOR_LEGACY_USE_ONLY), "SHA256" => Ok(&digest::SHA256), "SHA384" => Ok(&digest::SHA384), "SHA512" => Ok(&digest::SHA512), "SHA512_256" => Ok(&digest::SHA512_256), _ => Err(D::Error::custom("unknown hash algorithm")), } } #[cfg(test)] mod test { use super::*; use ring::digest::{ SHA1_FOR_LEGACY_USE_ONLY as sha1, SHA256 as sha256, SHA384 as sha384, SHA512 as sha512, SHA512_256 as sha512_256, }; static SHA1: &Algorithm = &sha1; static SHA256: &Algorithm = &sha256; static SHA384: &Algorithm = &sha384; static SHA512: &Algorithm = &sha512; static SHA512_256: &Algorithm = &sha512_256; #[test] fn test_serialize_known_algorithms() { extern crate serde_json; for alg in &[SHA1, SHA256, SHA384, SHA512, SHA512_256] { let mut serializer = serde_json::Serializer::with_formatter( vec![], serde_json::ser::PrettyFormatter::new(), ); serialize(alg, &mut serializer).unwrap_or_else(|_| panic!("{:?}", alg)); let alg_ = deserialize(&mut serde_json::Deserializer::from_slice( &serializer.into_inner()[..], )) .unwrap_or_else(|_| panic!("{:?}", alg)); assert_eq!(*alg, alg_); } } #[test] #[should_panic(expected = "unknown hash algorithm")] fn test_serialize_unknown_algorithm() { extern crate serde_json; { let alg_str = "\"BLAKE2b\""; let mut deserializer = serde_json::Deserializer::from_str(alg_str); let _ = deserialize(&mut deserializer) .unwrap_or_else(|_| panic!("unknown hash algorithm {:?}", alg_str)); } } } } impl<T: PartialEq> PartialEq for Proof<T> { fn eq(&self, other: &Proof<T>) -> bool { self.root_hash == other.root_hash && self.lemma == other.lemma && self.value == other.value } } impl<T: Eq> Eq for Proof<T> {} impl<T: Ord> PartialOrd for Proof<T> { fn partial_cmp(&self, other: &Proof<T>) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T: Ord> Ord for Proof<T> { fn cmp(&self, other: &Proof<T>) -> Ordering { self.root_hash .cmp(&other.root_hash) .then(self.value.cmp(&other.value)) .then_with(|| self.lemma.cmp(&other.lemma)) } } impl<T: Hash> Hash for Proof<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.root_hash.hash(state); self.lemma.hash(state); self.value.hash(state); } } impl<T> Proof<T> { /// Constructs a new `Proof` pub fn new(algorithm: &'static Algorithm, root_hash: Vec<u8>, lemma: Lemma, value: T) -> Self { Proof { algorithm, root_hash, lemma, value, } } /// Checks whether this inclusion proof is well-formed, /// and whether its root hash matches the given `root_hash`. pub fn validate(&self, root_hash: &[u8]) -> bool { if self.root_hash != root_hash || self.lemma.node_hash != root_hash { return false; } self.lemma.validate(self.algorithm) } /// Returns the index of this proof's value, given the total number of items in the tree. /// /// # Panics /// /// Panics if the proof is malformed. Call `validate` first. pub fn index(&self, count: usize) -> usize { self.lemma.index(count) } } /// A `Lemma` holds the hash of a node, the hash of its sibling node, /// and a sub lemma, whose `node_hash`, when combined with this `sibling_hash` /// must be equal to this `node_hash`. #[cfg_attr(feature = "serialization-serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Lemma { pub node_hash: Vec<u8>, pub sibling_hash: Option<Positioned<Vec<u8>>>, pub sub_lemma: Option<Box<Lemma>>, } impl Lemma { /// Attempts to generate a proof that the a value with hash `needle` is a /// member of the given `tree`. pub fn new<T>(tree: &Tree<T>, needle: &[u8]) -> Option<Lemma> { match *tree { Tree::Empty { .. } => None, Tree::Leaf { ref hash, .. } => Lemma::new_leaf_proof(hash, needle), Tree::Node { ref hash, ref left, ref right, } => Lemma::new_tree_proof(hash, needle, left, right), } } /// Attempts to generate a proof that the `idx`-th leaf is a member of /// the given tree. The `count` must equal the number of leaves in the /// `tree`. If `idx >= count`, `None` is returned. Otherwise it returns /// the new `Lemma` and the `idx`-th value. pub fn new_by_index<T>(tree: &Tree<T>, idx: usize, count: usize) -> Option<(Lemma, &T)> { if idx >= count { return None; } match *tree { Tree::Empty { .. } => None, Tree::Leaf { ref hash, ref value, .. } => { if count != 1 { return None; } let lemma = Lemma { node_hash: hash.clone(), sibling_hash: None, sub_lemma: None, }; Some((lemma, value)) } Tree::Node { ref hash, ref left, ref right, } => { let left_count = count.next_power_of_two() / 2; let (sub_lem_val, sibling_hash); if idx < left_count { sub_lem_val = Lemma::new_by_index(left, idx, left_count); sibling_hash = Positioned::Right(right.hash().clone()); } else { sub_lem_val = Lemma::new_by_index(right, idx - left_count, count - left_count); sibling_hash = Positioned::Left(left.hash().clone()); } sub_lem_val.map(|(sub_lemma, value)| { let lemma = Lemma { node_hash: hash.clone(), sibling_hash: Some(sibling_hash), sub_lemma: Some(Box::new(sub_lemma)), }; (lemma, value) }) } } } /// Returns the index of this lemma's value, given the total number of items in the tree. /// /// # Panics /// /// Panics if the lemma is malformed. Call `validate_lemma` first. pub fn index(&self, count: usize) -> usize { let left_count = count.next_power_of_two() / 2; match (self.sub_lemma.as_ref(), self.sibling_hash.as_ref()) { (None, None) => 0, (Some(l), Some(&Positioned::Left(_))) => left_count + l.index(count - left_count), (Some(l), Some(&Positioned::Right(_))) => l.index(left_count), (None, Some(_)) | (Some(_), None) => panic!("malformed lemma"), } } fn new_leaf_proof(hash: &[u8], needle: &[u8]) -> Option<Lemma> { if *hash == *needle { Some(Lemma { node_hash: hash.into(), sibling_hash: None, sub_lemma: None, }) } else { None } } fn new_tree_proof<T>( hash: &[u8], needle: &[u8], left: &Tree<T>, right: &Tree<T>, ) -> Option<Lemma> { Lemma::new(left, needle) .map(|lemma| { let right_hash = right.hash().clone(); let sub_lemma = Some(Positioned::Right(right_hash)); (lemma, sub_lemma) }) .or_else(|| { let sub_lemma = Lemma::new(right, needle); sub_lemma.map(|lemma| { let left_hash = left.hash().clone(); let sub_lemma = Some(Positioned::Left(left_hash)); (lemma, sub_lemma) }) }) .map(|(sub_lemma, sibling_hash)| Lemma { node_hash: hash.into(), sibling_hash, sub_lemma: Some(Box::new(sub_lemma)), }) } fn validate(&self, algorithm: &'static Algorithm) -> bool { match self.sub_lemma { None => self.sibling_hash.is_none(), Some(ref sub) => match self.sibling_hash { None => false, Some(Positioned::Left(ref hash)) => { let combined = algorithm.hash_nodes(hash, &sub.node_hash); let hashes_match = combined.as_ref() == self.node_hash.as_slice(); hashes_match && sub.validate(algorithm) } Some(Positioned::Right(ref hash)) => { let combined = algorithm.hash_nodes(&sub.node_hash, hash); let hashes_match = combined.as_ref() == self.node_hash.as_slice(); hashes_match && sub.validate(algorithm) } }, } } } /// Tags a value so that we know from which branch of a `Tree` (if any) it was found. #[cfg_attr(feature = "serialization-serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Positioned<T> { /// The value was found in the left branch Left(T), /// The value was found in the right branch Right(T), }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/merkletree.rs
src/merkletree.rs
use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use ring::digest::Algorithm; use crate::hashutils::{HashUtils, Hashable}; use crate::tree::{LeavesIntoIterator, LeavesIterator, Tree}; use crate::proof::{Lemma, Proof}; /// A Merkle tree is a binary tree, with values of type `T` at the leafs, /// and where every internal node holds the hash of the concatenation of the hashes of its children nodes. #[derive(Clone, Debug)] pub struct MerkleTree<T> { /// The hashing algorithm used by this Merkle tree pub algorithm: &'static Algorithm, /// The root of the inner binary tree root: Tree<T>, /// The height of the tree height: usize, /// The number of leaf nodes in the tree count: usize, } impl<T: PartialEq> PartialEq for MerkleTree<T> { #[allow(trivial_casts)] fn eq(&self, other: &MerkleTree<T>) -> bool { self.root == other.root && self.height == other.height && self.count == other.count && (self.algorithm as *const Algorithm) == (other.algorithm as *const Algorithm) } } impl<T: Eq> Eq for MerkleTree<T> {} impl<T: Ord> PartialOrd for MerkleTree<T> { fn partial_cmp(&self, other: &MerkleTree<T>) -> Option<Ordering> { Some(self.cmp(other)) } } impl<T: Ord> Ord for MerkleTree<T> { #[allow(trivial_casts)] fn cmp(&self, other: &MerkleTree<T>) -> Ordering { self.height .cmp(&other.height) .then(self.count.cmp(&other.count)) .then((self.algorithm as *const Algorithm).cmp(&(other.algorithm as *const Algorithm))) .then_with(|| self.root.cmp(&other.root)) } } impl<T: Hash> Hash for MerkleTree<T> { #[allow(trivial_casts)] fn hash<H: Hasher>(&self, state: &mut H) { <Tree<T> as Hash>::hash(&self.root, state); self.height.hash(state); self.count.hash(state); (self.algorithm as *const Algorithm).hash(state); } } impl<T> MerkleTree<T> { /// Constructs a Merkle Tree from a vector of data blocks. /// Returns `None` if `values` is empty. pub fn from_vec(algorithm: &'static Algorithm, values: Vec<T>) -> Self where T: Hashable, { if values.is_empty() { return MerkleTree { algorithm, root: Tree::empty(algorithm.hash_empty()), height: 0, count: 0, }; } let count = values.len(); let mut height = 0; let mut cur = Vec::with_capacity(count); for v in values { let leaf = Tree::new_leaf(algorithm, v); cur.push(leaf); } while cur.len() > 1 { let mut next = Vec::new(); while !cur.is_empty() { if cur.len() == 1 { next.push(cur.remove(0)); } else { let left = cur.remove(0); let right = cur.remove(0); let combined_hash = algorithm.hash_nodes(left.hash(), right.hash()); let node = Tree::Node { hash: combined_hash.as_ref().into(), left: Box::new(left), right: Box::new(right), }; next.push(node); } } height += 1; cur = next; } debug_assert!(cur.len() == 1); let root = cur.remove(0); MerkleTree { algorithm, root, height, count, } } /// Returns the root hash of Merkle tree pub fn root_hash(&self) -> &Vec<u8> { self.root.hash() } /// Returns the height of Merkle tree pub fn height(&self) -> usize { self.height } /// Returns the number of leaves in the Merkle tree pub fn count(&self) -> usize { self.count } /// Returns whether the Merkle tree is empty or not pub fn is_empty(&self) -> bool { self.count() == 0 } /// Generate an inclusion proof for the given value. /// Returns `None` if the given value is not found in the tree. pub fn gen_proof(&self, value: T) -> Option<Proof<T>> where T: Hashable, { let root_hash = self.root_hash().clone(); let leaf_hash = self.algorithm.hash_leaf(&value); Lemma::new(&self.root, leaf_hash.as_ref()) .map(|lemma| Proof::new(self.algorithm, root_hash, lemma, value)) } /// Generate an inclusion proof for the `n`-th leaf value. pub fn gen_nth_proof(&self, n: usize) -> Option<Proof<T>> where T: Hashable + Clone, { let root_hash = self.root_hash().clone(); Lemma::new_by_index(&self.root, n, self.count) .map(|(lemma, value)| Proof::new(self.algorithm, root_hash, lemma, value.clone())) } /// Creates an `Iterator` over the values contained in this Merkle tree. pub fn iter(&self) -> LeavesIterator<T> { self.root.iter() } } impl<T> IntoIterator for MerkleTree<T> { type Item = T; type IntoIter = LeavesIntoIterator<T>; /// Creates a consuming iterator, that is, one that moves each value out of the Merkle tree. /// The tree cannot be used after calling this. fn into_iter(self) -> Self::IntoIter { self.root.into_iter() } } impl<'a, T> IntoIterator for &'a MerkleTree<T> { type Item = &'a T; type IntoIter = LeavesIterator<'a, T>; /// Creates a borrowing `Iterator` over the values contained in this Merkle tree. fn into_iter(self) -> Self::IntoIter { self.root.iter() } }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/lib.rs
src/lib.rs
#![deny( missing_docs, unused_qualifications, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces )] //! *merkle* implements a Merkle Tree in Rust. extern crate ring; #[cfg(feature = "serialization-protobuf")] extern crate protobuf; #[cfg(feature = "serialization-serde")] extern crate serde; #[cfg(feature = "serialization-serde")] #[macro_use] extern crate serde_derive; mod merkletree; pub use crate::merkletree::MerkleTree; mod proof; pub use crate::proof::Proof; mod hashutils; pub use crate::hashutils::Hashable; mod tree; pub use crate::tree::{LeavesIntoIterator, LeavesIterator}; #[cfg(feature = "serialization-protobuf")] #[allow(unused_qualifications)] mod proto; #[cfg(test)] mod tests;
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/tests.rs
src/tests.rs
#![cfg(test)] #[cfg(feature = "serialization-serde")] extern crate serde_json; use ring::digest::{Algorithm, Context, SHA512}; use crate::hashutils::{HashUtils, Hashable}; use crate::merkletree::MerkleTree; use crate::proof::Positioned; static DIGEST: &Algorithm = &SHA512; #[test] fn test_from_str_vec() { let values = vec!["one", "two", "three", "four"]; let hashes = vec![ DIGEST.hash_leaf(&values[0].as_bytes()), DIGEST.hash_leaf(&values[1].as_bytes()), DIGEST.hash_leaf(&values[2].as_bytes()), DIGEST.hash_leaf(&values[3].as_bytes()), ]; let count = values.len(); let tree = MerkleTree::from_vec(DIGEST, values); let h01 = DIGEST.hash_nodes(&hashes[0], &hashes[1]); let h23 = DIGEST.hash_nodes(&hashes[2], &hashes[3]); let root_hash = DIGEST.hash_nodes(&h01, &h23); assert_eq!(tree.count(), count); assert_eq!(tree.height(), 2); assert_eq!(tree.root_hash().as_slice(), root_hash.as_ref()); } #[test] fn test_from_vec_empty() { let values: Vec<Vec<u8>> = vec![]; let tree = MerkleTree::from_vec(DIGEST, values); let empty_hash: Vec<u8> = DIGEST.hash_empty().as_ref().into(); let root_hash = tree.root_hash().clone(); assert_eq!(root_hash, empty_hash); } #[test] fn test_from_vec1() { let values = vec!["hello, world".to_string()]; let tree = MerkleTree::from_vec(DIGEST, values); let root_hash = &DIGEST.hash_leaf(b"hello, world"); assert_eq!(tree.count(), 1); assert_eq!(tree.height(), 0); assert_eq!(tree.root_hash().as_slice(), root_hash.as_ref()); } #[test] fn test_from_vec3() { let values = vec![vec![1], vec![2], vec![3]]; let tree = MerkleTree::from_vec(DIGEST, values); let hashes = vec![ DIGEST.hash_leaf(&vec![1]), DIGEST.hash_leaf(&vec![2]), DIGEST.hash_leaf(&vec![3]), ]; let h01 = DIGEST.hash_nodes(&hashes[0], &hashes[1]); let h2 = &hashes[2]; let root_hash = &DIGEST.hash_nodes(&h01, h2); assert_eq!(tree.count(), 3); assert_eq!(tree.height(), 2); assert_eq!(tree.root_hash().as_slice(), root_hash.as_ref()); } #[test] fn test_from_vec9() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let hashes = values .iter() .map(|v| DIGEST.hash_leaf(v)) .collect::<Vec<_>>(); let h01 = DIGEST.hash_nodes(&hashes[0], &hashes[1]); let h23 = DIGEST.hash_nodes(&hashes[2], &hashes[3]); let h45 = DIGEST.hash_nodes(&hashes[4], &hashes[5]); let h67 = DIGEST.hash_nodes(&hashes[6], &hashes[7]); let h8 = &hashes[8]; let h0123 = DIGEST.hash_nodes(&h01, &h23); let h4567 = DIGEST.hash_nodes(&h45, &h67); let h1to7 = DIGEST.hash_nodes(&h0123, &h4567); let root_hash = &DIGEST.hash_nodes(&h1to7, h8); assert_eq!(tree.count(), 9); assert_eq!(tree.height(), 4); assert_eq!(tree.root_hash().as_slice(), root_hash.as_ref()); } #[test] fn test_valid_proof() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let root_hash = tree.root_hash(); for value in values { let proof = tree.gen_proof(value); let is_valid = proof.map(|p| p.validate(&root_hash)).unwrap_or(false); assert!(is_valid); } } #[test] fn test_valid_proof_str() { let values = vec!["Hello", "my", "name", "is", "Rusty"]; let tree = MerkleTree::from_vec(DIGEST, values); let root_hash = tree.root_hash(); let value = "Rusty"; let proof = tree.gen_proof(&value); let is_valid = proof.map(|p| p.validate(&root_hash)).unwrap_or(false); assert!(is_valid); } #[test] fn test_wrong_proof() { let values1 = vec![vec![1], vec![2], vec![3], vec![4]]; let tree1 = MerkleTree::from_vec(DIGEST, values1.clone()); let values2 = vec![vec![4], vec![5], vec![6], vec![7]]; let tree2 = MerkleTree::from_vec(DIGEST, values2); let root_hash = tree2.root_hash(); for value in values1 { let proof = tree1.gen_proof(value); let is_valid = proof.map(|p| p.validate(root_hash)).unwrap_or(false); assert_eq!(is_valid, false); } } #[test] fn test_nth_proof() { // Calculation depends on the total count. Try a few numbers: odd, even, powers of two... for &count in &[1, 2, 3, 10, 15, 16, 17, 22] { let values = (1..=count).map(|x| vec![x as u8]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let root_hash = tree.root_hash(); for i in 0..count { let proof = tree.gen_nth_proof(i).expect("gen proof by index"); assert_eq!(vec![i as u8 + 1], proof.value); assert!(proof.validate(&root_hash)); assert_eq!(i, proof.index(tree.count())); } assert!(tree.gen_nth_proof(count).is_none()); assert!(tree.gen_nth_proof(count + 1000).is_none()); } } #[test] fn test_mutate_proof_first_lemma() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let root_hash = tree.root_hash(); for (i, value) in values.into_iter().enumerate() { let mut proof = tree.gen_proof(value).unwrap(); match i % 3 { 0 => { proof.lemma.node_hash = vec![1, 2, 3]; } 1 => { proof.lemma.sibling_hash = Some(Positioned::Left(vec![1, 2, 3])); } _ => { proof.lemma.sibling_hash = Some(Positioned::Right(vec![1, 2, 3])); } } let is_valid = proof.validate(root_hash); assert_eq!(is_valid, false); } } #[test] fn test_tree_iter() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let iter = tree.iter().cloned().collect::<Vec<_>>(); assert_eq!(values, iter); } #[test] fn test_tree_into_iter() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let iter = tree.into_iter().collect::<Vec<_>>(); assert_eq!(values, iter); } #[test] fn test_tree_into_iter_loop() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let mut collected = Vec::new(); for value in tree { collected.push(value); } assert_eq!(values, collected); } #[test] fn test_tree_into_iter_loop_borrow() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values.clone()); let mut collected = Vec::new(); for value in &tree { collected.push(value); } let refs = values.iter().collect::<Vec<_>>(); assert_eq!(refs, collected); } pub struct PublicKey { zero_values: Vec<Vec<u8>>, one_values: Vec<Vec<u8>>, } impl PublicKey { pub fn new(zero_values: Vec<Vec<u8>>, one_values: Vec<Vec<u8>>) -> Self { PublicKey { zero_values, one_values, } } pub fn to_bytes(&self) -> Vec<u8> { self.zero_values .iter() .chain(self.one_values.iter()) .fold(Vec::new(), |mut acc, i| { acc.append(&mut i.clone()); acc }) } } impl Hashable for PublicKey { fn update_context(&self, context: &mut Context) { context.update(&self.to_bytes()); } } #[test] fn test_custom_hashable_impl() { let keys = (0..10) .map(|i| { let zero_values = vec![vec![i], vec![i + 1], vec![i + 2]]; let one_values = vec![vec![i + 3], vec![i + 4], vec![i + 5]]; PublicKey::new(zero_values, one_values) }) .collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, keys); assert_eq!(tree.count(), 10); assert_eq!(tree.height(), 4); } #[cfg(feature = "serialization-serde")] #[test] fn test_serialize_proof_with_serde() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(DIGEST, values); let proof = tree.gen_proof(vec![5]); let serialized = serde_json::to_string(&proof).expect("serialize proof"); assert_eq!( proof, serde_json::from_str(&serialized).expect("deserialize proof") ); }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/tree.rs
src/tree.rs
use ring::digest::{Algorithm, Digest}; use crate::hashutils::{HashUtils, Hashable}; pub use crate::proof::{Lemma, Positioned, Proof}; /// Binary Tree where leaves hold a stand-alone value. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Tree<T> { Empty { hash: Vec<u8>, }, Leaf { hash: Vec<u8>, value: T, }, Node { hash: Vec<u8>, left: Box<Tree<T>>, right: Box<Tree<T>>, }, } impl<T> Tree<T> { /// Create an empty tree pub fn empty(hash: Digest) -> Self { Tree::Empty { hash: hash.as_ref().into(), } } /// Create a new tree pub fn new(hash: Digest, value: T) -> Self { Tree::Leaf { hash: hash.as_ref().into(), value, } } /// Create a new leaf pub fn new_leaf(algo: &'static Algorithm, value: T) -> Tree<T> where T: Hashable, { let hash = algo.hash_leaf(&value); Tree::new(hash, value) } /// Returns a hash from the tree. pub fn hash(&self) -> &Vec<u8> { match *self { Tree::Empty { ref hash } => hash, Tree::Leaf { ref hash, .. } => hash, Tree::Node { ref hash, .. } => hash, } } /// Returns a borrowing iterator over the leaves of the tree. pub fn iter(&self) -> LeavesIterator<T> { LeavesIterator::new(self) } } /// An borrowing iterator over the leaves of a `Tree`. /// Adapted from http://codereview.stackexchange.com/q/110283. #[allow(missing_debug_implementations)] pub struct LeavesIterator<'a, T> where T: 'a, { current_value: Option<&'a T>, right_nodes: Vec<&'a Tree<T>>, } impl<'a, T> LeavesIterator<'a, T> { fn new(root: &'a Tree<T>) -> Self { let mut iter = LeavesIterator { current_value: None, right_nodes: Vec::new(), }; iter.add_left(root); iter } fn add_left(&mut self, mut tree: &'a Tree<T>) { loop { match *tree { Tree::Empty { .. } => { self.current_value = None; break; } Tree::Node { ref left, ref right, .. } => { self.right_nodes.push(right); tree = left; } Tree::Leaf { ref value, .. } => { self.current_value = Some(value); break; } } } } } impl<'a, T> Iterator for LeavesIterator<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<&'a T> { let result = self.current_value.take(); if let Some(rest) = self.right_nodes.pop() { self.add_left(rest); } result } } /// An iterator over the leaves of a `Tree`. #[allow(missing_debug_implementations)] pub struct LeavesIntoIterator<T> { current_value: Option<T>, right_nodes: Vec<Tree<T>>, } impl<T> LeavesIntoIterator<T> { fn new(root: Tree<T>) -> Self { let mut iter = LeavesIntoIterator { current_value: None, right_nodes: Vec::new(), }; iter.add_left(root); iter } fn add_left(&mut self, mut tree: Tree<T>) { loop { match tree { Tree::Empty { .. } => { self.current_value = None; break; } Tree::Node { left, right, .. } => { self.right_nodes.push(*right); tree = *left; } Tree::Leaf { value, .. } => { self.current_value = Some(value); break; } } } } } impl<T> Iterator for LeavesIntoIterator<T> { type Item = T; fn next(&mut self) -> Option<T> { let result = self.current_value.take(); if let Some(rest) = self.right_nodes.pop() { self.add_left(rest); } result } } impl<T> IntoIterator for Tree<T> { type Item = T; type IntoIter = LeavesIntoIterator<T>; fn into_iter(self) -> Self::IntoIter { LeavesIntoIterator::new(self) } }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/hashutils.rs
src/hashutils.rs
use ring::digest::{digest, Algorithm, Context, Digest}; /// The type of values stored in a `MerkleTree` must implement /// this trait, in order for them to be able to be fed /// to a Ring `Context` when computing the hash of a leaf. /// /// A default instance for types that already implements /// `AsRef<[u8]>` is provided. /// /// ## Example /// /// Here is an example of how to implement `Hashable` for a type /// that does not (or cannot) implement `AsRef<[u8]>`: /// /// ```ignore /// impl Hashable for PublicKey { /// fn update_context(&self, context: &mut Context) { /// let bytes: Vec<u8> = self.to_bytes(); /// context.update(&bytes); /// } /// } /// ``` pub trait Hashable { /// Update the given `context` with `self`. /// /// See `ring::digest::Context::update` for more information. fn update_context(&self, context: &mut Context); } impl<T: AsRef<[u8]>> Hashable for T { fn update_context(&self, context: &mut Context) { context.update(self.as_ref()); } } /// The sole purpose of this trait is to extend the standard /// `ring::algo::Algorithm` type with a couple utility functions. pub trait HashUtils { /// Compute the hash of the empty string fn hash_empty(&'static self) -> Digest; /// Compute the hash of the given leaf fn hash_leaf<T>(&'static self, bytes: &T) -> Digest where T: Hashable; /// Compute the hash of the concatenation of `left` and `right`. // XXX: This is overly generic temporarily to make refactoring easier. // TODO: Give `left` and `right` type &Digest. fn hash_nodes<T>(&'static self, left: &T, right: &T) -> Digest where T: Hashable; } impl HashUtils for Algorithm { fn hash_empty(&'static self) -> Digest { digest(self, &[]) } fn hash_leaf<T>(&'static self, leaf: &T) -> Digest where T: Hashable, { let mut ctx = Context::new(self); ctx.update(&[0x00]); leaf.update_context(&mut ctx); ctx.finish() } fn hash_nodes<T>(&'static self, left: &T, right: &T) -> Digest where T: Hashable, { let mut ctx = Context::new(self); ctx.update(&[0x01]); left.update_context(&mut ctx); right.update_context(&mut ctx); ctx.finish() } }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/src/proto/mod.rs
src/proto/mod.rs
#[allow(missing_debug_implementations)] mod proof; use ring::digest::Algorithm; use protobuf::error::ProtobufResult; use protobuf::parse_from_bytes; use crate::proof::{Lemma, Positioned, Proof}; use crate::protobuf::Message; pub use self::proof::{LemmaProto, ProofProto}; impl<T> Proof<T> { /// Constructs a `Proof` struct from its Protobuf representation. pub fn from_protobuf(algorithm: &'static Algorithm, proto: ProofProto) -> Option<Self> where T: From<Vec<u8>>, { proto.into_proof(algorithm) } /// Encode this `Proof` to its Protobuf representation. pub fn into_protobuf(self) -> ProofProto where T: Into<Vec<u8>>, { ProofProto::from_proof(self) } /// Parse a `Proof` from its Protobuf binary representation. pub fn parse_from_bytes( bytes: &[u8], algorithm: &'static Algorithm, ) -> ProtobufResult<Option<Self>> where T: From<Vec<u8>>, { parse_from_bytes::<ProofProto>(bytes).map(|proto| proto.into_proof(algorithm)) } /// Serialize this `Proof` with Protobuf. pub fn write_to_bytes(self) -> ProtobufResult<Vec<u8>> where T: Into<Vec<u8>>, { self.into_protobuf().write_to_bytes() } } impl ProofProto { pub fn from_proof<T>(proof: Proof<T>) -> Self where T: Into<Vec<u8>>, { let mut proto = Self::new(); match proof { Proof { root_hash, lemma, value, .. } => { proto.set_root_hash(root_hash); proto.set_lemma(LemmaProto::from_lemma(lemma)); proto.set_value(value.into()); } } proto } pub fn into_proof<T>(mut self, algorithm: &'static Algorithm) -> Option<Proof<T>> where T: From<Vec<u8>>, { if self.root_hash.is_empty() || !self.has_lemma() { return None; } self.take_lemma().into_lemma().map(|lemma| { Proof::new( algorithm, self.take_root_hash(), lemma, self.take_value().into(), ) }) } } impl LemmaProto { pub fn from_lemma(lemma: Lemma) -> Self { let mut proto = Self::new(); match lemma { Lemma { node_hash, sibling_hash, sub_lemma, } => { proto.set_node_hash(node_hash); if let Some(sub_proto) = sub_lemma.map(|l| Self::from_lemma(*l)) { proto.set_sub_lemma(sub_proto); } match sibling_hash { Some(Positioned::Left(hash)) => proto.set_left_sibling_hash(hash), Some(Positioned::Right(hash)) => proto.set_right_sibling_hash(hash), None => {} } } } proto } pub fn into_lemma(mut self) -> Option<Lemma> { if self.node_hash.is_empty() { return None; } let node_hash = self.take_node_hash(); let sibling_hash = if self.has_left_sibling_hash() { Some(Positioned::Left(self.take_left_sibling_hash())) } else if self.has_right_sibling_hash() { Some(Positioned::Right(self.take_right_sibling_hash())) } else { None }; if self.has_sub_lemma() { // If a `sub_lemma` is present is the Protobuf, // then we expect it to unserialize to a valid `Lemma`, // otherwise we return `None` self.take_sub_lemma().into_lemma().map(|sub_lemma| Lemma { node_hash, sibling_hash, sub_lemma: Some(Box::new(sub_lemma)), }) } else { // We might very well not have a sub_lemma, // in which case we just set it to `None`, // but still return a potentially valid `Lemma`. Some(Lemma { node_hash, sibling_hash, sub_lemma: None, }) } } }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/tests/proto.rs
tests/proto.rs
#![cfg(feature = "serialization-protobuf")] extern crate merkle; extern crate protobuf; extern crate ring; use ring::digest::{Algorithm, Context, SHA512}; use merkle::{Hashable, MerkleTree, Proof}; #[allow(non_upper_case_globals)] static digest: &'static Algorithm = &SHA512; #[test] fn test_protobuf_inverse() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::from_vec(digest, values.clone()); for value in values { let proof = tree.gen_proof(value).unwrap(); let bytes = proof.clone().write_to_bytes().unwrap(); let res = Proof::<Vec<u8>>::parse_from_bytes(&bytes, digest) .unwrap() .unwrap(); assert_eq!(proof.root_hash, res.root_hash); assert_eq!(proof.value, res.value); assert_eq!(proof.lemma, res.lemma); } } #[derive(Clone, Debug, PartialEq)] pub struct PublicKey { zero_values: Vec<u8>, one_values: Vec<u8>, } impl PublicKey { pub fn new(zero_values: Vec<u8>, one_values: Vec<u8>) -> Self { PublicKey { zero_values, one_values, } } pub fn to_bytes(&self) -> Vec<u8> { self.zero_values .iter() .chain(self.one_values.iter()) .cloned() .collect() } } impl From<Vec<u8>> for PublicKey { fn from(mut bytes: Vec<u8>) -> Self { let len = bytes.len(); let ones = bytes.split_off(len / 2); let zeros = bytes; PublicKey::new(zeros, ones) } } impl Into<Vec<u8>> for PublicKey { fn into(self) -> Vec<u8> { self.to_bytes() } } impl Hashable for PublicKey { fn update_context(&self, context: &mut Context) { context.update(&self.to_bytes()); } } #[test] fn test_protobuf_custom_hashable_impl() { let keys = (0..10) .map(|i| { let zero_values = (i..i + 16).collect::<Vec<_>>(); let one_values = (i * 10..i * 10 + 16).collect::<Vec<_>>(); PublicKey::new(zero_values, one_values) }) .collect::<Vec<_>>(); let tree = MerkleTree::from_vec(digest, keys.clone()); for key in keys { let proof = tree.gen_proof(key).unwrap(); let bytes = proof.clone().write_to_bytes().unwrap(); let res = Proof::parse_from_bytes(&bytes, digest).unwrap().unwrap(); assert_eq!(proof.root_hash, res.root_hash); assert_eq!(proof.value, res.value); assert_eq!(proof.lemma, res.lemma); } }
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
SpinResearch/merkle.rs
https://github.com/SpinResearch/merkle.rs/blob/2acba1bc73eba800e29a833f85f18f337e465213/benches/proof.rs
benches/proof.rs
#[macro_use] extern crate criterion; use criterion::black_box; use criterion::Criterion; extern crate merkle; extern crate rand; extern crate ring; use merkle::MerkleTree; use rand::RngCore; use ring::digest::{Algorithm, SHA512}; static DIGEST: &Algorithm = &SHA512; fn bench_small_str_tree(c: &mut Criterion) { c.bench_function("MerkleTree::from_bec - small", |b| { let values = vec!["one", "two", "three", "four"]; b.iter(|| MerkleTree::from_vec(DIGEST, black_box(values.clone()))) }); } fn bench_small_str_proof_gen(c: &mut Criterion) { c.bench_function("MerkleTree::gen_proof - small", |b| { let values = vec!["one", "two", "three", "four"]; let tree = MerkleTree::from_vec(DIGEST, values.clone()); b.iter(|| { for value in &values { tree.gen_proof(black_box(value)); } }) }); } fn bench_small_str_proof_check(c: &mut Criterion) { c.bench_function("MerkleTree::validate_proof - small", |b| { let values = vec!["one", "two", "three", "four"]; let tree = MerkleTree::from_vec(DIGEST, values.clone()); let proofs = values .iter() .map(|v| tree.gen_proof(v).unwrap()) .collect::<Vec<_>>(); b.iter(|| { for proof in &proofs { proof.validate(black_box(tree.root_hash())); } }) }); } fn bench_big_rnd_tree(c: &mut Criterion) { c.bench_function("MerkleTree::from_vec - big", |b| { let mut values = vec![vec![0u8; 256]; 160]; let mut rng = rand::thread_rng(); for mut v in &mut values { rng.fill_bytes(&mut v); } b.iter(|| MerkleTree::from_vec(DIGEST, black_box(values.clone()))) }); } fn bench_big_rnd_proof_gen(c: &mut Criterion) { c.bench_function("MerkleTree::gen_proof - big", |b| { let mut values = vec![vec![0u8; 256]; 160]; let mut rng = rand::thread_rng(); for mut v in &mut values { rng.fill_bytes(&mut v); } let tree = MerkleTree::from_vec(DIGEST, values.clone()); b.iter(|| { for value in &values { tree.gen_proof(black_box(value.clone())); } }) }); } fn bench_big_rnd_proof_check(c: &mut Criterion) { c.bench_function("MerkleTree::validate_proof - big", |b| { let mut values = vec![vec![0u8; 256]; 160]; let mut rng = rand::thread_rng(); for mut v in &mut values { rng.fill_bytes(&mut v); } let tree = MerkleTree::from_vec(DIGEST, values.clone()); let proofs = values .into_iter() .map(|v| tree.gen_proof(v).unwrap()) .collect::<Vec<_>>(); b.iter(|| { for proof in &proofs { proof.validate(black_box(tree.root_hash())); } }) }); } fn bench_big_rnd_iter(c: &mut Criterion) { c.bench_function("MerkleTree::iter - big", |b| { let mut values = vec![vec![0u8; 256]; 160]; let mut rng = rand::thread_rng(); for mut v in &mut values { rng.fill_bytes(&mut v); } let tree = MerkleTree::from_vec(DIGEST, values); b.iter(|| { for value in &tree { black_box(value); } }) }); } criterion_group!( benches, bench_small_str_tree, bench_small_str_proof_gen, bench_small_str_proof_check, bench_big_rnd_tree, bench_big_rnd_proof_gen, bench_big_rnd_proof_check, bench_big_rnd_iter, ); criterion_main!(benches);
rust
BSD-3-Clause
2acba1bc73eba800e29a833f85f18f337e465213
2026-01-04T20:23:00.319157Z
false
leptos-rs/start-actix-0.6
https://github.com/leptos-rs/start-actix-0.6/blob/61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2/src/app.rs
src/app.rs
use leptos::*; use leptos_meta::*; use leptos_router::*; #[component] pub fn App() -> impl IntoView { // Provides context that manages stylesheets, titles, meta tags, etc. provide_meta_context(); view! { // injects a stylesheet into the document <head> // id=leptos means cargo-leptos will hot-reload this stylesheet <Stylesheet id="leptos" href="/pkg/{{project-name}}.css"/> // sets the document title <Title text="Welcome to Leptos"/> // content for this welcome page <Router> <main> <Routes> <Route path="" view=HomePage/> <Route path="/*any" view=NotFound/> </Routes> </main> </Router> } } /// Renders the home page of your application. #[component] fn HomePage() -> impl IntoView { // Creates a reactive value to update the button let (count, set_count) = create_signal(0); let on_click = move |_| set_count.update(|count| *count += 1); view! { <h1>"Welcome to Leptos!"</h1> <button on:click=on_click>"Click Me: " {count}</button> } } /// 404 - Not Found #[component] fn NotFound() -> impl IntoView { // set an HTTP status code 404 // this is feature gated because it can only be done during // initial server-side rendering // if you navigate to the 404 page subsequently, the status // code will not be set because there is not a new HTTP request // to the server #[cfg(feature = "ssr")] { // this can be done inline because it's synchronous // if it were async, we'd use a server function let resp = expect_context::<leptos_actix::ResponseOptions>(); resp.set_status(actix_web::http::StatusCode::NOT_FOUND); } view! { <h1>"Not Found"</h1> } }
rust
Unlicense
61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2
2026-01-04T20:23:01.626037Z
false
leptos-rs/start-actix-0.6
https://github.com/leptos-rs/start-actix-0.6/blob/61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2/src/lib.rs
src/lib.rs
pub mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use app::*; use leptos::*; console_error_panic_hook::set_once(); mount_to_body(App); }
rust
Unlicense
61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2
2026-01-04T20:23:01.626037Z
false
leptos-rs/start-actix-0.6
https://github.com/leptos-rs/start-actix-0.6/blob/61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2/src/main.rs
src/main.rs
#[cfg(feature = "ssr")] #[actix_web::main] async fn main() -> std::io::Result<()> { use actix_files::Files; use actix_web::*; use leptos::*; use leptos_actix::{generate_route_list, LeptosRoutes}; use {{crate_name}}::app::*; let conf = get_configuration(None).await.unwrap(); let addr = conf.leptos_options.site_addr; // Generate the list of routes in your Leptos App let routes = generate_route_list(App); println!("listening on http://{}", &addr); HttpServer::new(move || { let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() // serve JS/WASM/CSS from `pkg` .service(Files::new("/pkg", format!("{site_root}/pkg"))) // serve other assets from the `assets` directory .service(Files::new("/assets", site_root)) // serve the favicon from /favicon.ico .service(favicon) .leptos_routes(leptos_options.to_owned(), routes.to_owned(), App) .app_data(web::Data::new(leptos_options.to_owned())) //.wrap(middleware::Compress::default()) }) .bind(&addr)? .run() .await } #[cfg(feature = "ssr")] #[actix_web::get("favicon.ico")] async fn favicon( leptos_options: actix_web::web::Data<leptos::LeptosOptions>, ) -> actix_web::Result<actix_files::NamedFile> { let leptos_options = leptos_options.into_inner(); let site_root = &leptos_options.site_root; Ok(actix_files::NamedFile::open(format!( "{site_root}/favicon.ico" ))?) } #[cfg(not(any(feature = "ssr", feature = "csr")))] pub fn main() { // no client-side main function // unless we want this to work with e.g., Trunk for pure client-side testing // see lib.rs for hydration function instead // see optional feature `csr` instead } #[cfg(all(not(feature = "ssr"), feature = "csr"))] pub fn main() { // a client-side main function is required for using `trunk serve` // prefer using `cargo leptos serve` instead // to run: `trunk serve --open --features csr` use {{crate_name}}::app::*; console_error_panic_hook::set_once(); leptos::mount_to_body(App); }
rust
Unlicense
61de9d648bcd6efadc8a9ac6f66196f4ed0f84b2
2026-01-04T20:23:01.626037Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/build.rs
build.rs
use std::process::Command; fn main() { let hash_utf8 = Command::new("git").args(["rev-parse", "--short", "HEAD"]).output(); if let Ok(hash_utf8) = hash_utf8 { let hash = String::from_utf8(hash_utf8.stdout).unwrap(); println!("cargo:rustc-env=COMMIT_HASH={}", hash.trim()); } else { println!("cargo:rustc-env=COMMIT_HASH=NO_GIT"); } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/cursor.rs
src/cursor.rs
use bevy::prelude::*; use crate::components::*; pub fn update_cursor_info( mouse_button_input: Res<ButtonInput<MouseButton>>, camera_query: Query<(&Camera, &GlobalTransform)>, windows: Query<&Window>, mut cursor: ResMut<CursorInfo>, mut last_pos: Local<Vec2>, ) { if mouse_button_input.just_pressed(MouseButton::Left) { let (cam, cam_transform) = camera_query.single(); if let Some(cursor_pos) = windows.single().cursor_position() { if let Some(point) = cam.viewport_to_world_2d(cam_transform, cursor_pos) { cursor.i = point; } } } if mouse_button_input.pressed(MouseButton::Left) { let (cam, cam_transform) = camera_query.single(); if let Some(cursor_pos) = windows.single().cursor_position() { if let Some(point) = cam.viewport_to_world_2d(cam_transform, cursor_pos) { cursor.f = point; cursor.d = point - *last_pos; *last_pos = point; } } } if mouse_button_input.just_released(MouseButton::Left) { cursor.d = Vec2::ZERO; *last_pos = -cursor.f; // so on the pressed frame we don't get a delta } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/process.rs
src/process.rs
use bevy::{ core_pipeline::{ bloom::{BloomCompositeMode, BloomSettings}, tonemapping::Tonemapping, }, input::keyboard::{Key, KeyboardInput}, prelude::*, render::view::{screenshot::ScreenshotManager, RenderLayers}, utils::Duration, winit::{UpdateMode, WinitSettings}, }; use std::str::FromStr; use fundsp::hacker32::*; use crate::{components::*, functions::*, nodes::*, osc::*}; pub fn sort_by_order(query: Query<(Entity, &Order), With<Network>>, mut queue: ResMut<Queue>) { let mut max_order: usize = 1; queue.0.clear(); queue.0.push(Vec::new()); for (entity, order) in query.iter() { if order.0 > 0 { if order.0 > max_order { queue.0.resize(order.0, Vec::new()); max_order = order.0; } queue.0[order.0 - 1].push(entity); //order 1 at index 0 } } } pub fn prepare_loop_queue( mut loopq: ResMut<LoopQueue>, queue: Res<Queue>, op_num_query: Query<&OpNum>, targets_query: Query<&Targets>, ) { loopq.0.clear(); for id in queue.0.iter().flatten() { if op_num_query.get(*id).unwrap().0 == 92 { for t in &targets_query.get(*id).unwrap().0 { // only add existing circles (that aren't holes) if op_num_query.contains(*t) { loopq.0.push(*t); } } } } } pub fn process( // TODO(mara): organize queue: Res<Queue>, loopq: Res<LoopQueue>, holes_query: Query<&Holes>, mut white_hole_query: Query<&mut WhiteHole>, black_hole_query: Query<&BlackHole>, cursor: Res<CursorInfo>, mouse_button_input: Res<ButtonInput<MouseButton>>, camera_query: Query<(Entity, &Camera, &GlobalTransform)>, windows: Query<(Entity, &Window)>, mut commands: Commands, mut slot: ResMut<SlotRes>, ( mut order_query, op_query, mut bloom, mut num_query, mut trans_query, mut arr_query, mut tonemapping, mut net_query, mut net_ins_query, net_chan_query, mut col_query, mut order_change, mut vertices_query, mut op_changed_query, mut lost_wh_query, mut targets_query, ): ( Query<&mut Order>, Query<&mut Op>, Query<&mut BloomSettings, With<Camera>>, Query<&mut Number>, Query<&mut Transform>, Query<&mut Arr>, Query<&mut Tonemapping, With<Camera>>, Query<&mut Network>, Query<&mut NetIns>, Query<&NetChannel>, Query<&mut Col>, EventWriter<OrderChange>, Query<&mut Vertices>, Query<&mut OpChanged>, Query<&mut LostWH>, Query<&mut Targets>, ), ( mut screensot_manager, mut winit_settings, mut clear_color, mut default_color, mut default_verts, mut highlight_color, mut connection_color, mut connection_width, arrow_query, indicator, mut indicator_color, mut command_line_text, mut command_color, selected_query, mut delete_event, polygon_handles, ): ( ResMut<ScreenshotManager>, ResMut<WinitSettings>, ResMut<ClearColor>, ResMut<DefaultDrawColor>, ResMut<DefaultDrawVerts>, ResMut<HighlightColor>, ResMut<ConnectionColor>, ResMut<ConnectionWidth>, Query<&ConnectionArrow>, Res<Indicator>, ResMut<IndicatorColor>, Query<&mut Text, With<CommandText>>, ResMut<CommandColor>, Query<Entity, With<Selected>>, EventWriter<DeleteCommand>, Res<PolygonHandles>, ), ( mut materials, connection_mat, mut connect_command, info_text_query, mut text_size, mut osc_sender, mut osc_receiver, mut osc_messages, node_limit, input_receivers, op_num_query, mut key_event, mut ortho, float_chan_query, ): ( ResMut<Assets<ColorMaterial>>, ResMut<ConnectionMat>, EventWriter<ConnectCommand>, Query<&InfoText>, ResMut<TextSize>, ResMut<OscSender>, ResMut<OscReceiver>, Local<Vec<rosc::OscMessage>>, Res<NodeLimit>, Res<InputReceivers>, Query<&OpNum>, EventReader<KeyboardInput>, Query<&mut OrthographicProjection>, Query<&FloatChannel>, ), ) { let key_event = key_event.read().collect::<Vec<_>>(); let mut worm: Vec<(String, f32)> = Vec::new(); 'entity: for id in queue.0.iter().flatten().chain(loopq.0.iter()) { let holes = &holes_query.get(*id).unwrap().0; for hole in holes { let mut lt_to_open = 0; if let Ok(wh) = white_hole_query.get(*hole) { if !wh.open { continue; } let mut input = None; match wh.link_types.0 { -1 => input = Some(num_query.get(wh.bh_parent).unwrap().0), -2 => input = Some(trans_query.get(wh.bh_parent).unwrap().scale.x), -3 => input = Some(trans_query.get(wh.bh_parent).unwrap().translation.x), -4 => input = Some(trans_query.get(wh.bh_parent).unwrap().translation.y), -5 => input = Some(trans_query.get(wh.bh_parent).unwrap().translation.z), -6 => input = Some(col_query.get(wh.bh_parent).unwrap().0.hue), -7 => input = Some(col_query.get(wh.bh_parent).unwrap().0.saturation), -8 => input = Some(col_query.get(wh.bh_parent).unwrap().0.lightness), -9 => input = Some(col_query.get(wh.bh_parent).unwrap().0.alpha), -11 => input = Some(vertices_query.get(wh.bh_parent).unwrap().0 as f32), -12 => { input = Some( trans_query .get(wh.bh_parent) .unwrap() .rotation .to_euler(EulerRot::XYZ) .2, ) } -13 if wh.link_types.1 == -13 => { let arr = arr_query.get(wh.bh_parent).unwrap().0.clone(); arr_query.get_mut(*id).unwrap().0 = arr; lt_to_open = -13; } -14 if wh.link_types.1 == -14 => { let arr = targets_query.get(wh.bh_parent).unwrap().0.clone(); targets_query.get_mut(*id).unwrap().0 = arr; lt_to_open = -14; } _ => {} } if let Some(input) = input { lt_to_open = wh.link_types.1; match wh.link_types.1 { -1 => num_query.get_mut(*id).unwrap().0 = input, -2 => { trans_query.get_mut(*id).unwrap().scale.x = input.max(0.); trans_query.get_mut(*id).unwrap().scale.y = input.max(0.); } -3 => trans_query.get_mut(*id).unwrap().translation.x = input, -4 => trans_query.get_mut(*id).unwrap().translation.y = input, -5 => trans_query.get_mut(*id).unwrap().translation.z = input, -6 => col_query.get_mut(*id).unwrap().0.hue = input, -7 => col_query.get_mut(*id).unwrap().0.saturation = input, -8 => col_query.get_mut(*id).unwrap().0.lightness = input, -9 => col_query.get_mut(*id).unwrap().0.alpha = input, -11 => { vertices_query.get_mut(*id).unwrap().0 = (input as usize).clamp(3, 64) } -12 => { let q = Quat::from_euler(EulerRot::XYZ, 0., 0., input); trans_query.get_mut(*id).unwrap().rotation = q; } _ => lt_to_open = 0, } } } // open all white holes reading whatever just changed if lt_to_open != 0 { for hole in holes { if let Ok(bh) = black_hole_query.get(*hole) { if let Ok(wh) = white_hole_query.get(bh.wh) { if wh.link_types.0 == lt_to_open { white_hole_query.get_mut(bh.wh).unwrap().open = true; } } } } } } let mut lt_to_open = None; let op = op_query.get(*id).unwrap().0.as_str(); let op_num = op_num_query.get(*id).unwrap().0; match op_num { 0 => {} // -------------------- targets -------------------- // open_target | close_target 1 | 2 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && num_query.get(wh.bh_parent).unwrap().0 != 0. { let targets = &targets_query.get(*id).unwrap().0; for t in targets { if let Ok(mut wh) = white_hole_query.get_mut(*t) { wh.open = op_num == 1; } } } } } } // open_nth 3 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get(wh.bh_parent).unwrap().0; let targets = &targets_query.get(*id).unwrap().0; if let Some(nth) = targets.get(n as usize) { if let Ok(mut wh) = white_hole_query.get_mut(*nth) { wh.open = true; } } } } } } // del_target 4 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && num_query.get(wh.bh_parent).unwrap().0 != 0. { for e in selected_query.iter() { commands.entity(e).remove::<Selected>(); } for t in &targets_query.get(*id).unwrap().0 { if vertices_query.contains(*t) { commands.entity(*t).insert(Selected); } } targets_query.get_mut(*id).unwrap().0.clear(); delete_event.send_default(); } } } } // select_target 5 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get(wh.bh_parent).unwrap().0; if n != 0. { for t in &targets_query.get(*id).unwrap().0 { if vertices_query.contains(*t) { commands.entity(*t).insert(Selected); } } } else { for t in &targets_query.get(*id).unwrap().0 { if vertices_query.contains(*t) { commands.entity(*t).remove::<Selected>(); } } } } } } } // spin_target 6 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && num_query.get(wh.bh_parent).unwrap().0 != 0. { let point = trans_query.get(*id).unwrap().translation; let n = num_query.get(*id).unwrap().0; let rotation = Quat::from_euler(EulerRot::XYZ, 0., 0., n); for t in &targets_query.get(*id).unwrap().0 { if let Ok(mut trans) = trans_query.get_mut(*t) { trans.rotate_around(point, rotation); } } } } } } // reorder 7 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get(wh.bh_parent).unwrap().0; let targets = &targets_query.get(*id).unwrap().0; for t in targets { if let Ok(mut order) = order_query.get_mut(*t) { order.0 = n as usize; order_change.send_default(); } } } } } } // spawn 8 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && num_query.get(wh.bh_parent).unwrap().0 != 0. { let targets = &mut targets_query.get_mut(*id).unwrap().0; let v = vertices_query.get(*id).unwrap().0; let trans = trans_query.get(*id).unwrap(); let t = trans.translation.xy(); let r = trans.scale.x; let depth = trans.translation.z + (targets.len() + 1) as f32 * 0.01; let color = col_query.get(*id).unwrap().0; let (sndr, rcvr) = crossbeam_channel::bounded(1); let new = commands .spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[v].clone().unwrap(), material: materials.add(ColorMaterial::from_color(color)), transform: Transform { translation: t.extend(depth), rotation: trans.rotation, scale: Vec3::new(r, r, 1.), }, ..default() }, Vertices(v), Col(color), Number(0.), Arr(Vec::new()), Op("empty".to_string()), Targets(Vec::new()), Holes(Vec::new()), Order(0), ( OpNum(0), Network(Net::new(0, 0)), NetIns(Vec::new()), OpChanged(false), LostWH(false), NetChannel(sndr, rcvr), ), RenderLayers::layer(1), )) .id(); targets.push(new); lt_to_open = Some(-14); } } } } // connect_target 9 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open && num_query.get(wh.bh_parent).unwrap().0 != 0. { targets_query .get_mut(*id) .unwrap() .0 .retain(|x| holes_query.contains(*x)); connect_command.send(ConnectCommand(*id)); } } } } // isolate_target 10 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open && num_query.get(wh.bh_parent).unwrap().0 != 0. { for e in selected_query.iter() { commands.entity(e).remove::<Selected>(); } for t in &targets_query.get(*id).unwrap().0 { if let Ok(holes) = holes_query.get(*t) { for hole in &holes.0 { commands.entity(*hole).insert(Selected); } } } delete_event.send_default(); } } } } // target_lt 11 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get(wh.bh_parent).unwrap().0; for t in &targets_query.get(*id).unwrap().0 { if let Ok(mut wh) = white_hole_query.get_mut(*t) { wh.link_types.1 = n as i8; } else if let Ok(bh) = black_hole_query.get(*t) { white_hole_query.get_mut(bh.wh).unwrap().link_types.0 = n as i8; } } } } } } // distro 12 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types.0 == -13 && wh.open { let arr = &arr_query.get(wh.bh_parent).unwrap().0; let targets = &targets_query.get(*id).unwrap().0; let len = Ord::min(arr.len(), targets.len()); for i in 0..len { if vertices_query.get(targets[i]).is_err() { continue; } // input link type determines what property to write to in targets match wh.link_types.1 { -1 => { if let Ok(mut n) = num_query.get_mut(targets[i]) { n.0 = arr[i]; } } -2 => { trans_query.get_mut(targets[i]).unwrap().scale.x = arr[i].max(0.1); trans_query.get_mut(targets[i]).unwrap().scale.y = arr[i].max(0.1); } -3 => { trans_query.get_mut(targets[i]).unwrap().translation.x = arr[i]; } -4 => { trans_query.get_mut(targets[i]).unwrap().translation.y = arr[i]; } -5 => { trans_query.get_mut(targets[i]).unwrap().translation.z = arr[i]; } -6 => col_query.get_mut(targets[i]).unwrap().0.hue = arr[i], -7 => { col_query.get_mut(targets[i]).unwrap().0.saturation = arr[i]; } -8 => { col_query.get_mut(targets[i]).unwrap().0.lightness = arr[i] } -9 => col_query.get_mut(targets[i]).unwrap().0.alpha = arr[i], -10 => { if let Ok(mut ord) = order_query.get_mut(targets[i]) { ord.0 = arr[i] as usize; order_change.send_default(); } } -11 => { let v = arr[i].max(3.) as usize; vertices_query.get_mut(targets[i]).unwrap().0 = v; } -12 => { let q = Quat::from_euler(EulerRot::XYZ, 0., 0., arr[i]); trans_query.get_mut(targets[i]).unwrap().rotation = q; } _ => {} } } let lt = wh.link_types.1; for t in &targets_query.get(*id).unwrap().0 { if let Ok(holes) = &holes_query.get(*t) { for hole in &holes.0 { if let Ok(bh) = black_hole_query.get(*hole) { if let Ok(wh) = white_hole_query.get_mut(bh.wh) { if wh.link_types.0 == lt { white_hole_query.get_mut(bh.wh).unwrap().open = true; } } } } } } } } } } // repeat 13 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-14, 1) && wh.open { let n = num_query.get(*id).unwrap().0 as usize; let targets = &targets_query.get(wh.bh_parent).unwrap().0; targets_query.get_mut(*id).unwrap().0 = targets.repeat(n); lt_to_open = Some(-14); } } } } // -------------------- arrays -------------------- // zip 14 => { let mut arr1 = None; let mut arr2 = None; let mut changed = false; for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) { arr1 = Some(wh.bh_parent); } else if wh.link_types == (-13, 2) { arr2 = Some(wh.bh_parent); } if wh.open { changed = true; } } } if changed { if let (Some(arr1), Some(arr2)) = (arr1, arr2) { let a1 = arr_query.get(arr1).unwrap().0.clone(); let a2 = arr_query.get(arr2).unwrap().0.clone(); let n = Ord::max(a1.len(), a2.len()); let out = &mut arr_query.get_mut(*id).unwrap().0; out.clear(); for i in 0..n { if let Some(x) = a1.get(i) { out.push(*x); } if let Some(y) = a2.get(i) { out.push(*y); } } lt_to_open = Some(-13); } } } // unzip 15 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) && wh.open { let input = &arr_query.get(wh.bh_parent).unwrap().0; let mut l = Vec::new(); let mut r = Vec::new(); for (i, v) in input.iter().enumerate() { if i & 1 == 0 { l.push(*v); } else { r.push(*v); } } arr_query.get_mut(wh.bh_parent).unwrap().0 = l; arr_query.get_mut(*id).unwrap().0 = r; lt_to_open = Some(-13); } } } } // push 16 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get_mut(wh.bh_parent).unwrap().0; arr_query.get_mut(*id).unwrap().0.push(n); lt_to_open = Some(-13); } } } } // pop 17 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && num_query.get(wh.bh_parent).unwrap().0 != 0. { if let Some(n) = arr_query.get_mut(*id).unwrap().0.pop() { num_query.get_mut(*id).unwrap().0 = n; lt_to_open = Some(-1); } } } } } // len 18 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) && wh.open { let len = arr_query.get(wh.bh_parent).unwrap().0.len() as f32; num_query.get_mut(*id).unwrap().0 = len; lt_to_open = Some(-1); } else if wh.link_types == (-14, 1) && wh.open { let len = targets_query.get(wh.bh_parent).unwrap().0.len() as f32; num_query.get_mut(*id).unwrap().0 = len; lt_to_open = Some(-1); } } } } // append 19 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) && wh.open { let arr = &mut arr_query.get(wh.bh_parent).unwrap().0.clone(); arr_query.get_mut(*id).unwrap().0.append(arr); lt_to_open = Some(-13); } } } } // slice 20 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) && wh.open { let arr = &mut arr_query.get_mut(wh.bh_parent).unwrap(); let n = num_query.get(*id).unwrap().0 as usize; if n <= arr.0.len() { let slice = arr.0.split_off(n); arr_query.get_mut(*id).unwrap().0 = slice; lt_to_open = Some(-13); } } } } } // resize 21 => { for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-1, 1) && wh.open { let n = num_query.get(wh.bh_parent).unwrap().0 as usize; arr_query.get_mut(*id).unwrap().0.resize(n, 0.); lt_to_open = Some(-13); } } } } // contains 22 => { let mut changed = false; let mut arr = None; let mut n = None; for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-13, 1) { arr = Some(wh.bh_parent); if wh.open { changed = true; } } if wh.link_types == (-1, 2) { n = Some(wh.bh_parent); if wh.open { changed = true; } } } } if changed { if let (Some(arr), Some(n)) = (arr, n) { let n = num_query.get(n).unwrap().0; if arr_query.get(arr).unwrap().0.contains(&n) { num_query.get_mut(*id).unwrap().0 = 1.; } else { num_query.get_mut(*id).unwrap().0 = 0.; } lt_to_open = Some(-1); } } } // set 23 => { let mut changed = false; let mut ndx = None; let mut val = None; for hole in holes { if let Ok(wh) = white_hole_query.get(*hole) {
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
true
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/functions.rs
src/functions.rs
use crate::nodes::*; use fundsp::hacker32::*; use std::num::Wrapping; pub fn str_to_lt(s: &str) -> i8 { if let Ok(n) = s.parse::<i8>() { n } else { match s { "n" => -1, "r" => -2, "x" => -3, "y" => -4, "z" => -5, "h" => -6, "s" => -7, "l" => -8, "a" => -9, "v" => -11, "o" => -12, "A" => -13, "T" => -14, _ => 0, } } } pub fn lt_to_string(n: i8) -> String { match n { -1 => "n".to_string(), -2 => "r".to_string(), -3 => "x".to_string(), -4 => "y".to_string(), -5 => "z".to_string(), -6 => "h".to_string(), -7 => "s".to_string(), -8 => "l".to_string(), -9 => "a".to_string(), -11 => "v".to_string(), -12 => "o".to_string(), -13 => "A".to_string(), -14 => "T".to_string(), _ => n.to_string(), } } pub fn parse_with_constants(s: &str) -> Result<f32, &str> { if let Ok(n) = s.parse::<f32>() { Ok(n) } else { match s { "E" => Ok(std::f32::consts::E), "FRAC_1_PI" => Ok(std::f32::consts::FRAC_1_PI), "FRAC_1_SQRT_2" => Ok(std::f32::consts::FRAC_1_SQRT_2), "FRAC_2_PI" => Ok(std::f32::consts::FRAC_2_PI), "FRAC_2_SQRT_PI" => Ok(std::f32::consts::FRAC_2_SQRT_PI), "FRAC_PI_2" => Ok(std::f32::consts::FRAC_PI_2), "FRAC_PI_3" => Ok(std::f32::consts::FRAC_PI_3), "FRAC_PI_4" => Ok(std::f32::consts::FRAC_PI_4), "FRAC_PI_6" => Ok(std::f32::consts::FRAC_PI_6), "FRAC_PI_8" => Ok(std::f32::consts::FRAC_PI_8), "LN_2" => Ok(std::f32::consts::LN_2), "LN_10" => Ok(std::f32::consts::LN_10), "LOG2_10" => Ok(std::f32::consts::LOG2_10), "LOG2_E" => Ok(std::f32::consts::LOG2_E), "LOG10_2" => Ok(std::f32::consts::LOG10_2), "LOG10_E" => Ok(std::f32::consts::LOG10_E), "PI" => Ok(std::f32::consts::PI), "SQRT_2" => Ok(std::f32::consts::SQRT_2), "TAU" => Ok(std::f32::consts::TAU), "EGAMMA" => Ok(0.5772157), "FRAC_1_SQRT_3" => Ok(0.57735026), "FRAC_1_SQRT_PI" => Ok(0.5641896), "PHI" => Ok(1.618034), "SQRT_3" => Ok(1.7320508), "-E" => Ok(-std::f32::consts::E), "-FRAC_1_PI" => Ok(-std::f32::consts::FRAC_1_PI), "-FRAC_1_SQRT_2" => Ok(-std::f32::consts::FRAC_1_SQRT_2), "-FRAC_2_PI" => Ok(-std::f32::consts::FRAC_2_PI), "-FRAC_2_SQRT_PI" => Ok(-std::f32::consts::FRAC_2_SQRT_PI), "-FRAC_PI_2" => Ok(-std::f32::consts::FRAC_PI_2), "-FRAC_PI_3" => Ok(-std::f32::consts::FRAC_PI_3), "-FRAC_PI_4" => Ok(-std::f32::consts::FRAC_PI_4), "-FRAC_PI_6" => Ok(-std::f32::consts::FRAC_PI_6), "-FRAC_PI_8" => Ok(-std::f32::consts::FRAC_PI_8), "-LN_2" => Ok(-std::f32::consts::LN_2), "-LN_10" => Ok(-std::f32::consts::LN_10), "-LOG2_10" => Ok(-std::f32::consts::LOG2_10), "-LOG2_E" => Ok(-std::f32::consts::LOG2_E), "-LOG10_2" => Ok(-std::f32::consts::LOG10_2), "-LOG10_E" => Ok(-std::f32::consts::LOG10_E), "-PI" => Ok(-std::f32::consts::PI), "-SQRT_2" => Ok(-std::f32::consts::SQRT_2), "-TAU" => Ok(-std::f32::consts::TAU), "-EGAMMA" => Ok(-0.5772157), "-FRAC_1_SQRT_3" => Ok(-0.57735026), "-FRAC_1_SQRT_PI" => Ok(-0.5641896), "-PHI" => Ok(-1.618034), "-SQRT_3" => Ok(-1.7320508), "MAX" => Ok(f32::MAX), "MIN" => Ok(f32::MIN), "EPSILON" => Ok(f32::EPSILON), "MIN_POSITIVE" => Ok(f32::MIN_POSITIVE), _ => Err("not a float nor a constant"), } } } pub fn str_to_net(op: &str) -> Net { let op = op.replace(' ', ""); // "cat()" -> ["cat", "", ""], "cat(mew, mrp)" -> ["cat", "mew, mrp", ""] let args: Vec<&str> = op.split(['(', ')']).collect(); // parse the parameters (between parentheses) let mut p = Vec::new(); if let Some(params) = args.get(1) { let params = params.split(',').collect::<Vec<&str>>(); for s in params { if let Ok(n) = parse_with_constants(s) { p.push(n); } } } else { // no parentheses return Net::new(0, 0); } match args[0] { // -------------------- sources -------------------- "sine" => { if let Some(p) = p.first() { return Net::wrap(Box::new(sine_hz(*p))); } else { return Net::wrap(Box::new(sine())); } } "saw" => { if let Some(p) = p.first() { return Net::wrap(Box::new(saw_hz(*p))); } else { return Net::wrap(Box::new(saw())); } } "square" => { if let Some(p) = p.first() { return Net::wrap(Box::new(square_hz(*p))); } else { return Net::wrap(Box::new(square())); } } "triangle" => { if let Some(p) = p.first() { return Net::wrap(Box::new(triangle_hz(*p))); } else { return Net::wrap(Box::new(triangle())); } } "organ" => { if let Some(p) = p.first() { return Net::wrap(Box::new(organ_hz(*p))); } else { return Net::wrap(Box::new(organ())); } } "pulse" => return Net::wrap(Box::new(pulse())), "brown" => return Net::wrap(Box::new(brown())), "pink" => return Net::wrap(Box::new(pink())), "white" | "noise" => return Net::wrap(Box::new(white())), "hammond" => { if let Some(p) = p.first() { return Net::wrap(Box::new(hammond_hz(*p))); } else { return Net::wrap(Box::new(hammond())); } } "zero" => return Net::wrap(Box::new(zero())), "impulse" => return Net::wrap(Box::new(impulse::<U1>())), "lorenz" => return Net::wrap(Box::new(lorenz())), "rossler" => return Net::wrap(Box::new(rossler())), "constant" | "dc" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(constant((p0, p1, p2, p3, p4, p5, p6, p7)))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(constant((p0, p1, p2, p3, p4, p5, p6)))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(constant((p0, p1, p2, p3, p4, p5)))) } [p0, p1, p2, p3, p4, ..] => return Net::wrap(Box::new(constant((p0, p1, p2, p3, p4)))), [p0, p1, p2, p3, ..] => return Net::wrap(Box::new(constant((p0, p1, p2, p3)))), [p0, p1, p2, ..] => return Net::wrap(Box::new(constant((p0, p1, p2)))), [p0, p1, ..] => return Net::wrap(Box::new(constant((p0, p1)))), [p0, ..] => return Net::wrap(Box::new(constant(p0))), _ => return Net::wrap(Box::new(constant(1.))), }, "dsf_saw" => { if let Some(p) = p.first() { return Net::wrap(Box::new(dsf_saw_r(*p))); } else { return Net::wrap(Box::new(dsf_saw())); } } "dsf_square" => { if let Some(p) = p.first() { return Net::wrap(Box::new(dsf_square_r(*p))); } else { return Net::wrap(Box::new(dsf_square())); } } "pluck" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(pluck(p[0], p[1], p[2]))); } } "mls" => { if let Some(p) = p.first() { return Net::wrap(Box::new(mls_bits(p.clamp(1., 31.) as u64))); } else { return Net::wrap(Box::new(mls())); } } "soft_saw" => { if let Some(p) = p.first() { return Net::wrap(Box::new(soft_saw_hz(*p))); } else { return Net::wrap(Box::new(soft_saw())); } } "ramp" => return Net::wrap(Box::new(An(Ramp::new()))), // -------------------- filters -------------------- "allpole" => { if let Some(p) = p.first() { return Net::wrap(Box::new(allpole_delay(*p))); } else { return Net::wrap(Box::new(allpole())); } } "pinkpass" => return Net::wrap(Box::new(pinkpass())), "allpass" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(allpass_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(allpass_q(*p))); } else { return Net::wrap(Box::new(allpass())); } } "bandpass" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(bandpass_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(bandpass_q(*p))); } else { return Net::wrap(Box::new(bandpass())); } } "bandrez" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(bandrez_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(bandrez_q(*p))); } else { return Net::wrap(Box::new(bandrez())); } } "bell" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(bell_hz(p[0], p[1], p[2]))); } else if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(bell_q(p[0], p[1]))); } else { return Net::wrap(Box::new(bell())); } } "biquad" => { if let Some(p) = p.get(0..5) { return Net::wrap(Box::new(biquad(p[0], p[1], p[2], p[3], p[4]))); } } "butterpass" => { if let Some(p) = p.first() { return Net::wrap(Box::new(butterpass_hz(*p))); } else { return Net::wrap(Box::new(butterpass())); } } "dcblock" => { if let Some(p) = p.first() { return Net::wrap(Box::new(dcblock_hz(*p))); } else { return Net::wrap(Box::new(dcblock())); } } "fir" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, ..] => { return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)))) } [p0, p1, p2, p3, p4, p5, p6, p7, p8, ..] => { return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4, p5, p6, p7, p8)))) } [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4, p5, p6, p7)))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4, p5, p6)))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4, p5)))) } [p0, p1, p2, p3, p4, ..] => return Net::wrap(Box::new(fir((p0, p1, p2, p3, p4)))), [p0, p1, p2, p3, ..] => return Net::wrap(Box::new(fir((p0, p1, p2, p3)))), [p0, p1, p2, ..] => return Net::wrap(Box::new(fir((p0, p1, p2)))), [p0, p1, ..] => return Net::wrap(Box::new(fir((p0, p1)))), [p0, ..] => return Net::wrap(Box::new(fir(p0))), _ => {} }, "fir3" => { if let Some(p) = p.first() { return Net::wrap(Box::new(fir3(*p))); } } "follow" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(afollow(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(follow(*p))); } } "highpass" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(highpass_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(highpass_q(*p))); } else { return Net::wrap(Box::new(highpass())); } } "highpole" => { if let Some(p) = p.first() { return Net::wrap(Box::new(highpole_hz(*p))); } else { return Net::wrap(Box::new(highpole())); } } "highshelf" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(highshelf_hz(p[0], p[1], p[2]))); } else if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(highshelf_q(p[0], p[1]))); } else { return Net::wrap(Box::new(highshelf())); } } "lowpass" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(lowpass_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(lowpass_q(*p))); } else { return Net::wrap(Box::new(lowpass())); } } "lowpole" => { if let Some(p) = p.first() { return Net::wrap(Box::new(lowpole_hz(*p))); } else { return Net::wrap(Box::new(lowpole())); } } "lowrez" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(lowrez_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(lowrez_q(*p))); } else { return Net::wrap(Box::new(lowrez())); } } "lowshelf" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(lowshelf_hz(p[0], p[1], p[2]))); } else if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(lowshelf_q(p[0], p[1]))); } else { return Net::wrap(Box::new(lowshelf())); } } "moog" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(moog_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(moog_q(*p))); } else { return Net::wrap(Box::new(moog())); } } "morph" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(morph_hz(p[0], p[1], p[2]))); } else { return Net::wrap(Box::new(morph())); } } "notch" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(notch_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(notch_q(*p))); } else { return Net::wrap(Box::new(notch())); } } "peak" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(peak_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(peak_q(*p))); } else { return Net::wrap(Box::new(peak())); } } "resonator" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(resonator_hz(p[0], p[1]))); } else { return Net::wrap(Box::new(resonator())); } } // -------------------- channels -------------------- "sink" => return Net::wrap(Box::new(sink())), "pass" => return Net::wrap(Box::new(pass())), "chan" => { let mut net = Net::new(0, 0); for i in p { if i == 0. { net = net | sink(); } else { net = net | pass(); } } return net; } "pan" => { if let Some(p) = p.first() { return Net::wrap(Box::new(pan(*p))); } else { return Net::wrap(Box::new(panner())); } } "join" => { if let Some(p) = p.first() { match *p as usize { 2 => return Net::wrap(Box::new(join::<U2>())), 3 => return Net::wrap(Box::new(join::<U3>())), 4 => return Net::wrap(Box::new(join::<U4>())), 5 => return Net::wrap(Box::new(join::<U5>())), 6 => return Net::wrap(Box::new(join::<U6>())), 7 => return Net::wrap(Box::new(join::<U7>())), 8 => return Net::wrap(Box::new(join::<U8>())), _ => {} } } } "split" => { if let Some(p) = p.first() { match *p as usize { 2 => return Net::wrap(Box::new(split::<U2>())), 3 => return Net::wrap(Box::new(split::<U3>())), 4 => return Net::wrap(Box::new(split::<U4>())), 5 => return Net::wrap(Box::new(split::<U5>())), 6 => return Net::wrap(Box::new(split::<U6>())), 7 => return Net::wrap(Box::new(split::<U7>())), 8 => return Net::wrap(Box::new(split::<U8>())), _ => {} } } } "reverse" => { if let Some(p) = p.first() { match *p as usize { 2 => return Net::wrap(Box::new(reverse::<U2>())), 3 => return Net::wrap(Box::new(reverse::<U3>())), 4 => return Net::wrap(Box::new(reverse::<U4>())), 5 => return Net::wrap(Box::new(reverse::<U5>())), 6 => return Net::wrap(Box::new(reverse::<U6>())), 7 => return Net::wrap(Box::new(reverse::<U7>())), 8 => return Net::wrap(Box::new(reverse::<U8>())), _ => {} } } } // -------------------- envelopes -------------------- "adsr" => { if let Some(p) = p.get(0..4) { return Net::wrap(Box::new(adsr_live(p[0], p[1], p[2], p[3]))); } } "xd" => { if let Some(p) = p.first() { let p = *p; return Net::wrap(Box::new(lfo(move |t| exp(-t * p)))); } else { return Net::wrap(Box::new(lfo_in(|t, i: &Frame<f32, U1>| exp(-t * i[0])))); } } // decay time (in seconds), decay curvature // they're power functions, so a fractional (0..1) is like log, // 1 is linear, and above 1 is exponential (the higher the steeper) "xD" => { if let Some(p) = p.get(0..2) { let p0 = p[0]; let p1 = p[1]; return Net::wrap(Box::new(lfo(move |t| { if t < p0 { ((p0 - t) / p0).powf(p1) } else { 0. } }))); } else if let Some(p) = p.first() { let p = *p; return Net::wrap(Box::new(lfo_in(move |t, i: &Frame<f32, U1>| { if t < i[0] { ((i[0] - t) / i[0]).powf(p) } else { 0. } }))); } else { return Net::wrap(Box::new(lfo_in(|t, i: &Frame<f32, U2>| { if t < i[0] { ((i[0] - t) / i[0]).powf(i[1]) } else { 0. } }))); } } // attack time, attack curvature, release time, release curvature "ar" => { if let Some(p) = p.get(0..4) { let (p0, p1, p2, p3) = (p[0], p[1], p[2], p[3]); return Net::wrap(Box::new(lfo(move |t| { if t < p0 { (t / p0).powf(p1) } else if t < p0 + p2 { ((p2 - (t - p0)) / p2).powf(p3) } else { 0. } }))); } else if let Some(p) = p.get(0..2) { let (p0, p1) = (p[0], p[1]); return Net::wrap(Box::new(lfo_in(move |t, i: &Frame<f32, U2>| { if t < i[0] { (t / i[0]).powf(p0) } else if t < i[0] + i[1] { ((i[1] - (t - i[0])) / i[1]).powf(p1) } else { 0. } }))); } else { return Net::wrap(Box::new(lfo_in(|t, i: &Frame<f32, U4>| { if t < i[0] { (t / i[0]).powf(i[1]) } else if t < i[0] + i[2] { ((i[2] - (t - i[0])) / i[2]).powf(i[3]) } else { 0. } }))); } } // -------------------- other -------------------- "tick" => return Net::wrap(Box::new(tick())), "shift_reg" => return Net::wrap(Box::new(An(ShiftReg::new()))), "snh" => return Net::wrap(Box::new(An(SnH::new()))), "meter" => { if let (Some(arg), Some(p)) = (args.get(1), p.first()) { if arg.starts_with("peak") { return Net::wrap(Box::new(meter(Meter::Peak(*p as f64)))); } else if arg.starts_with("rms") { return Net::wrap(Box::new(meter(Meter::Rms(*p as f64)))); } } } "chorus" => { if let Some(p) = p.get(0..4) { return Net::wrap(Box::new(chorus(p[0] as u64, p[1], p[2], p[3]))); } } "clip" => { if let Some(p) = p.get(0..2) { if p[0] < p[1] { return Net::wrap(Box::new(clip_to(p[0], p[1]))); } else { return Net::wrap(Box::new(clip_to(p[1], p[0]))); } } else { return Net::wrap(Box::new(clip())); } } "declick" => { if let Some(p) = p.first() { return Net::wrap(Box::new(declick_s(*p))); } else { return Net::wrap(Box::new(declick())); } } "delay" => { if let Some(p) = p.first() { return Net::wrap(Box::new(delay(*p))); } } "hold" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(hold_hz(p[0], p[1]))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(hold(*p))); } } "limiter" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(limiter(p[0], p[1]))); } } "limiter_stereo" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(limiter_stereo(p[0], p[1]))); } } "reverb_stereo" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(reverb_stereo(p[0], p[1], p[2]))); } else if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(reverb_stereo(p[0], p[1], 1.))); } else if let Some(p) = p.first() { return Net::wrap(Box::new(reverb_stereo(*p, 5., 1.))); } } "reverb_mono" => { if let Some(p) = p.get(0..3) { return Net::wrap(Box::new(split() >> reverb_stereo(p[0], p[1], p[2]) >> join())); } else if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(split() >> reverb_stereo(p[0], p[1], 1.) >> join())); } else if let Some(p) = p.first() { return Net::wrap(Box::new(split() >> reverb_stereo(*p, 5., 1.) >> join())); } } "tap" => { if let Some(p) = p.get(0..2) { let p0 = p[0].max(0.); let p1 = p[1].max(0.); return Net::wrap(Box::new(tap(min(p0, p1), max(p0, p1)))); } } "tap_linear" => { if let Some(p) = p.get(0..2) { let p0 = p[0].max(0.); let p1 = p[1].max(0.); return Net::wrap(Box::new(tap_linear(min(p0, p1), max(p0, p1)))); } } "samp_delay" => { if let Some(p) = p.first() { return Net::wrap(Box::new(An(SampDelay::new(*p as usize)))); } } // thanks to the pdhalf csound opcode // https://github.com/csound/csound/blob/master/Opcodes/shape.c#L299 "pdhalf_bi" => { return Net::wrap(Box::new(map(|i: &Frame<f32, U2>| { let midpoint = i[1].clamp(-1., 1.); if i[0] < midpoint { let leftslope = if midpoint != -1. { (midpoint + 1.).recip() } else { 0. }; leftslope * i[0] } else { let rightslope = if midpoint != 1. { (1. - midpoint).recip() } else { 0. }; rightslope * (i[0] - midpoint) + 0.5 } }))); } "pdhalf_uni" => { return Net::wrap(Box::new(map(|i: &Frame<f32, U2>| { let midpoint = if i[1] >= 1. { 1. } else if i[1] <= -1. { 0. } else { (i[1] + 1.) / 2. }; if i[0] < midpoint { let leftslope = if midpoint != 0. { 0.5 / midpoint } else { 0. }; leftslope * i[0] } else { let rightslope = if midpoint != 1. { 0.5 / (1. - midpoint) } else { 0. }; rightslope * (i[0] - midpoint) + 0.5 } }))); } // -------------------- math -------------------- "add" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(add((p0, p1, p2, p3, p4, p5, p6, p7)))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(add((p0, p1, p2, p3, p4, p5, p6)))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(add((p0, p1, p2, p3, p4, p5)))) } [p0, p1, p2, p3, p4, ..] => return Net::wrap(Box::new(add((p0, p1, p2, p3, p4)))), [p0, p1, p2, p3, ..] => return Net::wrap(Box::new(add((p0, p1, p2, p3)))), [p0, p1, p2, ..] => return Net::wrap(Box::new(add((p0, p1, p2)))), [p0, p1, ..] => return Net::wrap(Box::new(add((p0, p1)))), [p0, ..] => return Net::wrap(Box::new(add(p0))), _ => return Net::wrap(Box::new(add(1.))), }, "sub" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(sub((p0, p1, p2, p3, p4, p5, p6, p7)))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(sub((p0, p1, p2, p3, p4, p5, p6)))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(sub((p0, p1, p2, p3, p4, p5)))) } [p0, p1, p2, p3, p4, ..] => return Net::wrap(Box::new(sub((p0, p1, p2, p3, p4)))), [p0, p1, p2, p3, ..] => return Net::wrap(Box::new(sub((p0, p1, p2, p3)))), [p0, p1, p2, ..] => return Net::wrap(Box::new(sub((p0, p1, p2)))), [p0, p1, ..] => return Net::wrap(Box::new(sub((p0, p1)))), [p0, ..] => return Net::wrap(Box::new(sub(p0))), _ => return Net::wrap(Box::new(sub(1.))), }, "mul" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(mul((p0, p1, p2, p3, p4, p5, p6, p7)))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(mul((p0, p1, p2, p3, p4, p5, p6)))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(mul((p0, p1, p2, p3, p4, p5)))) } [p0, p1, p2, p3, p4, ..] => return Net::wrap(Box::new(mul((p0, p1, p2, p3, p4)))), [p0, p1, p2, p3, ..] => return Net::wrap(Box::new(mul((p0, p1, p2, p3)))), [p0, p1, p2, ..] => return Net::wrap(Box::new(mul((p0, p1, p2)))), [p0, p1, ..] => return Net::wrap(Box::new(mul((p0, p1)))), [p0, ..] => return Net::wrap(Box::new(mul(p0))), _ => return Net::wrap(Box::new(mul(1.))), }, "div" => match p[..] { [p0, p1, p2, p3, p4, p5, p6, p7, ..] => { return Net::wrap(Box::new(mul(( 1. / p0, 1. / p1, 1. / p2, 1. / p3, 1. / p4, 1. / p5, 1. / p6, 1. / p7, )))) } [p0, p1, p2, p3, p4, p5, p6, ..] => { return Net::wrap(Box::new(mul(( 1. / p0, 1. / p1, 1. / p2, 1. / p3, 1. / p4, 1. / p5, 1. / p6, )))) } [p0, p1, p2, p3, p4, p5, ..] => { return Net::wrap(Box::new(mul(( 1. / p0, 1. / p1, 1. / p2, 1. / p3, 1. / p4, 1. / p5, )))) } [p0, p1, p2, p3, p4, ..] => { return Net::wrap(Box::new(mul((1. / p0, 1. / p1, 1. / p2, 1. / p3, 1. / p4)))) } [p0, p1, p2, p3, ..] => { return Net::wrap(Box::new(mul((1. / p0, 1. / p1, 1. / p2, 1. / p3)))) } [p0, p1, p2, ..] => return Net::wrap(Box::new(mul((1. / p0, 1. / p1, 1. / p2)))), [p0, p1, ..] => return Net::wrap(Box::new(mul((1. / p0, 1. / p1)))), [p0, ..] => return Net::wrap(Box::new(mul(1. / p0))), _ => return Net::wrap(Box::new(mul(1.))), }, "rotate" => { if let Some(p) = p.get(0..2) { return Net::wrap(Box::new(rotate(p[0], p[1]))); } } "t" => return Net::wrap(Box::new(lfo(|t| t))), "rise" => { return Net::wrap(Box::new( (pass() ^ tick()) >> map(|i: &Frame<f32, U2>| if i[0] > i[1] { 1. } else { 0. }), )); } "fall" => { return Net::wrap(Box::new( (pass() ^ tick()) >> map(|i: &Frame<f32, U2>| if i[0] < i[1] { 1. } else { 0. }), )); } ">" => { if let Some(p) = p.first() { let p = *p; return Net::wrap(Box::new(map( move |i: &Frame<f32, U1>| if i[0] > p { 1. } else { 0. }, ))); } else { return Net::wrap(Box::new(map( |i: &Frame<f32, U2>| if i[0] > i[1] { 1. } else { 0. }, ))); } } "<" => { if let Some(p) = p.first() { let p = *p; return Net::wrap(Box::new(map( move |i: &Frame<f32, U1>| if i[0] < p { 1. } else { 0. }, ))); } else { return Net::wrap(Box::new(map(
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
true
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/circles.rs
src/circles.rs
use bevy::{ prelude::*, render::view::{RenderLayers, VisibleEntities}, sprite::{Mesh2dHandle, WithMesh2d}, text::Text2dBounds, }; use fundsp::net::Net; use crate::{components::*, functions::*}; pub fn spawn_circles( mut commands: Commands, mouse_button_input: Res<ButtonInput<MouseButton>>, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, mut depth: Local<f32>, cursor: Res<CursorInfo>, keyboard_input: Res<ButtonInput<KeyCode>>, default_color: Res<DefaultDrawColor>, default_verts: Res<DefaultDrawVerts>, mut polygon_handles: ResMut<PolygonHandles>, ) { if mouse_button_input.just_released(MouseButton::Left) && !keyboard_input.pressed(KeyCode::Space) { let r = cursor.f.distance(cursor.i); let v = default_verts.0; let color = default_color.0; if polygon_handles.0.len() <= v { polygon_handles.0.resize(v + 1, None); } if polygon_handles.0[v].is_none() { let handle = meshes.add(RegularPolygon::new(1., v)).into(); polygon_handles.0[v] = Some(handle); } let (sndr, rcvr) = crossbeam_channel::bounded(1); commands.spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[v].clone().unwrap(), material: materials.add(ColorMaterial::from_color(color)), transform: Transform { translation: cursor.i.extend(*depth), scale: Vec3::new(r, r, 1.), ..default() }, ..default() }, Vertices(v), Col(color), Number(0.), Arr(Vec::new()), Op("empty".to_string()), Targets(Vec::new()), Holes(Vec::new()), Order(0), ( OpNum(0), Network(Net::new(0, 0)), NetIns(Vec::new()), OpChanged(false), LostWH(false), NetChannel(sndr, rcvr), ), RenderLayers::layer(1), )); *depth += 0.01; } } pub fn highlight_selected( mut commands: Commands, mut materials: ResMut<Assets<ColorMaterial>>, selected: Query<(Entity, &Vertices, &Transform), (With<Selected>, Without<Highlight>)>, deselected: Query<Entity, (With<Highlight>, Without<Selected>)>, highlight_query: Query<&Highlight>, highlight_color: Res<HighlightColor>, polygon_handles: Res<PolygonHandles>, ) { for (e, v, t) in selected.iter() { let trans = t.translation.xy().extend(t.translation.z - 0.00001); let highlight = commands .spawn(ColorMesh2dBundle { mesh: polygon_handles.0[v.0].clone().unwrap(), material: materials.add(ColorMaterial::from_color(highlight_color.0)), transform: Transform { translation: trans, scale: Vec3::new(t.scale.x + 5., t.scale.y + 5., 1.), rotation: t.rotation, }, ..default() }) .id(); commands.entity(e).insert(Highlight(highlight)); } for e in deselected.iter() { let highlight = highlight_query.get(e).unwrap(); commands.entity(highlight.0).despawn(); commands.entity(e).remove::<Highlight>(); } } pub fn transform_highlights( moved: Query<(&Transform, &Highlight), Changed<Transform>>, changed_verts: Query<(&Vertices, &Highlight), Changed<Vertices>>, mut trans_query: Query<&mut Transform, Without<Highlight>>, mut handle_query: Query<&mut Mesh2dHandle>, polygon_handles: Res<PolygonHandles>, ) { for (t, h) in moved.iter() { // FIXME(amy): next_up/down would make offsets like this accurate // avoiding the funky behavior with bigger z values here let trans = t.translation.xy().extend(t.translation.z - 0.00001); trans_query.get_mut(h.0).unwrap().translation = trans; trans_query.get_mut(h.0).unwrap().rotation = t.rotation; trans_query.get_mut(h.0).unwrap().scale.x = t.scale.x + 5.; trans_query.get_mut(h.0).unwrap().scale.y = t.scale.y + 5.; } for (v, h) in changed_verts.iter() { if let Ok(mut handle) = handle_query.get_mut(h.0) { *handle = polygon_handles.0[v.0].clone().unwrap(); } } } pub fn update_selection( mut commands: Commands, mouse_button_input: Res<ButtonInput<MouseButton>>, circle_trans_query: Query<&Transform, With<Vertices>>, visible: Query<&VisibleEntities>, selected: Query<Entity, With<Selected>>, cursor: Res<CursorInfo>, keyboard_input: Res<ButtonInput<KeyCode>>, mut top_clicked_circle: Local<Option<(Entity, f32)>>, order_query: Query<(), With<Order>>, // non-hole circle mut clicked_on_space: ResMut<ClickedOnSpace>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } let shift = keyboard_input.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]); let ctrl = keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]); let alt = keyboard_input.any_pressed([KeyCode::AltLeft, KeyCode::AltRight]); if mouse_button_input.just_pressed(MouseButton::Left) { // NOTE apparently this can be missed in just_released? // so an invalid id when deleted. very rare tho (only 2 panics ever) // we only use the id here, so it's better updated here *top_clicked_circle = None; for e in visible.single().get::<WithMesh2d>() { if let Ok(t) = circle_trans_query.get(*e) { if top_clicked_circle.is_some() { if t.translation.z > top_clicked_circle.unwrap().1 && cursor.i.distance_squared(t.translation.xy()) < t.scale.x * t.scale.x { *top_clicked_circle = Some((*e, t.translation.z)); } } else if cursor.i.distance_squared(t.translation.xy()) < t.scale.x * t.scale.x { *top_clicked_circle = Some((*e, t.translation.z)); } } } if let Some(top) = *top_clicked_circle { clicked_on_space.0 = false; if !selected.contains(top.0) { if shift { commands.entity(top.0).insert(Selected); } else { for entity in selected.iter() { commands.entity(entity).remove::<Selected>(); } commands.entity(top.0).insert(Selected); } } else if ctrl { commands.entity(top.0).remove::<Selected>(); } } else { clicked_on_space.0 = true; } } else if mouse_button_input.just_released(MouseButton::Left) && top_clicked_circle.is_none() { if !shift { for entity in selected.iter() { commands.entity(entity).remove::<Selected>(); } } // select those in the dragged area let (min_x, max_x) = if cursor.i.x < cursor.f.x { (cursor.i.x, cursor.f.x) } else { (cursor.f.x, cursor.i.x) }; let (min_y, max_y) = if cursor.i.y < cursor.f.y { (cursor.i.y, cursor.f.y) } else { (cursor.f.y, cursor.i.y) }; for e in visible.single().get::<WithMesh2d>() { if let Ok(t) = circle_trans_query.get(*e) { if (min_x < t.translation.x && t.translation.x < max_x) && (min_y < t.translation.y && t.translation.y < max_y) { // only select holes if ctrl is held if (ctrl && order_query.contains(*e)) // only select non-holes if alt is held || (alt && !order_query.contains(*e)) { continue; } commands.entity(*e).insert(Selected); } } } } } pub fn move_selected( mouse_button_input: Res<ButtonInput<MouseButton>>, cursor: Res<CursorInfo>, mut circle_query: Query<&mut Transform, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, drag_modes: Res<DragModes>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if drag_modes.t { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { for mut t in circle_query.iter_mut() { t.translation.x += cursor.d.x; t.translation.y += cursor.d.y; } } if keyboard_input.pressed(KeyCode::ArrowUp) { for mut t in circle_query.iter_mut() { t.translation.y += 1.; } } if keyboard_input.pressed(KeyCode::ArrowDown) { for mut t in circle_query.iter_mut() { t.translation.y -= 1.; } } if keyboard_input.pressed(KeyCode::ArrowRight) { for mut t in circle_query.iter_mut() { t.translation.x += 1.; } } if keyboard_input.pressed(KeyCode::ArrowLeft) { for mut t in circle_query.iter_mut() { t.translation.x -= 1.; } } } } pub fn rotate_selected( mouse_button_input: Res<ButtonInput<MouseButton>>, cursor: Res<CursorInfo>, mut query: Query<&mut Transform, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, drag_modes: Res<DragModes>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if drag_modes.o { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { for mut t in query.iter_mut() { t.rotate_z(cursor.d.y / 100.); } } if keyboard_input.any_pressed([KeyCode::ArrowUp, KeyCode::ArrowRight]) { for mut t in query.iter_mut() { t.rotate_z(0.01); } } if keyboard_input.any_pressed([KeyCode::ArrowDown, KeyCode::ArrowLeft]) { for mut t in query.iter_mut() { t.rotate_z(-0.01); } } } } pub fn update_color( mouse_button_input: Res<ButtonInput<MouseButton>>, cursor: Res<CursorInfo>, mut query: Query<&mut Col, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, drag_modes: Res<DragModes>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { if drag_modes.h { for mut c in query.iter_mut() { let h = (c.0.hue + cursor.d.x).clamp(0., 360.); c.0.hue = h; } } if drag_modes.s { for mut c in query.iter_mut() { let s = (c.0.saturation + cursor.d.x / 100.).clamp(0., 1.); c.0.saturation = s; } } if drag_modes.l { for mut c in query.iter_mut() { let l = (c.0.lightness + cursor.d.x / 100.).clamp(0., 1.); c.0.lightness = l; } } if drag_modes.a { for mut c in query.iter_mut() { let a = (c.0.alpha + cursor.d.x / 100.).clamp(0., 1.); c.0.alpha = a; } } } if keyboard_input.any_pressed([KeyCode::ArrowLeft, KeyCode::ArrowDown]) { for mut c in query.iter_mut() { if drag_modes.h { let h = (c.0.hue - 1.).clamp(0., 360.); c.0.hue = h; } if drag_modes.s { let s = (c.0.saturation - 0.01).clamp(0., 1.); c.0.saturation = s; } if drag_modes.l { let l = (c.0.lightness - 0.01).clamp(0., 1.); c.0.lightness = l; } if drag_modes.a { let a = (c.0.alpha - 0.01).clamp(0., 1.); c.0.alpha = a; } } } if keyboard_input.any_pressed([KeyCode::ArrowRight, KeyCode::ArrowUp]) { for mut c in query.iter_mut() { if drag_modes.h { let h = (c.0.hue + 1.).clamp(0., 360.); c.0.hue = h; } if drag_modes.s { let s = (c.0.saturation + 0.01).clamp(0., 1.); c.0.saturation = s; } if drag_modes.l { let l = (c.0.lightness + 0.01).clamp(0., 1.); c.0.lightness = l; } if drag_modes.a { let a = (c.0.alpha + 0.01).clamp(0., 1.); c.0.alpha = a; } } } } pub fn update_mat( mut mats: ResMut<Assets<ColorMaterial>>, material_ids: Query<&Handle<ColorMaterial>>, color_query: Query<(Entity, &Col), Changed<Col>>, ) { for (id, c) in color_query.iter() { if let Ok(mat_id) = material_ids.get(id) { let mat = mats.get_mut(mat_id).unwrap(); mat.color = Color::Hsla(c.0); } } } pub fn update_radius( mut query: Query<&mut Transform, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, cursor: Res<CursorInfo>, mouse_button_input: Res<ButtonInput<MouseButton>>, drag_modes: Res<DragModes>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if drag_modes.r { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { for mut t in query.iter_mut() { t.scale.x = (t.scale.x + cursor.d.y).max(0.); t.scale.y = (t.scale.y + cursor.d.y).max(0.); } } if keyboard_input.any_pressed([KeyCode::ArrowUp, KeyCode::ArrowRight]) { for mut t in query.iter_mut() { t.scale.x = (t.scale.x + 1.).max(0.); t.scale.y = (t.scale.y + 1.).max(0.); } } if keyboard_input.any_pressed([KeyCode::ArrowDown, KeyCode::ArrowLeft]) { for mut t in query.iter_mut() { t.scale.x = (t.scale.x - 1.).max(0.); t.scale.y = (t.scale.y - 1.).max(0.); } } } } pub fn update_vertices( mut query: Query<&mut Vertices, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, drag_modes: Res<DragModes>, mouse_button_input: Res<ButtonInput<MouseButton>>, cursor: Res<CursorInfo>, mut delta: Local<f32>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if drag_modes.v { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { *delta += cursor.d.y / 10.; let d = *delta as i32; if d >= 1 { for mut v in query.iter_mut() { v.0 = (v.0 as i32 + d).min(64) as usize; } *delta = 0.; } else if d <= -1 { for mut v in query.iter_mut() { v.0 = (v.0 as i32 + d).max(3) as usize; } *delta = 0.; } } if keyboard_input.any_just_pressed([KeyCode::ArrowUp, KeyCode::ArrowRight]) { for mut v in query.iter_mut() { v.0 = (v.0 + 1).min(64); } } if keyboard_input.any_just_pressed([KeyCode::ArrowDown, KeyCode::ArrowLeft]) { for mut v in query.iter_mut() { v.0 = (v.0 - 1).max(3); } } } } pub fn update_mesh( mut meshes: ResMut<Assets<Mesh>>, mut handle_query: Query<&mut Mesh2dHandle>, query: Query<(Entity, &Vertices), Changed<Vertices>>, mut polygon_handles: ResMut<PolygonHandles>, ) { for (id, v) in query.iter() { if polygon_handles.0.len() <= v.0 { polygon_handles.0.resize(v.0 + 1, None); } if polygon_handles.0[v.0].is_none() { let handle = meshes.add(RegularPolygon::new(1., v.0)).into(); polygon_handles.0[v.0] = Some(handle); } if let Ok(mut handle) = handle_query.get_mut(id) { *handle = polygon_handles.0[v.0].clone().unwrap(); } } } pub fn update_num( mut query: Query<&mut Number, With<Selected>>, keyboard_input: Res<ButtonInput<KeyCode>>, cursor: Res<CursorInfo>, mouse_button_input: Res<ButtonInput<MouseButton>>, drag_modes: Res<DragModes>, ) { if keyboard_input.pressed(KeyCode::Space) { return; } if drag_modes.n { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) { for mut n in query.iter_mut() { n.0 += cursor.d.y / 10.; } } if keyboard_input.pressed(KeyCode::ArrowUp) { for mut n in query.iter_mut() { n.0 += 0.01; } } if keyboard_input.pressed(KeyCode::ArrowDown) { for mut n in query.iter_mut() { n.0 -= 0.01; } } } } pub fn spawn_info_text( show_info_text: Res<ShowInfoText>, // fully loaded (not an orphaned hole) that's why With<RenderLayers> query: Query<Entity, (With<Vertices>, Without<InfoText>, With<RenderLayers>)>, text_size: Res<TextSize>, mut commands: Commands, ) { if show_info_text.0 { for e in query.iter() { let id_text = if show_info_text.1 { format!("{}\n", e) } else { String::new() }; let info_text = commands .spawn(Text2dBundle { text: Text::from_sections([ TextSection::new( id_text, TextStyle { color: Color::BLACK, font_size: 120., ..default() }, ), TextSection::new( "", TextStyle { color: Color::BLACK, font_size: 120., ..default() }, ), TextSection::new( "", TextStyle { color: Color::BLACK, font_size: 120., ..default() }, ), TextSection::new( "", TextStyle { color: Color::BLACK, font_size: 120., ..default() }, ), ]) .with_justify(JustifyText::Left), transform: Transform::from_scale(Vec3::new(text_size.0, text_size.0, 1.)), ..default() }) .id(); commands.entity(e).insert(InfoText(info_text)); } } } pub fn update_info_text( mut query: Query<(Entity, &mut InfoText)>, mut text_query: Query<&mut Text>, mut text_bounds: Query<&mut Text2dBounds>, mut trans_query: Query<&mut Transform>, mut order_query: Query<&mut Order>, mut num_query: Query<&mut Number>, mut op_query: Query<&mut Op>, mut white_hole_query: Query<&mut WhiteHole>, black_hole_query: Query<&BlackHole>, mut color_query: Query<&mut Col>, text_size: Res<TextSize>, ) { for (id, info) in query.iter_mut() { let t = trans_query.get_mut(id).unwrap(); if t.is_changed() || info.is_added() || text_size.is_changed() { text_bounds.get_mut(info.0).unwrap().size.x = t.scale.x * text_size.0.recip(); let t = t.translation; trans_query.get_mut(info.0).unwrap().translation = t.xy().extend(t.z + 0.00001); } if let Ok(ord) = order_query.get_mut(id) { if ord.is_changed() || info.is_added() { text_query.get_mut(info.0).unwrap().sections[1].value = format!("{}\n", ord.0); } } if let Ok(n) = num_query.get_mut(id) { if n.is_changed() || info.is_added() { text_query.get_mut(info.0).unwrap().sections[3].value = n.0.to_string(); } } if let Ok(op) = op_query.get_mut(id) { if op.is_changed() || info.is_added() { text_query.get_mut(info.0).unwrap().sections[2].value = format!("{}\n", op.0); } } if let Ok(wh) = white_hole_query.get_mut(id) { if wh.is_changed() || info.is_added() { text_query.get_mut(info.0).unwrap().sections[1].value = lt_to_string(wh.link_types.1); } } if let Ok(bh) = black_hole_query.get(id) { if let Ok(wh) = white_hole_query.get_mut(bh.wh) { if wh.is_changed() || info.is_added() { text_query.get_mut(info.0).unwrap().sections[1].value = lt_to_string(wh.link_types.0); } } } let c = color_query.get_mut(id).unwrap(); if c.is_changed() || info.is_added() { let l = if c.0.lightness < 0.3 { 1. } else { 0. }; let opposite_color = Color::hsl(0., 1.0, l); let t = &mut text_query.get_mut(info.0).unwrap(); for section in &mut t.sections { section.style.color = opposite_color; } } } } pub fn delete_selected( mut commands: Commands, selected_query: Query<Entity, With<Selected>>, mut holes_query: Query<&mut Holes>, bh_query: Query<&BlackHole>, wh_query: Query<&WhiteHole>, arrow_query: Query<&ConnectionArrow>, info_text_query: Query<&InfoText>, highlight_query: Query<&Highlight>, mut order_change: EventWriter<OrderChange>, mut lost_wh_query: Query<&mut LostWH>, ) { let mut order = false; for e in selected_query.iter() { if let Ok(holes) = holes_query.get(e) { // it's a circle for hole in &holes.0.clone() { if let Ok(bh) = bh_query.get(*hole) { let arrow = arrow_query.get(bh.wh).unwrap().0; commands.entity(arrow).despawn(); commands.entity(*hole).despawn(); commands.entity(bh.wh).despawn(); if let Ok(wh_text) = info_text_query.get(bh.wh) { commands.entity(wh_text.0).despawn(); } if let Ok(bh_text) = info_text_query.get(*hole) { commands.entity(bh_text.0).despawn(); } if let Ok(highlight) = highlight_query.get(bh.wh) { commands.entity(highlight.0).despawn(); } if let Ok(highlight) = highlight_query.get(*hole) { commands.entity(highlight.0).despawn(); } lost_wh_query.get_mut(bh.wh_parent).unwrap().0 = true; holes_query.get_mut(bh.wh_parent).unwrap().0.retain(|x| *x != bh.wh); } else if let Ok(wh) = wh_query.get(*hole) { // don't remove things that will get removed later if selected_query.contains(wh.bh_parent) { continue; } let arrow = arrow_query.get(*hole).unwrap().0; commands.entity(arrow).despawn(); commands.entity(wh.bh).despawn(); commands.entity(*hole).despawn(); if let Ok(wh_text) = info_text_query.get(*hole) { commands.entity(wh_text.0).despawn(); } if let Ok(bh_text) = info_text_query.get(wh.bh) { commands.entity(bh_text.0).despawn(); } if let Ok(highlight) = highlight_query.get(*hole) { commands.entity(highlight.0).despawn(); } if let Ok(highlight) = highlight_query.get(wh.bh) { commands.entity(highlight.0).despawn(); } holes_query.get_mut(wh.bh_parent).unwrap().0.retain(|x| *x != wh.bh); } } order = true; if let Ok(text) = info_text_query.get(e) { commands.entity(text.0).despawn(); } if let Ok(highlight) = highlight_query.get(e) { commands.entity(highlight.0).despawn(); } commands.entity(e).despawn(); } else { // it's a hole if let Ok(wh) = wh_query.get(e) { // get parent let parent = bh_query.get(wh.bh).unwrap().wh_parent; if selected_query.contains(parent) { continue; } if selected_query.contains(wh.bh_parent) { continue; } // remove from parents' vecs holes_query.get_mut(parent).unwrap().0.retain(|x| *x != e); holes_query.get_mut(wh.bh_parent).unwrap().0.retain(|x| *x != wh.bh); // parent has lost a wh lost_wh_query.get_mut(parent).unwrap().0 = true; let arrow = arrow_query.get(e).unwrap().0; commands.entity(arrow).despawn(); commands.entity(e).despawn(); commands.entity(wh.bh).despawn(); // info texts and highlights if let Ok(wh_text) = info_text_query.get(e) { commands.entity(wh_text.0).despawn(); } if let Ok(bh_text) = info_text_query.get(wh.bh) { commands.entity(bh_text.0).despawn(); } if let Ok(highlight) = highlight_query.get(e) { commands.entity(highlight.0).despawn(); } if let Ok(highlight) = highlight_query.get(wh.bh) { commands.entity(highlight.0).despawn(); } } else if let Ok(bh) = bh_query.get(e) { let parent = wh_query.get(bh.wh).unwrap().bh_parent; if selected_query.contains(parent) { continue; } if selected_query.contains(bh.wh_parent) { continue; } if selected_query.contains(bh.wh) { continue; } holes_query.get_mut(parent).unwrap().0.retain(|x| *x != e); holes_query.get_mut(bh.wh_parent).unwrap().0.retain(|x| *x != bh.wh); lost_wh_query.get_mut(bh.wh_parent).unwrap().0 = true; let arrow = arrow_query.get(bh.wh).unwrap().0; commands.entity(arrow).despawn(); commands.entity(e).despawn(); commands.entity(bh.wh).despawn(); if let Ok(wh_text) = info_text_query.get(e) { commands.entity(wh_text.0).despawn(); } if let Ok(bh_text) = info_text_query.get(bh.wh) { commands.entity(bh_text.0).despawn(); } if let Ok(highlight) = highlight_query.get(e) { commands.entity(highlight.0).despawn(); } if let Ok(highlight) = highlight_query.get(bh.wh) { commands.entity(highlight.0).despawn(); } } } } if order { order_change.send_default(); } } pub fn open_after_drag( mouse_button_input: Res<ButtonInput<MouseButton>>, keyboard_input: Res<ButtonInput<KeyCode>>, drag_modes: Res<DragModes>, query: Query<&Holes, With<Selected>>, mut white_hole_query: Query<&mut WhiteHole>, black_hole_query: Query<&BlackHole>, ) { let arrows = [KeyCode::ArrowDown, KeyCode::ArrowUp, KeyCode::ArrowLeft, KeyCode::ArrowRight]; if keyboard_input.any_pressed(arrows) || mouse_button_input.pressed(MouseButton::Left) { let mut lts_to_open = Vec::new(); if drag_modes.t { lts_to_open.push(-3); lts_to_open.push(-4); } if drag_modes.r { lts_to_open.push(-2); } if drag_modes.n { lts_to_open.push(-1); } if drag_modes.h { lts_to_open.push(-6); } if drag_modes.s { lts_to_open.push(-7); } if drag_modes.l { lts_to_open.push(-8); } if drag_modes.a { lts_to_open.push(-9); } if drag_modes.o { lts_to_open.push(-12); } if drag_modes.v { lts_to_open.push(-11); } for holes in query.iter() { for hole in &holes.0 { if let Ok(bh) = black_hole_query.get(*hole) { if let Ok(wh) = white_hole_query.get(bh.wh) { if lts_to_open.contains(&wh.link_types.0) { white_hole_query.get_mut(bh.wh).unwrap().open = true; } } } } } } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/commands.rs
src/commands.rs
use bevy::{ app::AppExit, core_pipeline::bloom::{BloomCompositeMode, BloomSettings}, input::keyboard::{Key, KeyboardInput}, prelude::*, render::view::{RenderLayers, VisibleEntities}, sprite::WithMesh2d, }; use crate::{components::*, functions::*}; use fundsp::audiounit::AudioUnit; use copypasta::ClipboardProvider; use cpal::traits::{DeviceTrait, HostTrait}; pub fn command_parser( keyboard_input: Res<ButtonInput<KeyCode>>, mut key_event: EventReader<KeyboardInput>, mut command_line_text: Query<&mut Text, With<CommandText>>, circle_query: Query<Entity, With<Vertices>>, mut next_mode: ResMut<NextState<Mode>>, mode: Res<State<Mode>>, mut commands: Commands, asset_server: Res<AssetServer>, info_text_query: Query<(Entity, &InfoText)>, holes_query: Query<&Holes>, mut show_info_text: ResMut<ShowInfoText>, ( mut op_query, mut num_query, mut col_query, mut trans_query, mut arr_query, mut order_query, selected_query, mut white_hole_query, black_hole_query, mut order_change, mut vertices_query, mut save_event, mut copy_event, mut delete_event, mut targets_query, mut render_layers, ): ( Query<&mut Op>, Query<&mut Number>, Query<&mut Col>, Query<&mut Transform>, Query<&mut Arr>, Query<&mut Order>, Query<Entity, With<Selected>>, Query<&mut WhiteHole>, Query<&BlackHole>, EventWriter<OrderChange>, Query<&mut Vertices>, EventWriter<SaveCommand>, EventWriter<CopyCommand>, EventWriter<DeleteCommand>, Query<&mut Targets>, Query<&mut RenderLayers, With<Camera>>, ), ( mut net_query, mut op_changed_query, mut exit_event, mut drag_modes, mut default_color, mut default_verts, mut default_lt, version, visible, mut out_device_event, mut in_device_event, mut node_limit, mut op_num_query, mut clipboard, paste_chan, mut bloom, ): ( Query<&mut Network>, Query<&mut OpChanged>, EventWriter<AppExit>, ResMut<DragModes>, ResMut<DefaultDrawColor>, ResMut<DefaultDrawVerts>, ResMut<DefaultLT>, Res<Version>, Query<&VisibleEntities>, EventWriter<OutDeviceCommand>, EventWriter<InDeviceCommand>, ResMut<NodeLimit>, Query<&mut OpNum>, ResMut<SystemClipboard>, Res<PasteChannel>, Query<&mut BloomSettings, With<Camera>>, ), (mut ortho, cam): (Query<&mut OrthographicProjection>, Query<Entity, With<Camera>>), ) { let clt = &mut command_line_text.single_mut(); if key_event.is_empty() && !clt.is_changed() && !keyboard_input.just_released(KeyCode::KeyT) { return; } let text = &mut clt.sections[0].value; if *mode.get() == Mode::Draw { // exit to edit if keyboard_input.any_just_pressed([KeyCode::Escape, KeyCode::KeyE]) { text.clear(); next_mode.set(Mode::Edit); key_event.clear(); // we have an 'e' that we don't want } // switch to connect mode if keyboard_input.just_pressed(KeyCode::KeyC) { *text = "-- CONNECT --".to_string(); next_mode.set(Mode::Connect); } } else if *mode.get() == Mode::Connect { // edit the link type if text.starts_with("-- CONNECT") && keyboard_input.just_pressed(KeyCode::KeyC) { *text = "-- LT --> ".to_string(); return; } if text.starts_with("-- LT --> ") { for key in key_event.read() { if key.state.is_pressed() { if let Key::Character(c) = &key.logical_key { if text.len() == 10 { default_lt.0 .0 = str_to_lt(c); text.push_str(c); } else if text.len() == 11 { default_lt.0 .1 = str_to_lt(c); *text = "-- CONNECT --".to_string(); } } } } return; } if !keyboard_input.pressed(KeyCode::KeyT) { *text = format!( "-- CONNECT -- ({} {})", lt_to_string(default_lt.0 .0), lt_to_string(default_lt.0 .1) ); } // exit to edit if keyboard_input.any_just_pressed([KeyCode::Escape, KeyCode::KeyE]) { text.clear(); next_mode.set(Mode::Edit); key_event.clear(); // consume the 'e' when exiting to edit } // target if keyboard_input.just_pressed(KeyCode::KeyT) { *text = "-- TARGET --".to_string(); } // switch to draw mode if keyboard_input.just_pressed(KeyCode::KeyD) { *text = "-- DRAW --".to_string(); next_mode.set(Mode::Draw); } } else if *mode.get() == Mode::Edit { if keyboard_input.just_pressed(KeyCode::Delete) { delete_event.send_default(); return; } for key in key_event.read() { if key.state.is_pressed() { match &key.logical_key { Key::Character(c) => { if let Some(c) = c.chars().next() { if text.starts_with('>') { text.clear(); } if !c.is_control() && *text != "F" { text.push(c); } } } Key::Space => { if !text.ends_with(' ') && !text.is_empty() && *text != "F" { text.push(' '); } } Key::Backspace => { text.pop(); } Key::Escape => { text.clear(); } Key::Enter => { text.push('\t'); } // tab completion when? _ => {} } } } if text.ends_with('\t') { // commands starting with : let lines = text.as_str().split(';'); for line in lines { // (entity, lt) if there's a given entity let mut lt_to_open = (None, None); let mut command = line.split_ascii_whitespace(); let c0 = command.next(); match c0 { // open scene file Some(":e") => { if let Some(s) = command.next() { commands.spawn(DynamicSceneBundle { scene: asset_server.load(s.to_string()), ..default() }); } } // save scene file Some(":w") => { if let Some(s) = command.next() { save_event.send(SaveCommand(s.to_string())); } } Some(":q") => { exit_event.send_default(); } Some(":od") | Some(":id") => { let h = command.next(); let d = command.next(); let mut sr = None; let mut b = None; if let (Some(h), Some(d)) = (h, d) { let h = h.parse::<usize>(); let d = d.parse::<usize>(); if let (Ok(h), Ok(d)) = (h, d) { let samplerate = command.next(); let block = command.next(); if let Some(samplerate) = samplerate { if let Ok(samplerate) = samplerate.parse::<u32>() { sr = Some(samplerate); } } if let Some(block) = block { if let Ok(block) = block.parse::<u32>() { b = Some(block); } } if c0 == Some(":od") { out_device_event.send(OutDeviceCommand(h, d, sr, b)); } else { in_device_event.send(InDeviceCommand(h, d, sr, b)); } } } } Some(":nl") => { if let Some(s) = command.next() { if let Ok(n) = s.parse::<usize>() { node_limit.0 = n; } } } // white hole / black hole link type Some(":lt") | Some("lt") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut wh) = white_hole_query.get_mut(e) { if let Some(s) = command.next() { wh.link_types.1 = str_to_lt(s); wh.open = true; } } else if let Ok(bh) = black_hole_query.get(e) { let wh = &mut white_hole_query.get_mut(bh.wh).unwrap(); if let Some(s) = command.next() { wh.link_types.0 = str_to_lt(s); wh.open = true; } } } else { for id in selected_query.iter() { if let Ok(mut wh) = white_hole_query.get_mut(id) { wh.link_types.1 = str_to_lt(s); wh.open = true; } else if let Ok(bh) = black_hole_query.get(id) { let wh = &mut white_hole_query.get_mut(bh.wh).unwrap(); wh.link_types.0 = str_to_lt(s); wh.open = true; } } } } } Some(":dv") | Some("dv") => { if let Some(s) = command.next() { if let Ok(n) = s.parse::<usize>() { default_verts.0 = n.clamp(3, 64); } } } Some(":dc") | Some("dc") => { let mut h = 270.; let mut s = 1.; let mut l = 0.5; let mut a = 1.; if let Some(n) = command.next() { if let Ok(n) = n.parse::<f32>() { h = n; } } if let Some(n) = command.next() { if let Ok(n) = n.parse::<f32>() { s = n; } } if let Some(n) = command.next() { if let Ok(n) = n.parse::<f32>() { l = n; } } if let Some(n) = command.next() { if let Ok(n) = n.parse::<f32>() { a = n; } } default_color.0 = Hsla::new(h, s, l, a); } // toggle open a white hole (by id) Some(":ht") | Some("ht") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut wh) = white_hole_query.get_mut(e) { wh.open = !wh.open; } } } } Some(":push") | Some("push") => { if let Some(a1) = command.next() { if let Some(a2) = command.next() { if let Some(e) = str_to_id(a1) { if let Some(t) = str_to_id(a2) { if let Ok(mut targets) = targets_query.get_mut(e) { targets.0.push(t); } } else if let Ok(n) = parse_with_constants(a2) { if let Ok(mut arr) = arr_query.get_mut(e) { arr.0.push(n); } } } } else { for id in selected_query.iter() { if let Some(t) = str_to_id(a1) { if let Ok(mut targets) = targets_query.get_mut(id) { targets.0.push(t); } } else if let Ok(n) = parse_with_constants(a1) { if let Ok(mut arr) = arr_query.get_mut(id) { arr.0.push(n); } } } } } } Some(":set") | Some("set") | Some(":delta") | Some("delta") => { let c1 = command.next(); match c1 { Some("n") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut num) = num_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { num.0 = n; } else { num.0 += n; } lt_to_open = (Some(e), Some(-1)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut num) = num_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { num.0 = n; } else { num.0 += n; } } } lt_to_open = (None, Some(-1)); } } } Some("r") | Some("rx") | Some("ry") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut trans) = trans_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { if c1 == Some("r") { trans.scale.x = n.max(0.); trans.scale.y = n.max(0.); } else if c1 == Some("rx") { trans.scale.x = n.max(0.); } else { trans.scale.y = n.max(0.); } } else if c1 == Some("r") { trans.scale.x = (trans.scale.x + n).max(0.); trans.scale.y = (trans.scale.y + n).max(0.); } else if c1 == Some("rx") { trans.scale.x = (trans.scale.x + n).max(0.); } else { trans.scale.y = (trans.scale.y + n).max(0.); } lt_to_open = (Some(e), Some(-2)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut trans) = trans_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { if c1 == Some("r") { trans.scale.x = n.max(0.); trans.scale.y = n.max(0.); } else if c1 == Some("rx") { trans.scale.x = n.max(0.); } else { trans.scale.y = n.max(0.); } } else if c1 == Some("r") { trans.scale.x = (trans.scale.x + n).max(0.); trans.scale.y = (trans.scale.y + n).max(0.); } else if c1 == Some("rx") { trans.scale.x = (trans.scale.x + n).max(0.); } else { trans.scale.y = (trans.scale.y + n).max(0.); } } } lt_to_open = (None, Some(-2)); } } } Some("x") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut t) = trans_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { t.translation.x = n; } else { t.translation.x += n; } lt_to_open = (Some(e), Some(-3)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut t) = trans_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { t.translation.x = n; } else { t.translation.x += n; } } } lt_to_open = (None, Some(-3)); } } } Some("y") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut t) = trans_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { t.translation.y = n; } else { t.translation.y += n; } lt_to_open = (Some(e), Some(-4)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut t) = trans_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { t.translation.y = n; } else { t.translation.y += n; } } } lt_to_open = (None, Some(-4)); } } } Some("z") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut t) = trans_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { t.translation.z = n; } else { t.translation.z += n; } lt_to_open = (Some(e), Some(-5)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut t) = trans_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { t.translation.z = n; } else { t.translation.z += n; } } } lt_to_open = (None, Some(-5)); } } } Some("h") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut color) = col_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { color.0.hue = n; } else { color.0.hue += n; } lt_to_open = (Some(e), Some(-6)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut color) = col_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { color.0.hue = n; } else { color.0.hue += n; } } } lt_to_open = (None, Some(-6)); } } } Some("s") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut color) = col_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { color.0.saturation = n; } else { color.0.saturation += n; } lt_to_open = (Some(e), Some(-7)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut color) = col_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { color.0.saturation = n; } else { color.0.saturation += n; } } } lt_to_open = (None, Some(-7)); } } } Some("l") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut color) = col_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { color.0.lightness = n; } else { color.0.lightness += n; } lt_to_open = (Some(e), Some(-8)); } } } } else if let Ok(n) = parse_with_constants(s) { for id in selected_query.iter() { if let Ok(mut color) = col_query.get_mut(id) { if c0 == Some(":set") || c0 == Some("set") { color.0.lightness = n; } else { color.0.lightness += n; } } } lt_to_open = (None, Some(-8)); } } } Some("a") => { if let Some(s) = command.next() { if let Some(e) = str_to_id(s) { if let Ok(mut color) = col_query.get_mut(e) { if let Some(n) = command.next() { if let Ok(n) = parse_with_constants(n) { if c0 == Some(":set") || c0 == Some("set") { color.0.alpha = n; } else {
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
true
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/nodes.rs
src/nodes.rs
use crossbeam_channel::{Receiver, Sender}; use fundsp::fft::*; use fundsp::hacker32::*; use std::collections::VecDeque; /// switch between nets based on index /// - input 0: index /// - output 0: output from selected net #[derive(Default, Clone)] pub struct Select { nets: Vec<Net>, } impl Select { /// create a select node. takes an array of nets pub fn new(nets: Vec<Net>) -> Self { Select { nets } } } impl AudioNode for Select { const ID: u64 = 1213; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; if let Some(network) = self.nets.get_mut(input[0] as usize) { network.tick(&[], &mut buffer); } buffer.into() } fn set_sample_rate(&mut self, sample_rate: f64) { for net in &mut self.nets { net.set_sample_rate(sample_rate); } } fn reset(&mut self) { for net in &mut self.nets { net.reset(); } } } /// sequence nets /// - input 0: trigger /// - input 1: index of network to play /// - input 2: delay time /// - input 3: duration /// - output 0: output from all playing nets #[derive(Default, Clone)] pub struct Seq { nets: Vec<Net>, // index, delay, duration (times in samples) events: Vec<(usize, usize, usize)>, sr: f32, } impl Seq { pub fn new(nets: Vec<Net>) -> Self { Seq { nets, events: Vec::new(), sr: 44100. } } } impl AudioNode for Seq { const ID: u64 = 1729; type Inputs = U4; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { // triggered, add an event if input[0] != 0. { // remove existing events for that index self.events.retain(|&x| x.0 != input[1] as usize); // reset the net if let Some(network) = self.nets.get_mut(input[1] as usize) { network.reset(); } // push the new event self.events.push(( input[1] as usize, (input[2] * self.sr).round() as usize, (input[3] * self.sr).round() as usize, )); } // remove finished events self.events.retain(|&x| x.2 != 0); let mut buffer = [0.]; let mut out = [0.]; for i in &mut self.events { if i.1 == 0 { if let Some(network) = self.nets.get_mut(i.0) { network.tick(&[], &mut buffer); out[0] += buffer[0]; } i.2 -= 1; } else { i.1 -= 1; } } out.into() } fn set_sample_rate(&mut self, sample_rate: f64) { self.sr = sample_rate as f32; for net in &mut self.nets { net.set_sample_rate(sample_rate); } } fn reset(&mut self) { for net in &mut self.nets { net.reset(); } } } /// index an array of floats /// - input 0: index /// - output 0: value at index #[derive(Clone)] pub struct ArrGet { arr: Vec<f32>, } impl ArrGet { pub fn new(arr: Vec<f32>) -> Self { ArrGet { arr } } } impl AudioNode for ArrGet { const ID: u64 = 1312; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; if let Some(n) = self.arr.get(input[0] as usize) { buffer[0] = *n; } buffer.into() } } /// shift register /// - input 0: input signal /// - input 1: trigger /// - output 0...8: output from each index #[derive(Default, Clone)] pub struct ShiftReg { reg: [f32; 8], } impl ShiftReg { pub fn new() -> Self { ShiftReg { reg: [0.; 8] } } } impl AudioNode for ShiftReg { const ID: u64 = 1110; type Inputs = U2; type Outputs = U8; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { if input[1] != 0. { self.reg[7] = self.reg[6]; self.reg[6] = self.reg[5]; self.reg[5] = self.reg[4]; self.reg[4] = self.reg[3]; self.reg[3] = self.reg[2]; self.reg[2] = self.reg[1]; self.reg[1] = self.reg[0]; self.reg[0] = input[0]; } self.reg.into() } fn reset(&mut self) { self.reg = [0., 0., 0., 0., 0., 0., 0., 0.]; } } /// quantizer /// - input 0: value to quantize /// - output 0: quantized value #[derive(Clone)] pub struct Quantizer { arr: Vec<f32>, range: f32, } impl Quantizer { pub fn new(arr: Vec<f32>, range: f32) -> Self { Quantizer { arr, range } } } impl AudioNode for Quantizer { const ID: u64 = 1111; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; let n = input[0]; let wrapped = n - self.range * (n / self.range).floor(); let mut nearest = 0.; let mut dist = f32::MAX; for i in &self.arr { let d = (wrapped - i).abs(); if d < dist { nearest = *i; dist = d; } } buffer[0] = n + nearest - wrapped; buffer.into() } } /// tick a network every n samples /// - inputs 0..: inputs to the net /// - outputs 0..: last outputs from the net #[derive(Clone)] pub struct Kr { x: Net, n: usize, vals: Vec<f32>, count: usize, inputs: usize, outputs: usize, // set the sr of the inner net to sr/n to keep durations and frequencies unchanged preserve_time: bool, } impl Kr { pub fn new(x: Net, n: usize, preserve_time: bool) -> Self { let inputs = x.inputs(); let outputs = x.outputs(); let mut vals = Vec::new(); vals.resize(outputs, 0.); Kr { x, n, vals, count: 0, inputs, outputs, preserve_time } } } impl AudioUnit for Kr { fn reset(&mut self) { self.x.reset(); self.count = 0; self.vals.fill(0.); } fn set_sample_rate(&mut self, sample_rate: f64) { if self.preserve_time { self.x.set_sample_rate(sample_rate / self.n as f64); } else { self.x.set_sample_rate(sample_rate); } } fn tick(&mut self, input: &[f32], output: &mut [f32]) { if self.count == 0 { self.count = self.n; self.x.tick(input, &mut self.vals); } self.count -= 1; output[..self.outputs].copy_from_slice(&self.vals[..self.outputs]); } fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) { let mut i = 0; while i < size { if self.count == 0 { self.count = self.n; let mut tmp = Vec::new(); for c in 0..input.channels() { tmp.push(input.at_f32(c, i)); } self.x.tick(&tmp, &mut self.vals); } self.count -= 1; for c in 0..output.channels() { output.set_f32(c, i, self.vals[c]); } i += 1; } } fn inputs(&self) -> usize { self.inputs } fn outputs(&self) -> usize { self.outputs } fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame { Routing::Arbitrary(0.0).route(input, self.outputs()) } fn get_id(&self) -> u64 { const ID: u64 = 1112; ID } fn ping(&mut self, probe: bool, hash: AttoHash) -> AttoHash { self.x.ping(probe, hash.hash(self.get_id())) } fn footprint(&self) -> usize { core::mem::size_of::<Self>() } fn allocate(&mut self) { self.x.allocate(); } } /// reset network every s seconds /// - output 0: output from the net #[derive(Default, Clone)] pub struct Reset { net: Net, dur: f32, n: usize, count: usize, } impl Reset { pub fn new(net: Net, s: f32) -> Self { Reset { net, dur: s, n: (s * 44100.).round() as usize, count: 0 } } } impl AudioNode for Reset { const ID: u64 = 1113; type Inputs = U0; type Outputs = U1; #[inline] fn tick(&mut self, _input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; if self.count >= self.n { self.net.reset(); self.count = 0; } self.net.tick(&[], &mut buffer); self.count += 1; buffer.into() } fn set_sample_rate(&mut self, sample_rate: f64) { self.n = (self.dur * sample_rate as f32).round() as usize; self.net.set_sample_rate(sample_rate); } fn reset(&mut self) { self.count = 0; self.net.reset(); } } /// reset network when triggered /// - input 0: reset the net when non-zero /// - output 0: output from the net #[derive(Default, Clone)] pub struct TrigReset { net: Net, } impl TrigReset { pub fn new(net: Net) -> Self { TrigReset { net } } } impl AudioNode for TrigReset { const ID: u64 = 1114; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; if input[0] != 0. { self.net.reset(); } self.net.tick(&[], &mut buffer); buffer.into() } fn set_sample_rate(&mut self, sample_rate: f64) { self.net.set_sample_rate(sample_rate); } fn reset(&mut self) { self.net.reset(); } } /// reset network every s seconds (duration as input) /// - input 0: reset interval /// - output 0: output from the net #[derive(Default, Clone)] pub struct ResetV { net: Net, count: usize, sr: f32, } impl ResetV { pub fn new(net: Net) -> Self { ResetV { net, count: 0, sr: 44100. } } } impl AudioNode for ResetV { const ID: u64 = 1115; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let mut buffer = [0.]; if self.count >= (input[0] * self.sr).round() as usize { self.net.reset(); self.count = 0; } self.net.tick(&[], &mut buffer); self.count += 1; buffer.into() } fn set_sample_rate(&mut self, sample_rate: f64) { self.sr = sample_rate as f32; self.net.set_sample_rate(sample_rate); } fn reset(&mut self) { self.count = 0; self.net.reset(); } } /// phasor (ramp from 0..1) /// - input 0: frequency /// - output 0: ramp output #[derive(Default, Clone)] pub struct Ramp { val: f32, sr: f32, } impl Ramp { pub fn new() -> Self { Ramp { val: 0., sr: 44100. } } } impl AudioNode for Ramp { const ID: u64 = 1116; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let buffer = [self.val]; self.val += input[0] / self.sr; if self.val >= 1. { self.val -= 1.; } buffer.into() } fn reset(&mut self) { self.val = 0.; } fn set_sample_rate(&mut self, sample_rate: f64) { self.sr = sample_rate as f32; } } /// node that receives samples from crossbeam channels /// - output 0: left /// - output 1: right #[derive(Clone)] pub struct InputNode { lr: Receiver<f32>, rr: Receiver<f32>, } impl InputNode { pub fn new(lr: Receiver<f32>, rr: Receiver<f32>) -> Self { InputNode { lr, rr } } } impl AudioNode for InputNode { const ID: u64 = 1117; type Inputs = U0; type Outputs = U2; #[inline] fn tick(&mut self, _input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let l = self.lr.try_recv().unwrap_or(0.); let r = self.rr.try_recv().unwrap_or(0.); [l, r].into() } } /// unit for swapping nodes #[derive(Clone)] pub struct SwapUnit { x: Net, receiver: Receiver<Net>, inputs: usize, outputs: usize, } impl SwapUnit { pub fn new(x: Net, receiver: Receiver<Net>) -> Self { let inputs = x.inputs(); let outputs = x.outputs(); Self { x, receiver, inputs, outputs } } } impl AudioUnit for SwapUnit { fn reset(&mut self) { self.x.reset(); } fn set_sample_rate(&mut self, sample_rate: f64) { self.x.set_sample_rate(sample_rate); } fn tick(&mut self, input: &[f32], output: &mut [f32]) { if let Ok(net) = self.receiver.try_recv() { if self.x.inputs() == net.inputs() && self.x.outputs() == net.outputs() { self.x = net; } } self.x.tick(input, output); } fn process(&mut self, size: usize, input: &BufferRef, output: &mut BufferMut) { if let Ok(net) = self.receiver.try_recv() { if self.x.inputs() == net.inputs() && self.x.outputs() == net.outputs() { self.x = net; } } self.x.process(size, input, output); } fn inputs(&self) -> usize { self.inputs } fn outputs(&self) -> usize { self.outputs } fn route(&mut self, input: &SignalFrame, _frequency: f64) -> SignalFrame { Routing::Arbitrary(0.0).route(input, self.outputs()) } fn get_id(&self) -> u64 { const ID: u64 = 1118; ID } fn ping(&mut self, probe: bool, hash: AttoHash) -> AttoHash { self.x.ping(probe, hash.hash(self.get_id())) } fn footprint(&self) -> usize { core::mem::size_of::<Self>() } fn allocate(&mut self) { self.x.allocate(); } } /// rfft /// - input 0: input /// - output 0: real /// - output 1: imaginary #[derive(Default, Clone)] pub struct Rfft { n: usize, input: Vec<f32>, output: Vec<Complex32>, count: usize, start: usize, } impl Rfft { pub fn new(n: usize, start: usize) -> Self { let mut input = Vec::new(); let mut output = Vec::new(); input.resize(n, 0.); output.resize(n / 2 + 1, Complex32::ZERO); Rfft { n, input, output, count: start, start } } } impl AudioNode for Rfft { const ID: u64 = 1120; type Inputs = U1; type Outputs = U2; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let i = self.count; self.count += 1; if self.count == self.n { self.count = 0; } if i == 0 { real_fft(self.input.as_slice(), self.output.as_mut_slice()); } self.input[i] = input[0]; if i <= self.n / 2 { let out = self.output[i]; [out.re, out.im].into() } else { let out = self.output[self.n - i].conj(); [out.re, out.im].into() } } fn reset(&mut self) { self.count = self.start; self.input.fill(0.); self.output.fill(Complex32::ZERO); } } /// ifft /// - input 0: real /// - input 1: imaginary /// - output 0: real /// - output 1: imaginary #[derive(Default, Clone)] pub struct Ifft { n: usize, input: Vec<Complex32>, output: Vec<Complex32>, count: usize, start: usize, } impl Ifft { pub fn new(n: usize, start: usize) -> Self { let mut input = Vec::new(); let mut output = Vec::new(); input.resize(n, Complex32::ZERO); output.resize(n, Complex32::ZERO); Ifft { n, input, output, count: start, start } } } impl AudioNode for Ifft { const ID: u64 = 1121; type Inputs = U2; type Outputs = U2; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let i = self.count; self.count += 1; if self.count == self.n { self.count = 0; } if i == 0 { inverse_fft(self.input.as_slice(), self.output.as_mut_slice()); } self.input[i] = Complex32::new(input[0], input[1]); let buffer = [self.output[i].re, self.output[i].im]; buffer.into() } fn reset(&mut self) { self.count = self.start; self.input.fill(Complex32::ZERO); self.output.fill(Complex32::ZERO); } } /// variable delay with input time in samples /// - input 0: signal /// - input 1: delay time in samples /// - output 0: delayed signal #[derive(Clone)] pub struct SampDelay { buffer: VecDeque<f32>, max: usize, } impl SampDelay { pub fn new(max: usize) -> Self { let mut buffer = VecDeque::new(); buffer.resize(max, 0.); SampDelay { buffer, max } } } impl AudioNode for SampDelay { const ID: u64 = 1122; type Inputs = U2; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { self.buffer.push_front(input[0]); let _ = self.buffer.pop_back(); let out = self.buffer.get(input[1] as usize).unwrap_or(&0.); [*out].into() } fn reset(&mut self) { let mut new = VecDeque::new(); new.resize(self.max, 0.); self.buffer = new; } } /// send samples to crossbeam channel /// - input 0: input /// - output 0: input passed through #[derive(Clone)] pub struct BuffIn { s: Sender<f32>, } impl BuffIn { pub fn new(s: Sender<f32>) -> Self { BuffIn { s } } } impl AudioNode for BuffIn { const ID: u64 = 1123; type Inputs = U1; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { let _ = self.s.try_send(input[0]); [input[0]].into() } } /// receive smaples from crossbeam channel /// - output 0: output #[derive(Clone)] pub struct BuffOut { r: Receiver<f32>, } impl BuffOut { pub fn new(r: Receiver<f32>) -> Self { BuffOut { r } } } impl AudioNode for BuffOut { const ID: u64 = 1124; type Inputs = U0; type Outputs = U1; #[inline] fn tick(&mut self, _input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { [self.r.try_recv().unwrap_or(0.)].into() } } /// sample and hold /// - input 0: input signal /// - input 1: trigger /// - output 0: held signal #[derive(Clone)] pub struct SnH { val: f32, } impl SnH { pub fn new() -> Self { SnH { val: 0. } } } impl AudioNode for SnH { const ID: u64 = 1125; type Inputs = U2; type Outputs = U1; #[inline] fn tick(&mut self, input: &Frame<f32, Self::Inputs>) -> Frame<f32, Self::Outputs> { if input[1] != 0. { self.val = input[0]; } [self.val].into() } fn reset(&mut self) { self.val = 0.; } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/main.rs
src/main.rs
#![allow(clippy::type_complexity, clippy::too_many_arguments)] use bevy::{ asset::ron::Deserializer, color::Hsla, core_pipeline::{ bloom::{BloomCompositeMode, BloomSettings}, tonemapping::Tonemapping, }, prelude::*, render::view::RenderLayers, scene::{serde::SceneDeserializer, SceneInstance}, sprite::Mesh2dHandle, tasks::IoTaskPool, utils::Duration, window::{FileDragAndDrop::DroppedFile, WindowMode}, winit::{UpdateMode, WinitSettings}, }; use bevy_pancam::{PanCam, PanCamPlugin}; use copypasta::{ClipboardContext, ClipboardProvider}; use serde::de::DeserializeSeed; use std::{fs::File, io::Write}; #[cfg(feature = "inspector")] use bevy_inspector_egui::quick::WorldInspectorPlugin; mod audio; mod circles; mod commands; mod components; mod connections; mod cursor; mod functions; mod nodes; mod osc; mod process; use { audio::*, circles::*, commands::*, components::*, connections::*, cursor::*, functions::*, osc::*, process::*, }; fn main() { let mut app = App::new(); app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { //transparent: true, title: String::from("awawawa"), ..default() }), ..default() })) .add_plugins(PanCamPlugin) // osc .insert_resource(OscSender { host: "127.0.0.1".to_string(), port: 1729 }) .insert_resource(OscReceiver { socket: None }) // settings .insert_resource(WinitSettings { focused_mode: UpdateMode::reactive_low_power(Duration::from_secs_f64(1.0 / 60.0)), unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs_f64(1.0 / 30.0)), }) .insert_resource(ClearColor(Color::hsla(0., 0., 0., 1.))) .insert_resource(DefaultDrawColor(Hsla::new(330., 1., 0.5, 1.))) .insert_resource(DefaultDrawVerts(4)) .insert_resource(HighlightColor(Hsla::new(0.0, 1.0, 0.5, 1.))) .insert_resource(ConnectionColor(Hsla::new(0., 1., 1., 0.7))) .insert_resource(ConnectionWidth(4.)) .insert_resource(CommandColor(Hsla::new(0., 0., 0.7, 1.))) .insert_resource(IndicatorColor(Hsla::new(0., 1., 0.5, 0.3))) .insert_resource(TextSize(0.1)) .insert_resource(NodeLimit(500)) .insert_resource(Version(format!("{} {}", env!("CARGO_PKG_VERSION"), env!("COMMIT_HASH")))) .insert_resource(Msaa::Sample4) // audio .add_systems(Startup, default_out_device) .add_systems(Update, set_out_device) .add_systems(Startup, default_in_device) .add_systems(Update, set_in_device) // main .insert_resource(SystemClipboard(ClipboardContext::new().unwrap())) .insert_resource(PasteChannel(crossbeam_channel::bounded::<String>(1))) .add_systems(Startup, setup) .add_systems(Update, toggle_pan) .add_systems(Update, toggle_fullscreen) .add_systems(Update, save_scene) .add_systems(Update, copy_scene.run_if(on_event::<CopyCommand>())) .add_systems(Update, paste_scene) .add_systems(Update, post_load) .add_systems(Update, file_drag_and_drop) .add_systems(Update, update_indicator) .init_state::<Mode>() // cursor .insert_resource(CursorInfo::default()) .add_systems(Update, update_cursor_info) // circles .insert_resource(ClickedOnSpace(true)) .insert_resource(ShowInfoText(true, false)) .init_resource::<PolygonHandles>() .init_resource::<DragModes>() .add_systems(Update, spawn_circles.run_if(in_state(Mode::Draw))) .add_systems(Update, update_selection.after(update_cursor_info).run_if(in_state(Mode::Edit))) .add_systems(Update, move_selected.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, update_color.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, update_mat) .add_systems(Update, update_radius.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, update_vertices.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, update_mesh.after(update_vertices).after(command_parser)) .add_systems(Update, update_num.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, highlight_selected.after(delete_selected)) .add_systems(Update, open_after_drag.run_if(in_state(Mode::Edit))) .add_systems(PreUpdate, transform_highlights) .add_systems(Update, rotate_selected.after(update_selection).run_if(in_state(Mode::Edit))) .add_systems(Update, delete_selected.run_if(on_event::<DeleteCommand>())) .add_systems(PreUpdate, update_info_text) .add_systems(Update, spawn_info_text) // events .add_event::<SaveCommand>() .add_event::<CopyCommand>() .add_event::<DeleteCommand>() .add_event::<ConnectCommand>() .add_event::<OutDeviceCommand>() .add_event::<InDeviceCommand>() // connections .insert_resource(DefaultLT((0, 0))) .add_systems(Update, connect.run_if(in_state(Mode::Connect))) .add_systems(Update, connect_targets) .add_systems(Update, target.run_if(in_state(Mode::Connect))) .add_systems(PreUpdate, update_connection_arrows) // process .init_resource::<Queue>() .init_resource::<LoopQueue>() .add_event::<OrderChange>() .add_systems(PostUpdate, sort_by_order.before(process).run_if(on_event::<OrderChange>())) .add_systems(PostUpdate, prepare_loop_queue.after(sort_by_order).before(process)) .add_systems(PostUpdate, process) // commands .add_systems(Update, command_parser) // type registry .register_type::<DragModes>() .register_type::<Queue>() .register_type::<Col>() .register_type::<Op>() .register_type::<Number>() .register_type::<Arr>() .register_type::<Selected>() .register_type::<Save>() .register_type::<Order>() .register_type::<BlackHole>() .register_type::<WhiteHole>() .register_type::<Vertices>() .register_type::<Targets>() .register_type::<LostWH>() .register_type::<DefaultDrawColor>() .register_type::<DefaultDrawVerts>() .register_type::<HighlightColor>() .register_type::<ConnectionColor>() .register_type::<ConnectionWidth>() .register_type::<CommandColor>() .register_type::<IndicatorColor>() .register_type::<TextSize>() .register_type::<Version>() .register_type::<Holes>() .register_type::<NodeLimit>() .register_type::<ShowInfoText>(); #[cfg(feature = "inspector")] app.add_plugins(WorldInspectorPlugin::new()); app.run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, command_color: Res<CommandColor>, connection_color: Res<ConnectionColor>, indicator_color: Res<IndicatorColor>, ) { // camera commands.spawn(( Camera2dBundle { camera: Camera { hdr: true, ..default() }, tonemapping: Tonemapping::TonyMcMapface, transform: Transform::from_translation(Vec3::Z * 200.), ..default() }, BloomSettings { intensity: 0.2, low_frequency_boost: 0.6, low_frequency_boost_curvature: 0.4, composite_mode: BloomCompositeMode::Additive, ..default() }, PanCam { enabled: false, max_scale: Some(80.), min_scale: 0.005, ..default() }, RenderLayers::from_layers(&[0, 1, 2, 3, 4]), )); // command line commands .spawn(NodeBundle { style: Style { width: Val::Percent(100.0), height: Val::Percent(100.0), justify_content: JustifyContent::SpaceBetween, ..default() }, ..default() }) .with_children(|parent| { parent.spawn(( TextBundle::from_section( "", TextStyle { font_size: 13.0, color: command_color.0.into(), ..default() }, ) .with_style(Style { margin: UiRect::all(Val::Px(5.)), align_self: AlignSelf::End, ..default() }), CommandText, )); }); // selecting / drawing / connecting indicator let id = commands .spawn(( ColorMesh2dBundle { mesh: meshes.add(Triangle2d::default()).into(), material: materials.add(ColorMaterial::from_color(indicator_color.0)), transform: Transform::from_translation(Vec3::Z), ..default() }, Col(indicator_color.0), )) .id(); commands.insert_resource(Indicator(id)); // arrow mesh commands.insert_resource(ArrowHandle(meshes.add(Triangle2d::default()).into())); // connection material commands.insert_resource(ConnectionMat( materials.add(ColorMaterial::from_color(connection_color.0)), )); } fn toggle_pan(mut query: Query<&mut PanCam>, keyboard_input: Res<ButtonInput<KeyCode>>) { if keyboard_input.just_pressed(KeyCode::Space) { query.single_mut().enabled = true; } else if keyboard_input.just_released(KeyCode::Space) { query.single_mut().enabled = false; } } fn toggle_fullscreen(mut query: Query<&mut Window>, keyboard_input: Res<ButtonInput<KeyCode>>) { if keyboard_input.just_pressed(KeyCode::F11) { if query.single().mode == WindowMode::Fullscreen { query.single_mut().mode = WindowMode::Windowed; } else { query.single_mut().mode = WindowMode::Fullscreen; } } } fn update_indicator( mode: Res<State<Mode>>, id: Res<Indicator>, mut trans_query: Query<&mut Transform>, mouse_button_input: Res<ButtonInput<MouseButton>>, cursor: Res<CursorInfo>, keyboard_input: Res<ButtonInput<KeyCode>>, connection_width: Res<ConnectionWidth>, default_verts: Res<DefaultDrawVerts>, mut meshes: ResMut<Assets<Mesh>>, mesh_ids: Query<&Mesh2dHandle>, clicked_on_space: Res<ClickedOnSpace>, ) { if mouse_button_input.pressed(MouseButton::Left) && !mouse_button_input.just_pressed(MouseButton::Left) && !keyboard_input.pressed(KeyCode::Space) { if *mode.get() == Mode::Edit && clicked_on_space.0 { let Mesh2dHandle(mesh_id) = mesh_ids.get(id.0).unwrap(); let mesh = meshes.get_mut(mesh_id).unwrap(); *mesh = Rectangle::default().into(); *trans_query.get_mut(id.0).unwrap() = Transform { translation: ((cursor.i + cursor.f) / 2.).extend(400.), scale: (cursor.f - cursor.i).abs().extend(1.), ..default() }; } else if *mode.get() == Mode::Draw { let v = default_verts.0; let Mesh2dHandle(mesh_id) = mesh_ids.get(id.0).unwrap(); let mesh = meshes.get_mut(mesh_id).unwrap(); *mesh = RegularPolygon::new(1., v).into(); let dist = cursor.i.distance(cursor.f); *trans_query.get_mut(id.0).unwrap() = Transform { translation: cursor.i.extend(400.), scale: Vec3::new(dist, dist, 1.), ..default() }; } else if *mode.get() == Mode::Connect { let Mesh2dHandle(mesh_id) = mesh_ids.get(id.0).unwrap(); let mesh = meshes.get_mut(mesh_id).unwrap(); *mesh = Triangle2d::default().into(); let perp = (cursor.i - cursor.f).perp(); *trans_query.get_mut(id.0).unwrap() = Transform { translation: ((cursor.i + cursor.f) / 2.).extend(400.), scale: Vec3::new(connection_width.0, cursor.f.distance(cursor.i), 1.), rotation: Quat::from_rotation_z(perp.to_angle()), } } } if mouse_button_input.just_released(MouseButton::Left) { *trans_query.get_mut(id.0).unwrap() = Transform::default(); let Mesh2dHandle(mesh_id) = mesh_ids.get(id.0).unwrap(); let mesh = meshes.get_mut(mesh_id).unwrap(); *mesh = Triangle2d::default().into(); } } fn save_scene(world: &mut World) { let mut save_events = world.resource_mut::<Events<SaveCommand>>(); let events: Vec<SaveCommand> = save_events.drain().collect(); for event in events { let name = event.0; let mut query = world.query_filtered::<Entity, With<Vertices>>(); let scene = DynamicSceneBuilder::from_world(world) .allow::<Col>() .allow::<Transform>() .allow::<Op>() .allow::<Number>() .allow::<Arr>() .allow::<Order>() .allow::<BlackHole>() .allow::<WhiteHole>() .allow::<Holes>() .allow::<Vertices>() .allow::<Targets>() .allow_resource::<DefaultDrawColor>() .allow_resource::<DefaultDrawVerts>() .allow_resource::<HighlightColor>() .allow_resource::<ConnectionColor>() .allow_resource::<ConnectionWidth>() .allow_resource::<ClearColor>() .allow_resource::<CommandColor>() .allow_resource::<IndicatorColor>() .allow_resource::<TextSize>() .allow_resource::<Version>() .allow_resource::<NodeLimit>() .allow_resource::<ShowInfoText>() .extract_entities(query.iter(world)) .extract_resources() .build(); let type_registry = world.resource::<AppTypeRegistry>(); let type_registry = type_registry.read(); let serialized_scene = scene.serialize(&type_registry).unwrap(); #[cfg(not(target_arch = "wasm32"))] IoTaskPool::get() .spawn(async move { File::create(format!("assets/{}", name)) .and_then(|mut file| file.write(serialized_scene.as_bytes())) .expect("Error while writing scene to file"); }) .detach(); } } fn copy_scene(world: &mut World) { let mut query = world.query_filtered::<Entity, With<Selected>>(); let scene = DynamicSceneBuilder::from_world(world) .allow::<Col>() .allow::<Transform>() .allow::<Op>() .allow::<Number>() .allow::<Arr>() .allow::<Order>() .allow::<BlackHole>() .allow::<WhiteHole>() .allow::<Holes>() .allow::<Vertices>() .allow::<Targets>() .extract_entities(query.iter(world)) .build(); let serialized_scene = scene.serialize(&world.resource::<AppTypeRegistry>().read()).unwrap(); #[cfg(not(target_arch = "wasm32"))] { let mut ctx = world.resource_mut::<SystemClipboard>(); ctx.0.set_contents(serialized_scene).unwrap(); } #[cfg(target_arch = "wasm32")] if let Some(window) = web_sys::window() { if let Some(clipboard) = window.navigator().clipboard() { let _ = clipboard.write_text(&serialized_scene); } } } fn paste_scene(world: &mut World) { if let Ok(string) = world.resource::<PasteChannel>().0 .1.try_recv() { let bytes = string.into_bytes(); let mut scene = None; if let Ok(mut deserializer) = Deserializer::from_bytes(&bytes) { let type_registry = world.resource::<AppTypeRegistry>(); let scene_deserializer = SceneDeserializer { type_registry: &type_registry.read() }; if let Ok(s) = scene_deserializer.deserialize(&mut deserializer) { scene = Some(s); } } if let Some(s) = scene { let scene = world.resource_mut::<Assets<DynamicScene>>().add(s); world.spawn(DynamicSceneBundle { scene, ..default() }); } } } fn file_drag_and_drop( mut commands: Commands, mut events: EventReader<FileDragAndDrop>, asset_server: Res<AssetServer>, ) { for event in events.read() { if let DroppedFile { path_buf, .. } = event { commands.spawn(DynamicSceneBundle { scene: asset_server.load(path_buf.clone()), ..default() }); } } } fn post_load( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, main_query: Query<(&Transform, &Col, &Vertices)>, mut order_change: EventWriter<OrderChange>, mut white_hole_query: Query<&mut WhiteHole>, black_hole_query: Query<&BlackHole>, scenes: Query<(Entity, &SceneInstance)>, children_query: Query<&Children>, mut holes_query: Query<&mut Holes>, mut op_query: Query<&mut Op>, mut command_line_text: Query<&mut Text, With<CommandText>>, scene_spawner: Res<SceneSpawner>, mut polygon_handles: ResMut<PolygonHandles>, mut indicator_color_query: Query<&mut Col, Without<Vertices>>, ( command_color, connection_color, arrow_handle, connection_mat, selected_query, indicator_color, indicator_id, ): ( Res<CommandColor>, Res<ConnectionColor>, Res<ArrowHandle>, Res<ConnectionMat>, Query<Entity, With<Selected>>, Res<IndicatorColor>, Res<Indicator>, ), ) { for (scene_id, instance_id) in scenes.iter() { if scene_spawner.instance_is_ready(**instance_id) { for e in selected_query.iter() { commands.entity(e).remove::<Selected>(); } // update indicator color indicator_color_query.get_mut(indicator_id.0).unwrap().0 = indicator_color.0; // update connection material from color resource materials.get_mut(&connection_mat.0).unwrap().color = connection_color.0.into(); if let Ok(children) = children_query.get(scene_id) { for child in children { if let Ok((t, c, v)) = main_query.get(*child) { if polygon_handles.0.len() <= v.0 { polygon_handles.0.resize(v.0 + 1, None); } if polygon_handles.0[v.0].is_none() { let handle = meshes.add(RegularPolygon::new(1., v.0)).into(); polygon_handles.0[v.0] = Some(handle); } commands.entity(*child).try_insert(( ColorMesh2dBundle { mesh: polygon_handles.0[v.0].clone().unwrap(), material: materials.add(ColorMaterial::from_color(c.0)), transform: *t, ..default() }, Selected, )); if let Ok(op) = op_query.get_mut(*child) { let (s, r) = crossbeam_channel::bounded(1); commands.entity(*child).insert(( OpNum(str_to_op_num(&op.0)), Network(str_to_net(&op.0)), NetIns(Vec::new()), OpChanged(true), LostWH(false), NetChannel(s, r), RenderLayers::layer(1), )); let holes = &mut holes_query.get_mut(*child).unwrap().0; let mut new_holes = Vec::new(); for hole in &mut *holes { if let Ok(mut wh) = white_hole_query.get_mut(*hole) { if black_hole_query.contains(wh.bh) && main_query.contains(wh.bh_parent) { wh.open = true; let arrow = commands .spawn(( ColorMesh2dBundle { mesh: arrow_handle.0.clone(), material: connection_mat.0.clone(), transform: Transform::default(), ..default() }, RenderLayers::layer(4), )) .id(); commands.entity(*hole).insert(( ConnectionArrow(arrow), RenderLayers::layer(3), )); new_holes.push(*hole); commands.entity(*hole).remove_parent(); } } else if let Ok(bh) = black_hole_query.get(*hole) { if white_hole_query.contains(bh.wh) && main_query.contains(bh.wh_parent) { commands.entity(*hole).insert(RenderLayers::layer(2)); new_holes.push(*hole); commands.entity(*hole).remove_parent(); } } } *holes = new_holes; commands.entity(*child).remove_parent(); } } } order_change.send_default(); } // update the command line color from resource let clt = &mut command_line_text.single_mut(); clt.sections[0].style.color = command_color.0.into(); // despawn the now empty instance (may contain bad state connections when pasting) commands.entity(scene_id).remove::<SceneInstance>(); commands.entity(scene_id).despawn_recursive(); } } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/components.rs
src/components.rs
use bevy::{ color::Hsla, ecs::{ entity::MapEntities, reflect::{ReflectComponent, ReflectMapEntities}, }, prelude::*, sprite::Mesh2dHandle, }; use fundsp::{net::Net, shared::Shared, slot::Slot}; use crossbeam_channel::{Receiver, Sender}; use cpal::Stream; use copypasta::ClipboardContext; // -------------------- components -------------------- #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Op(pub String); #[derive(Component, Reflect, Default, PartialEq)] #[reflect(Component)] pub struct Number(pub f32); #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Arr(pub Vec<f32>); #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Vertices(pub usize); #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Col(pub Hsla); #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Selected; #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Order(pub usize); #[derive(Component)] pub struct OpChanged(pub bool); #[derive(Component)] pub struct Network(pub Net); #[derive(Component)] pub struct NetIns(pub Vec<Shared>); #[derive(Component)] pub struct NetChannel(pub Sender<Net>, pub Receiver<Net>); #[derive(Component)] pub struct FloatChannel(pub Sender<f32>, pub Receiver<f32>); #[derive(Component, Reflect)] #[reflect(Component, MapEntities)] pub struct Holes(pub Vec<Entity>); impl FromWorld for Holes { fn from_world(_world: &mut World) -> Self { Holes(Vec::new()) } } impl MapEntities for Holes { fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) { for entity in &mut self.0 { *entity = entity_mapper.map_entity(*entity); } } } #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct LostWH(pub bool); // deprecated #[derive(Component, Reflect, Default)] #[reflect(Component)] pub struct Save; #[derive(Component)] pub struct Highlight(pub Entity); #[derive(Component, Reflect)] #[reflect(Component, MapEntities)] pub struct Targets(pub Vec<Entity>); impl FromWorld for Targets { fn from_world(_world: &mut World) -> Self { Targets(Vec::new()) } } impl MapEntities for Targets { fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) { for entity in &mut self.0 { *entity = entity_mapper.map_entity(*entity); } } } #[derive(Component, Reflect)] #[reflect(Component, MapEntities)] pub struct WhiteHole { pub bh: Entity, pub bh_parent: Entity, pub link_types: (i8, i8), //(black, white) pub open: bool, } impl FromWorld for WhiteHole { fn from_world(_world: &mut World) -> Self { WhiteHole { bh: Entity::PLACEHOLDER, bh_parent: Entity::PLACEHOLDER, link_types: (0, 0), open: true, } } } impl MapEntities for WhiteHole { fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) { self.bh = entity_mapper.map_entity(self.bh); self.bh_parent = entity_mapper.map_entity(self.bh_parent); } } #[derive(Component)] pub struct ConnectionArrow(pub Entity); #[derive(Component, Reflect)] #[reflect(Component, MapEntities)] pub struct BlackHole { pub wh: Entity, pub wh_parent: Entity, } impl FromWorld for BlackHole { fn from_world(_world: &mut World) -> Self { BlackHole { wh: Entity::PLACEHOLDER, wh_parent: Entity::PLACEHOLDER } } } impl MapEntities for BlackHole { fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) { self.wh = entity_mapper.map_entity(self.wh); self.wh_parent = entity_mapper.map_entity(self.wh_parent); } } #[derive(Component)] pub struct CommandText; #[derive(Component)] pub struct InfoText(pub Entity); #[derive(Component)] pub struct OpNum(pub u16); // -------------------- states -------------------- #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)] pub enum Mode { Draw, Connect, #[default] Edit, } // -------------------- resources -------------------- #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct Queue(pub Vec<Vec<Entity>>); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct LoopQueue(pub Vec<Entity>); // initial, final, delta #[derive(Resource, Default)] pub struct CursorInfo { pub i: Vec2, pub f: Vec2, pub d: Vec2, } #[derive(Resource)] pub struct SlotRes(pub Slot); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct DragModes { pub t: bool, pub r: bool, pub n: bool, pub h: bool, pub s: bool, pub l: bool, pub a: bool, pub o: bool, pub v: bool, } impl DragModes { pub fn falsify(&mut self) { self.t = false; self.r = false; self.n = false; self.h = false; self.s = false; self.l = false; self.a = false; self.o = false; self.v = false; } } #[derive(Resource)] pub struct Indicator(pub Entity); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct DefaultDrawColor(pub Hsla); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct DefaultDrawVerts(pub usize); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct HighlightColor(pub Hsla); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct ConnectionColor(pub Hsla); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct CommandColor(pub Hsla); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct ConnectionWidth(pub f32); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct TextSize(pub f32); #[derive(Resource)] pub struct DefaultLT(pub (i8, i8)); #[derive(Resource)] pub struct SystemClipboard(pub ClipboardContext); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct Version(pub String); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct IndicatorColor(pub Hsla); #[derive(Resource, Default)] pub struct PolygonHandles(pub Vec<Option<Mesh2dHandle>>); #[derive(Resource)] pub struct ArrowHandle(pub Mesh2dHandle); #[derive(Resource)] pub struct ConnectionMat(pub Handle<ColorMaterial>); #[derive(Resource)] pub struct ClickedOnSpace(pub bool); pub struct OutStream(pub Stream); pub struct InStream(pub Stream); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct NodeLimit(pub usize); #[derive(Resource)] pub struct InputReceivers(pub Receiver<f32>, pub Receiver<f32>); #[derive(Resource)] pub struct PasteChannel(pub (Sender<String>, Receiver<String>)); #[derive(Resource, Reflect, Default)] #[reflect(Resource)] pub struct ShowInfoText(pub bool, pub bool); // (show text, show id) // -------------------- events -------------------- #[derive(Event, Default)] pub struct OrderChange; #[derive(Event)] pub struct SaveCommand(pub String); #[derive(Event, Default)] pub struct CopyCommand; #[derive(Event, Default)] pub struct DeleteCommand; #[derive(Event)] pub struct ConnectCommand(pub Entity); #[derive(Event)] pub struct OutDeviceCommand(pub usize, pub usize, pub Option<u32>, pub Option<u32>); #[derive(Event)] pub struct InDeviceCommand(pub usize, pub usize, pub Option<u32>, pub Option<u32>);
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/audio.rs
src/audio.rs
use bevy::prelude::*; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{FromSample, SizedSample}; use fundsp::hacker32::*; use crossbeam_channel::{bounded, Sender}; use crate::components::*; pub fn default_out_device(world: &mut World) { let slot = Slot::new(Box::new(dc(0.) | dc(0.))); world.insert_resource(SlotRes(slot.0)); let host = cpal::default_host(); if let Some(device) = host.default_output_device() { let default_config = device.default_output_config().unwrap(); let mut config = default_config.config(); config.channels = 2; let stream = match default_config.sample_format() { cpal::SampleFormat::F32 => run::<f32>(&device, &config, slot.1), cpal::SampleFormat::I16 => run::<i16>(&device, &config, slot.1), cpal::SampleFormat::U16 => run::<u16>(&device, &config, slot.1), format => { error!("unsupported sample format: {}", format); None } }; if let Some(stream) = stream { world.insert_non_send_resource(OutStream(stream)); } else { error!("couldn't build stream"); } } } pub fn set_out_device(world: &mut World) { let mut out_events = world.resource_mut::<Events<OutDeviceCommand>>(); let events: Vec<OutDeviceCommand> = out_events.drain().collect(); for e in events { let slot = Slot::new(Box::new(dc(0.) | dc(0.))); world.insert_resource(SlotRes(slot.0)); let OutDeviceCommand(h, d, sr, b) = e; if let Some(host_id) = cpal::platform::ALL_HOSTS.get(h) { if let Ok(host) = cpal::platform::host_from_id(*host_id) { if let Ok(mut devices) = host.output_devices() { if let Some(device) = devices.nth(d) { let default_config = device.default_output_config().unwrap(); let mut config = default_config.config(); config.channels = 2; if let Some(sr) = sr { config.sample_rate = cpal::SampleRate(sr); } if let Some(b) = b { config.buffer_size = cpal::BufferSize::Fixed(b); } let stream = match default_config.sample_format() { cpal::SampleFormat::F32 => run::<f32>(&device, &config, slot.1), cpal::SampleFormat::I16 => run::<i16>(&device, &config, slot.1), cpal::SampleFormat::U16 => run::<u16>(&device, &config, slot.1), format => { error!("unsupported sample format: {}", format); None } }; if let Some(stream) = stream { world.insert_non_send_resource(OutStream(stream)); } else { error!("couldn't build stream"); } } } } } } } fn run<T>( device: &cpal::Device, config: &cpal::StreamConfig, slot: SlotBackend, ) -> Option<cpal::Stream> where T: SizedSample + FromSample<f32>, { let mut slot = BlockRateAdapter::new(Box::new(slot)); let mut next_value = move || { let (l, r) = slot.get_stereo(); ( if l.is_normal() { l.clamp(-1., 1.) } else { 0. }, if r.is_normal() { r.clamp(-1., 1.) } else { 0. }, ) }; let err_fn = |err| eprintln!("an error occurred on stream: {}", err); let stream = device.build_output_stream( config, move |data: &mut [T], _: &cpal::OutputCallbackInfo| write_data(data, &mut next_value), err_fn, None, ); if let Ok(stream) = stream { if let Ok(()) = stream.play() { return Some(stream); } } None } fn write_data<T>(output: &mut [T], next_sample: &mut dyn FnMut() -> (f32, f32)) where T: SizedSample + FromSample<f32>, { for frame in output.chunks_mut(2) { let sample = next_sample(); frame[0] = T::from_sample(sample.0); frame[1] = T::from_sample(sample.1); } } pub fn default_in_device(world: &mut World) { let (ls, lr) = bounded(4096); let (rs, rr) = bounded(4096); world.insert_resource(InputReceivers(lr, rr)); let host = cpal::default_host(); if let Some(device) = host.default_input_device() { let config = device.default_input_config().unwrap(); let stream = match config.sample_format() { cpal::SampleFormat::F32 => run_in::<f32>(&device, &config.into(), ls, rs), cpal::SampleFormat::I16 => run_in::<i16>(&device, &config.into(), ls, rs), cpal::SampleFormat::U16 => run_in::<u16>(&device, &config.into(), ls, rs), format => { error!("unsupported sample format: {}", format); None } }; if let Some(stream) = stream { world.insert_non_send_resource(InStream(stream)); } else { error!("couldn't build stream"); } } } pub fn set_in_device(world: &mut World) { let mut out_events = world.resource_mut::<Events<InDeviceCommand>>(); let events: Vec<InDeviceCommand> = out_events.drain().collect(); for e in events { let (ls, lr) = bounded(4096); let (rs, rr) = bounded(4096); world.insert_resource(InputReceivers(lr, rr)); let InDeviceCommand(h, d, sr, b) = e; if let Some(host_id) = cpal::platform::ALL_HOSTS.get(h) { if let Ok(host) = cpal::platform::host_from_id(*host_id) { if let Ok(mut devices) = host.input_devices() { if let Some(device) = devices.nth(d) { let default_config = device.default_input_config().unwrap(); let mut config = default_config.config(); if let Some(sr) = sr { config.sample_rate = cpal::SampleRate(sr); } if let Some(b) = b { config.buffer_size = cpal::BufferSize::Fixed(b); } let stream = match default_config.sample_format() { cpal::SampleFormat::F32 => run_in::<f32>(&device, &config, ls, rs), cpal::SampleFormat::I16 => run_in::<i16>(&device, &config, ls, rs), cpal::SampleFormat::U16 => run_in::<u16>(&device, &config, ls, rs), format => { error!("unsupported sample format: {}", format); None } }; if let Some(stream) = stream { world.insert_non_send_resource(InStream(stream)); } else { error!("couldn't build stream"); } } } } } } } fn run_in<T>( device: &cpal::Device, config: &cpal::StreamConfig, ls: Sender<f32>, rs: Sender<f32>, ) -> Option<cpal::Stream> where T: SizedSample, f32: FromSample<T>, { let channels = config.channels as usize; let err_fn = |err| eprintln!("an error occurred on stream: {}", err); let stream = device.build_input_stream( config, move |data: &[T], _: &cpal::InputCallbackInfo| { read_data(data, channels, ls.clone(), rs.clone()) }, err_fn, None, ); if let Ok(stream) = stream { if let Ok(()) = stream.play() { return Some(stream); } } None } fn read_data<T>(input: &[T], channels: usize, ls: Sender<f32>, rs: Sender<f32>) where T: SizedSample, f32: FromSample<T>, { for frame in input.chunks(channels) { for (channel, sample) in frame.iter().enumerate() { if channel & 1 == 0 { let _ = ls.try_send(sample.to_sample::<f32>()); } else { let _ = rs.try_send(sample.to_sample::<f32>()); } } } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/osc.rs
src/osc.rs
use bevy::prelude::*; use rosc::{ decoder::{decode_udp, MTU}, encoder, OscMessage, OscPacket, OscType, }; use std::net::UdpSocket; #[derive(Resource)] pub struct OscSender { pub host: String, pub port: u16, } impl OscSender { pub fn send<T, I>(&self, address: &str, args: T) where T: IntoIterator<Item = I>, I: Into<OscType>, { if let Ok(client) = UdpSocket::bind("0.0.0.0:0") { let packet = OscPacket::Message(OscMessage { addr: address.to_string(), args: args.into_iter().map(Into::into).collect(), }); let buf = encoder::encode(&packet).unwrap(); let _ = client.send_to(&buf, format!("{}:{}", self.host, self.port)); } } } #[derive(Resource)] pub struct OscReceiver { pub socket: Option<UdpSocket>, } impl OscReceiver { pub fn init(&mut self, port: u16) { if let Ok(socket) = UdpSocket::bind(format!("0.0.0.0:{}", port)) { socket.set_nonblocking(true).unwrap(); self.socket = Some(socket); } else { warn!("can't bind! another app is using port {}", port); self.socket = None; } } } pub fn unpacket(packet: OscPacket, buffer: &mut Vec<OscMessage>) { match packet { OscPacket::Message(msg) => { buffer.push(msg); } OscPacket::Bundle(bundle) => { bundle.content.iter().for_each(|packet| { unpacket(packet.clone(), buffer); }); } } } pub fn receive_packet(socket: &UdpSocket) -> Option<OscPacket> { let mut buf = [0u8; MTU]; if let Ok(num_bytes) = socket.recv(&mut buf) { if let Ok((_, packet)) = decode_udp(&buf[0..num_bytes]) { return Some(packet); } } None }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
tomara-x/quartz
https://github.com/tomara-x/quartz/blob/266a3df12648a73b57fdae26694bdbcbf70fcb45/src/connections.rs
src/connections.rs
use bevy::{ prelude::*, render::view::{RenderLayers, VisibleEntities}, sprite::WithMesh2d, }; use crate::components::*; pub fn connect( mouse_button_input: Res<ButtonInput<MouseButton>>, mut commands: Commands, trans_query: Query<&Transform>, vertices_query: Query<&Vertices>, visible: Query<&VisibleEntities>, cursor: Res<CursorInfo>, mut materials: ResMut<Assets<ColorMaterial>>, keyboard_input: Res<ButtonInput<KeyCode>>, mut holes_query: Query<&mut Holes>, default_lt: Res<DefaultLT>, polygon_handles: Res<PolygonHandles>, arrow_handle: Res<ArrowHandle>, connection_mat: Res<ConnectionMat>, mut order_query: Query<&mut Order>, mut order_change: EventWriter<OrderChange>, ) { if mouse_button_input.just_released(MouseButton::Left) && !keyboard_input.pressed(KeyCode::KeyT) && !keyboard_input.pressed(KeyCode::Space) { let mut source_entity: (Option<Entity>, f32) = (None, f32::MIN); let mut sink_entity: (Option<Entity>, f32) = (None, f32::MIN); for e in visible.single().get::<WithMesh2d>() { if holes_query.contains(*e) { // it's a non-hole let t = trans_query.get(*e).unwrap(); if cursor.i.distance(t.translation.xy()) < t.scale.x && t.translation.z > source_entity.1 { source_entity = (Some(*e), t.translation.z); } if cursor.f.distance(t.translation.xy()) < t.scale.x && t.translation.z > sink_entity.1 { sink_entity = (Some(*e), t.translation.z); } } } if let (Some(src), Some(snk)) = (source_entity.0, sink_entity.0) { // don't connect entity to itself if source_entity.0 == sink_entity.0 { return; } // increment order of sink let src_order = order_query.get(src).unwrap().0; let snk_order = order_query.get(snk).unwrap().0; if snk_order <= src_order { order_query.get_mut(snk).unwrap().0 = src_order + 1; order_change.send_default(); } // get translation, radius, and vertices let src_trans = trans_query.get(src).unwrap().translation; let snk_trans = trans_query.get(snk).unwrap().translation; let src_radius = trans_query.get(src).unwrap().scale.x; let snk_radius = trans_query.get(snk).unwrap().scale.x; let src_verts = vertices_query.get(src).unwrap().0; let snk_verts = vertices_query.get(snk).unwrap().0; let bh_radius = src_radius * 0.15; let wh_radius = snk_radius * 0.15; // spawn connection arrow let arrow = commands .spawn(( ColorMesh2dBundle { mesh: arrow_handle.0.clone(), material: connection_mat.0.clone(), transform: Transform::default(), ..default() }, RenderLayers::layer(4), )) .id(); // spawn circles let bh_depth = 0.001 * (holes_query.get(src).unwrap().0.len() + 1) as f32; let bh_verts = snk_verts; let bh_color = Hsla::new(0., 0., 0.2, 1.); let black_hole = commands .spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[bh_verts].clone().unwrap(), material: materials.add(ColorMaterial::from_color(bh_color)), transform: Transform { translation: cursor.i.extend(bh_depth + src_trans.z), scale: Vec3::new(bh_radius, bh_radius, 1.), ..default() }, ..default() }, Col(bh_color), Vertices(bh_verts), RenderLayers::layer(2), )) .id(); let wh_depth = 0.001 * (holes_query.get(snk).unwrap().0.len() + 1) as f32; let wh_verts = src_verts; let wh_color = Hsla::new(0., 0., 0.8, 1.); let white_hole = commands .spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[bh_verts].clone().unwrap(), material: materials.add(ColorMaterial::from_color(wh_color)), transform: Transform { translation: cursor.f.extend(wh_depth + snk_trans.z), scale: Vec3::new(wh_radius, wh_radius, 1.), ..default() }, ..default() }, Col(wh_color), Vertices(wh_verts), WhiteHole { bh_parent: src, bh: black_hole, link_types: default_lt.0, open: true, }, RenderLayers::layer(3), ConnectionArrow(arrow), )) .id(); // insert black hole white hole commands.entity(black_hole).insert(BlackHole { wh: white_hole, wh_parent: snk }); // add to parents holes_query.get_mut(src).unwrap().0.push(black_hole); holes_query.get_mut(snk).unwrap().0.push(white_hole); } } } pub fn target( mouse_button_input: Res<ButtonInput<MouseButton>>, circle_trans_query: Query<&Transform, With<Vertices>>, visible: Query<&VisibleEntities>, cursor: Res<CursorInfo>, keyboard_input: Res<ButtonInput<KeyCode>>, mut targets_query: Query<&mut Targets>, ) { if mouse_button_input.just_released(MouseButton::Left) && keyboard_input.pressed(KeyCode::KeyT) && !keyboard_input.pressed(KeyCode::Space) { let mut source_entity: (Option<Entity>, f32) = (None, f32::MIN); let mut sink_entity: (Option<Entity>, f32) = (None, f32::MIN); for e in visible.single().get::<WithMesh2d>() { if let Ok(t) = circle_trans_query.get(*e) { if cursor.i.distance(t.translation.xy()) < t.scale.x && t.translation.z > source_entity.1 { source_entity = (Some(*e), t.translation.z); } if cursor.f.distance(t.translation.xy()) < t.scale.x && t.translation.z > sink_entity.1 { sink_entity = (Some(*e), t.translation.z); } } } if let (Some(src), Some(snk)) = (source_entity.0, sink_entity.0) { // don't target self if source_entity.0 == sink_entity.0 { return; } if let Ok(mut targets) = targets_query.get_mut(src) { targets.0.push(snk); } } } } pub fn update_connection_arrows( bh_query: Query<(Entity, &BlackHole), (Changed<Transform>, With<Vertices>)>, wh_query: Query<(Entity, &WhiteHole), (Changed<Transform>, With<Vertices>)>, trans_query: Query<&Transform, With<Vertices>>, mut arrow_trans: Query<&mut Transform, Without<Vertices>>, arrow_query: Query<&ConnectionArrow>, connection_width: Res<ConnectionWidth>, ) { for (id, bh) in bh_query.iter() { if wh_query.contains(bh.wh) { continue; } if let (Ok(bh_t), Ok(wh_t)) = (trans_query.get(id), trans_query.get(bh.wh)) { let bh_radius = bh_t.scale.x; let wh_radius = wh_t.scale.x; let bh_trans = bh_t.translation.xy(); let wh_trans = wh_t.translation.xy(); if let Ok(arrow_id) = arrow_query.get(bh.wh) { let perp = (bh_trans - wh_trans).perp(); let norm = (wh_trans - bh_trans).normalize_or_zero(); let i = wh_trans - wh_radius * norm; let f = bh_trans + bh_radius * norm; *arrow_trans.get_mut(arrow_id.0).unwrap() = Transform { translation: ((i + f) / 2.).extend(100.), scale: Vec3::new( connection_width.0, wh_trans.distance(bh_trans) - (bh_radius + wh_radius), 1., ), rotation: Quat::from_rotation_z(perp.to_angle()), }; } } } for (id, wh) in wh_query.iter() { if let (Ok(bh_t), Ok(wh_t)) = (trans_query.get(wh.bh), trans_query.get(id)) { let bh_radius = bh_t.scale.x; let wh_radius = wh_t.scale.x; let bh_trans = bh_t.translation.xy(); let wh_trans = wh_t.translation.xy(); if let Ok(arrow_id) = arrow_query.get(id) { let perp = (bh_trans - wh_trans).perp(); let norm = (wh_trans - bh_trans).normalize_or_zero(); let i = wh_trans - wh_radius * norm; let f = bh_trans + bh_radius * norm; *arrow_trans.get_mut(arrow_id.0).unwrap() = Transform { translation: ((i + f) / 2.).extend(100.), scale: Vec3::new( connection_width.0, wh_trans.distance(bh_trans) - (bh_radius + wh_radius), 1., ), rotation: Quat::from_rotation_z(perp.to_angle()), }; } } } } pub fn connect_targets( mut commands: Commands, query: Query<(Entity, &Transform, &Vertices), With<Order>>, mut materials: ResMut<Assets<ColorMaterial>>, mut holes_query: Query<&mut Holes>, polygon_handles: Res<PolygonHandles>, arrow_handle: Res<ArrowHandle>, connection_mat: Res<ConnectionMat>, mut connect_command: EventReader<ConnectCommand>, arr_query: Query<&Arr>, mut targets_query: Query<&mut Targets>, white_hole_query: Query<&WhiteHole>, ) { for e in connect_command.read() { let targets = &targets_query.get(e.0).unwrap().0; if targets.is_empty() { continue; } let arr = &arr_query.get(e.0).unwrap().0; let lt = if let Some(a) = arr.get(0..2) { (a[0] as i8, a[1] as i8) } else { (0, 0) }; let mut white_holes = Vec::new(); for pair in targets.windows(2) { let (src, snk) = (pair[0], pair[1]); // don't connect entity to itself if src == snk { continue; } // get translation, radius, and vertices let src_trans = query.get(src).unwrap().1.translation; let snk_trans = query.get(snk).unwrap().1.translation; let src_radius = query.get(src).unwrap().1.scale.x; let snk_radius = query.get(snk).unwrap().1.scale.x; let src_verts = query.get(src).unwrap().2 .0; let snk_verts = query.get(snk).unwrap().2 .0; let bh_radius = src_radius * 0.15; let wh_radius = snk_radius * 0.15; // spawn connection arrow let arrow = commands .spawn(( ColorMesh2dBundle { mesh: arrow_handle.0.clone(), material: connection_mat.0.clone(), transform: Transform::default(), ..default() }, RenderLayers::layer(4), )) .id(); // spawn circles let bh_depth = 0.001 * (holes_query.get(src).unwrap().0.len() + 1) as f32; let bh_verts = snk_verts; let bh_color = Hsla::new(0., 0., 0.2, 1.); let black_hole = commands .spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[bh_verts].clone().unwrap(), material: materials.add(ColorMaterial::from_color(bh_color)), transform: Transform { translation: src_trans.xy().extend(bh_depth + src_trans.z), scale: Vec3::new(bh_radius, bh_radius, 1.), ..default() }, ..default() }, Col(bh_color), Vertices(bh_verts), RenderLayers::layer(2), )) .id(); let wh_depth = 0.001 * (holes_query.get(snk).unwrap().0.len() + 1) as f32; let wh_verts = src_verts; let wh_color = Hsla::new(0., 0., 0.8, 1.); let white_hole = commands .spawn(( ColorMesh2dBundle { mesh: polygon_handles.0[bh_verts].clone().unwrap(), material: materials.add(ColorMaterial::from_color(wh_color)), transform: Transform { translation: snk_trans.xy().extend(wh_depth + snk_trans.z), scale: Vec3::new(wh_radius, wh_radius, 1.), ..default() }, ..default() }, Col(wh_color), Vertices(wh_verts), WhiteHole { bh_parent: src, bh: black_hole, link_types: lt, open: true }, RenderLayers::layer(3), ConnectionArrow(arrow), )) .id(); // insert black hole white hole commands.entity(black_hole).insert(BlackHole { wh: white_hole, wh_parent: snk }); // add to parents holes_query.get_mut(src).unwrap().0.push(black_hole); holes_query.get_mut(snk).unwrap().0.push(white_hole); white_holes.push(white_hole); } for hole in &holes_query.get(e.0).unwrap().0 { if let Ok(wh) = white_hole_query.get(*hole) { if wh.link_types == (-14, 2) { targets_query.get_mut(wh.bh_parent).unwrap().0 = white_holes; break; } } } } }
rust
Apache-2.0
266a3df12648a73b57fdae26694bdbcbf70fcb45
2026-01-04T20:23:10.292062Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/src/args.rs
src/args.rs
use clap::Parser; #[cfg(feature = "tls")] use clap::ValueHint; use hyper::header::{HeaderMap, HeaderName, HeaderValue}; use std::net::IpAddr; #[cfg(feature = "tls")] use std::path::PathBuf; #[derive(Debug, Clone, Parser)] #[command(name = "dummyhttp", author, about, version)] pub struct Args { /// Be quiet (log nothing) #[arg(short, long)] pub quiet: bool, /// Be verbose (log data of incoming and outgoing requests). If given twice it will also log /// the body data. #[arg(short, long, action = clap::ArgAction::Count)] pub verbose: u8, /// Port on which to listen #[arg(short, long, default_value = "8080")] pub port: u16, /// Headers to send (format: key:value) #[arg(short = 'H', long, value_parser(parse_header))] pub headers: Vec<HeaderMap>, /// HTTP status code to send #[arg(short, long, default_value = "200")] pub code: u16, /// HTTP body to send /// /// Supports Tera-based templating (https://tera.netlify.app/docs/) with a few additional /// functions over the default built-ins: /// /// uuid() - generate a random UUID /// lorem(words) - generate `words` lorem ipsum words /// /// Example: dummyhttp -b "Hello {{ uuid() }}, it's {{ now() | date(format="%Y") }} {{ lorem(words=5)}}" #[arg(short, long, default_value = "dummyhttp", verbatim_doc_comment)] pub body: String, /// Interface to bind to #[arg( short, long, value_parser(parse_interface), number_of_values = 1, default_value = "0.0.0.0" )] pub interface: IpAddr, /// Delay in milliseconds before sending the response in milliseconds #[arg(short, long, default_value = "0")] pub delay: u64, /// Generate completion file for a shell #[arg(long = "print-completions", value_name = "shell")] pub print_completions: Option<clap_complete::Shell>, /// Generate man page #[arg(long = "print-manpage")] pub print_manpage: bool, /// TLS certificate to use #[cfg(feature = "tls")] #[arg(long = "tls-cert", alias = "cert", requires = "tls_key", value_hint = ValueHint::FilePath)] pub tls_cert: Option<PathBuf>, /// TLS private key to use #[cfg(feature = "tls")] #[arg(long = "tls-key", alias = "key", requires = "tls_cert", value_hint = ValueHint::FilePath)] pub tls_key: Option<PathBuf>, } /// Checks wether an interface is valid, i.e. it can be parsed into an IP address fn parse_interface(src: &str) -> Result<IpAddr, std::net::AddrParseError> { src.parse::<IpAddr>() } /// Parse a header given in a string format into a `HeaderMap` /// /// Headers are expected to be in format "key:value". fn parse_header(header: &str) -> Result<HeaderMap, String> { let header: Vec<&str> = header.split(':').collect(); if header.len() != 2 { return Err("Wrong header format (see --help for format)".to_string()); } let (header_name, header_value) = (header[0], header[1]); let hn = HeaderName::from_lowercase(header_name.to_lowercase().as_bytes()) .map_err(|e| e.to_string())?; let hv = HeaderValue::from_str(header_value).map_err(|e| e.to_string())?; let mut map = HeaderMap::new(); map.insert(hn, hv); Ok(map) }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/src/main.rs
src/main.rs
use std::{collections::HashMap, net::SocketAddr}; #[cfg(not(feature = "tls"))] use anyhow::Result; #[cfg(feature = "tls")] use anyhow::{Context, Result}; use axum::{ body::{Body, Bytes}, extract::{ConnectInfo, Request}, http::{HeaderValue, StatusCode, Uri}, middleware::{self, Next}, response::{IntoResponse, Response}, Extension, Router, }; #[cfg(feature = "tls")] use axum_server::tls_rustls::RustlsConfig; use chrono::Local; use clap::{crate_version, CommandFactory, Parser}; use colored::*; use colored_json::ToColoredJson; use hyper::{header::CONTENT_TYPE, HeaderMap}; use inflector::Inflector; use tokio::time::{sleep, Duration}; use crate::args::Args; mod args; pub fn template_uuid(_args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> { Ok(tera::to_value(uuid::Uuid::new_v4().to_string()).unwrap()) } pub fn template_lorem(args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> { let n_words = args .get("words") .and_then(|w| w.as_u64()) .ok_or_else(|| tera::Error::from("Failed to template lorem"))?; Ok(tera::to_value(lipsum::lipsum(n_words as usize)).unwrap()) } /// dummyhttp only has a single response and this is it :) async fn dummy_response(_uri: Uri, Extension(args): Extension<Args>) -> impl IntoResponse { let status_code = StatusCode::from_u16(args.code).unwrap(); let mut headers = HeaderMap::new(); for header in &args.headers { let val = header.iter().next().unwrap(); headers.insert(val.0.clone(), val.1.clone()); } // Manually insert a Date header here so that our log print will catch it later on as the // date is inserted _after_ logging otherwise. let time = Local::now(); headers.insert("date", HeaderValue::from_str(&time.to_rfc2822()).unwrap()); // Render body as Tera template. let mut tera = tera::Tera::default(); tera.register_function("uuid", template_uuid); tera.register_function("lorem", template_lorem); let rendered_body = tera.render_str(&args.body, &tera::Context::new()).unwrap(); // Delay response. sleep(Duration::from_millis(args.delay)).await; (status_code, headers, rendered_body) } async fn print_request_response( req: Request, next: Next, ) -> Result<impl IntoResponse, (StatusCode, String)> { let args = req.extensions().get::<Args>().unwrap().clone(); let ConnectInfo(peer_info) = *req.extensions().get::<ConnectInfo<SocketAddr>>().unwrap(); let method = req.method().to_string(); let uri = req.uri().to_string(); let http_version = format!("{:?}", req.version()) .split('/') .nth(1) .unwrap_or("unknown") .to_string(); let req_headers = req.headers().clone(); let (parts, body) = req.into_parts(); let bytes = buffer_and_print("request", body).await?; let bytes2 = bytes.clone(); let req = Request::from_parts(parts, Body::from(bytes)); let resp = next.run(req).await; let time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string(); let connect_line = format!( "{time} {peer_info} {method} {uri} {http}/{version}", time = time.yellow(), peer_info = peer_info.to_string().bold(), method = method.green(), uri = uri.cyan().underline(), http = "HTTP".blue(), version = http_version.blue(), ); if args.verbose >= 1 { let method_path_version_line = format!( "{method} {uri} {http}/{version}", method = method.green(), uri = uri.cyan().underline(), http = "HTTP".blue(), version = http_version.blue(), ); let mut incoming_headers_vec = vec![]; for (hk, hv) in &req_headers { incoming_headers_vec.push(format!( "{deco} {key}: {value}", deco = "│".green().bold(), key = Inflector::to_train_case(hk.as_str()).cyan(), value = hv.to_str().unwrap_or("<unprintable>") )); } incoming_headers_vec.sort(); if !incoming_headers_vec.is_empty() { incoming_headers_vec.insert(0, "".to_string()); } let incoming_headers = incoming_headers_vec.join("\n"); let body = String::from_utf8_lossy(&bytes2); let req_body_text = if body.is_empty() || args.verbose < 2 { "".to_string() } else { let mut body_invalid_json = false; let body_formatted = if let Some(content_type) = req_headers.get(CONTENT_TYPE) { if content_type == "application/json" { serde_json::from_str::<serde_json::Value>(&body) .and_then(|loaded_json| serde_json::to_string_pretty(&loaded_json)) .and_then(|pretty_json| pretty_json.to_colored_json_auto()) .unwrap_or_else(|_| { body_invalid_json = true; body.to_string() }) } else { body.to_string() } } else { body.to_string() }; let body_title = if body_invalid_json { "Body (invalid JSON):" } else { "Body:" }; let body_formatted = body_formatted .lines() .map(|line| format!("{deco} {line}", deco = "│".green().bold(), line = line)) .collect::<Vec<_>>() .join("\n"); format!( "\n{deco} {body}\n{body_formatted}", deco = "│".green().bold(), body = body_title.yellow(), body_formatted = body_formatted, ) }; let req_info = format!( "{deco} {method_path_version_line}{headers}{req_body_text}", deco = "│".green().bold(), method_path_version_line = method_path_version_line, headers = incoming_headers, req_body_text = req_body_text, ); let status_line = format!( "{http}/{version} {status_code} {status_text}", http = "HTTP".blue(), version = http_version.blue(), status_code = resp.status().as_u16().to_string().blue(), status_text = resp.status().canonical_reason().unwrap_or("").cyan(), ); let mut outgoing_headers_vec = vec![]; for (hk, hv) in resp.headers() { outgoing_headers_vec.push(format!( "{deco} {key}: {value}", deco = "│".red().bold(), key = Inflector::to_train_case(hk.as_str()).cyan(), value = hv.to_str().unwrap_or("<unprintable>") )); } if !outgoing_headers_vec.is_empty() { outgoing_headers_vec.insert(0, "".to_string()); } outgoing_headers_vec.sort(); let outgoing_headers = outgoing_headers_vec.join("\n"); let resp_body_text = if args.body.is_empty() || args.verbose < 2 { "".to_string() } else { let body_formatted = args .body .lines() .map(|line| format!("{deco} {line}", deco = "│".red().bold(), line = line)) .collect::<Vec<_>>() .join("\n"); format!( "\n{deco} {body}\n{body_formatted}", deco = "│".red().bold(), body = "Body:".yellow(), body_formatted = body_formatted, ) }; let resp_info = format!( "{deco} {status_line}{headers}{resp_body_text}", deco = "│".red().bold(), status_line = status_line, headers = outgoing_headers, resp_body_text = resp_body_text, ); println!( "{connect_line}\n{req_banner}\n{req_info}\n{resp_banner}\n{resp_info}", req_banner = "┌─Incoming request".green().bold(), req_info = req_info, resp_banner = "┌─Outgoing response".red().bold(), resp_info = resp_info, ); } else if !args.quiet { println!("{connect_line}",); } let (parts, body) = resp.into_parts(); let bytes = buffer_and_print("response", body).await?; let resp = Response::from_parts(parts, Body::from(bytes)); Ok(resp) } async fn buffer_and_print(direction: &str, body: Body) -> Result<Bytes, (StatusCode, String)> { let bytes = match axum::body::to_bytes(body, usize::MAX).await { Ok(bytes) => bytes, Err(err) => { return Err(( StatusCode::BAD_REQUEST, format!("failed to read {direction} body: {err}"), )); } }; Ok(bytes) } #[tokio::main] async fn main() -> Result<()> { let args = Args::parse(); if let Some(shell) = args.print_completions { let mut clap_app = args::Args::command(); let app_name = clap_app.get_name().to_string(); clap_complete::generate(shell, &mut clap_app, app_name, &mut std::io::stdout()); return Ok(()); } if args.print_manpage { let clap_app = args::Args::command(); let man = clap_mangen::Man::new(clap_app); man.render(&mut std::io::stdout())?; return Ok(()); } let app = Router::new() .fallback(dummy_response) .layer(middleware::from_fn(print_request_response)) .layer(Extension(args.clone())); let addr = SocketAddr::from((args.interface, args.port)); if !args.quiet { let protocol = { #[cfg(feature = "tls")] if args.tls_cert.is_some() { "https://" } else { "http://" } #[cfg(not(feature = "tls"))] "http://" }; println!( "{}{} {} {}{}", "dummyhttp v".bold(), crate_version!().bold(), "listening on".dimmed(), protocol.bold(), addr.to_string().bold() ); } // configure certificate and private key used by https #[cfg(feature = "tls")] if let (Some(tls_cert), Some(tls_key)) = (args.tls_cert, args.tls_key) { rustls::crypto::ring::default_provider() .install_default() .expect("Failed to install rustls crypto provider"); let tls_config = RustlsConfig::from_pem_file(&tls_cert, &tls_key) .await .context(format!( "Failed to load certificate file '{}' or key '{}'", tls_cert.to_string_lossy(), tls_key.to_string_lossy() ))?; axum_server::bind_rustls(addr, tls_config) .serve(app.into_make_service_with_connect_info::<SocketAddr>()) .await?; } else { axum_server::bind(addr) .serve(app.into_make_service_with_connect_info::<SocketAddr>()) .await?; } #[cfg(not(feature = "tls"))] axum_server::bind(addr) .serve(app.into_make_service_with_connect_info::<SocketAddr>()) .await?; Ok(()) }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/tests/tls.rs
tests/tls.rs
mod utils; use assert_cmd::prelude::*; use axum::http::StatusCode; use predicates::str::contains; use reqwest::blocking::ClientBuilder; use std::process::Command; use utils::{DummyhttpProcess, Error}; /// We can connect to a secured connection. #[test] fn tls_works() -> Result<(), Error> { let dh = DummyhttpProcess::new(vec![ "--tls-cert", "tests/data/cert.pem", "--tls-key", "tests/data/key.pem", ])?; let client = ClientBuilder::new() .danger_accept_invalid_certs(true) .build()?; let resp = client.get(&dh.url).send()?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.text()?, "dummyhttp"); Ok(()) } /// Wrong path for cert throws error. #[test] fn wrong_path_cert() -> Result<(), Error> { Command::cargo_bin("dummyhttp")? .args(["--tls-cert", "wrong", "--tls-key", "tests/data/key.pem"]) .assert() .failure() .stderr(contains( "Error: Failed to load certificate file 'wrong' or key 'tests/data/key.pem'", )); Ok(()) } /// Wrong paths for key throws errors. #[test] fn wrong_path_key() -> Result<(), Error> { Command::cargo_bin("dummyhttp")? .args(["--tls-cert", "tests/data/cert.pem", "--tls-key", "wrong"]) .assert() .failure() .stderr(contains( "Error: Failed to load certificate file 'tests/data/cert.pem' or key 'wrong'", )); Ok(()) }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/tests/basic.rs
tests/basic.rs
mod utils; use assert_cmd::prelude::*; use clap::{crate_name, crate_version}; use reqwest::blocking::Client; use rstest::rstest; use std::io::Read; use std::process::Command; use utils::{DummyhttpProcess, Error}; /// Show help and exit. #[test] fn help_shows() -> Result<(), Error> { Command::cargo_bin("dummyhttp")? .arg("--help") .assert() .success(); Ok(()) } /// Show version and exit. #[test] fn version_shows() -> Result<(), Error> { Command::cargo_bin("dummyhttp")? .arg("-V") .assert() .success() .stdout(format!("{} {}\n", crate_name!(), crate_version!())); Ok(()) } /// If provided with no options, we're shown some basic information on stdout. #[test] fn has_some_output_by_default() -> Result<(), Error> { let mut dh = DummyhttpProcess::new(Vec::<String>::new())?; reqwest::blocking::get(&dh.url)?.error_for_status()?; dh.child.kill()?; let mut output = String::new(); dh.child .stdout .as_mut() .unwrap() .read_to_string(&mut output)?; assert!(output.contains("dummyhttp")); assert!(output.contains("GET")); Ok(()) } /// If we pass --quiet, we get no output. #[test] fn has_quiet_output() -> Result<(), Error> { let mut dh = DummyhttpProcess::new(vec!["--quiet"])?; reqwest::blocking::get(&dh.url)?.error_for_status()?; dh.child.kill()?; let mut output = String::new(); dh.child .stdout .as_mut() .unwrap() .read_to_string(&mut output)?; dbg!(&output); assert!(output.is_empty()); Ok(()) } /// If we pass -v/--verbose, we get a ton of pretty output. #[rstest(flag, case::v("-v"), case::verbose("--verbose"))] fn has_verbose_output(flag: &'static str) -> Result<(), Error> { let mut dh = DummyhttpProcess::new(vec![flag, "-b", "teststring"])?; let client = Client::new(); client .post(&dh.url) .body("some body") .send()? .error_for_status()?; dh.child.kill()?; let mut output = String::new(); dh.child .stdout .as_mut() .unwrap() .read_to_string(&mut output)?; assert!(output.contains("Incoming request")); assert!(output.contains("Outgoing response")); assert!(!output.contains("teststring")); assert!(!output.contains("some body")); Ok(()) } /// If we pass -vv, we also get body output. #[test] fn has_very_verbose_output() -> Result<(), Error> { let mut dh = DummyhttpProcess::new(vec!["-vv", "-b", "teststring"])?; let client = Client::new(); client .post(&dh.url) .body("some body") .send()? .error_for_status()?; dh.child.kill()?; let mut output = String::new(); dh.child .stdout .as_mut() .unwrap() .read_to_string(&mut output)?; assert!(output.contains("Incoming request")); assert!(output.contains("Outgoing response")); assert!(output.contains("teststring")); assert!(output.contains("some body")); Ok(()) }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/tests/requests.rs
tests/requests.rs
mod utils; use axum::http::{self, Method, StatusCode}; use chrono::DateTime; use reqwest::blocking::Client; use rstest::rstest; use rstest_reuse::{self, apply, template}; use utils::{DummyhttpProcess, Error}; use uuid::Uuid; #[template] #[rstest( method, case::get(Method::GET), case::post(Method::POST), case::put(Method::PUT), case::delete(Method::DELETE), case::options(Method::OPTIONS), case::patch(Method::PATCH) )] fn http_methods(method: http::Method) {} /// By default, we expect a 200 OK answer with a "dummyhttp" text body. #[apply(http_methods)] fn serves_requests_with_no_options(method: http::Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(Vec::<String>::new())?; let client = Client::new(); let resp = client.request(method, &dh.url).send()?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.text()?, "dummyhttp"); Ok(()) } /// Setting a custom body will always answer with that body. #[apply(http_methods)] fn returns_custom_body(method: Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(vec!["-b", "hi test"])?; let client = Client::new(); let resp = client.request(method, &dh.url).send()?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.text()?, "hi test"); Ok(()) } /// Setting a custom body with Tera templating will template fine. #[apply(http_methods)] fn returns_templated_body(method: Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(vec!["-b", "{{ uuid() }} {{ now() }} {{ lorem(words=5)}}"])?; let client = Client::new(); let resp = client.request(method, &dh.url).send()?; assert_eq!(resp.status(), StatusCode::OK); let body = resp.text()?; let body_split = body.split_ascii_whitespace().collect::<Vec<_>>(); assert!(Uuid::parse_str(body_split[0]).is_ok()); assert!(DateTime::parse_from_rfc3339(body_split[1]).is_ok()); assert_eq!(body_split.len(), 7); Ok(()) } /// Setting a custom code will always answer with that code. #[apply(http_methods)] fn returns_custom_code(method: Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(vec!["-c", "201"])?; let client = Client::new(); let resp = client.request(method, &dh.url).send()?; assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(resp.text()?, "dummyhttp"); Ok(()) } /// Setting a custom header will always return that header. #[apply(http_methods)] fn returns_custom_headers(method: Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(vec!["-H", "test:header"])?; let client = Client::new(); let resp = client.request(method, &dh.url).send()?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.headers().get("test").unwrap(), "header"); assert_eq!(resp.text()?, "dummyhttp"); Ok(()) } /// Setting a custom delay will delay the response making it at least that long. #[apply(http_methods)] fn returns_custom_delay(method: Method) -> Result<(), Error> { let dh = DummyhttpProcess::new(vec!["-d", "1000"])?; let client = Client::new(); let start = std::time::Instant::now(); let resp = client.request(method, &dh.url).send()?; let elapsed = start.elapsed(); assert_eq!(resp.status(), StatusCode::OK); assert!(elapsed >= std::time::Duration::from_millis(1000)); assert_eq!(resp.text()?, "dummyhttp"); Ok(()) }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
svenstaro/dummyhttp
https://github.com/svenstaro/dummyhttp/blob/67c13e1fabb8b01bfcac67914310fe2967ce43f5/tests/utils/mod.rs
tests/utils/mod.rs
use assert_cmd::prelude::*; use port_check::{free_local_port, is_port_reachable}; use std::ffi::OsStr; use std::process::{Child, Command, Stdio}; use std::thread::sleep; use std::time::{Duration, Instant}; /// Error type used by tests pub type Error = Box<dyn std::error::Error>; #[derive(Debug)] pub struct DummyhttpProcess { pub child: Child, pub url: String, } impl Drop for DummyhttpProcess { fn drop(&mut self) { if let Err(e) = self.child.kill() { eprintln!("WARN: {}", e); } } } #[allow(dead_code)] impl DummyhttpProcess { /// Get a Dummyhttp instance on a free port. pub fn new<I, S>(args: I) -> Result<Self, Error> where I: IntoIterator<Item = S> + Clone + std::fmt::Debug, S: AsRef<OsStr> + PartialEq + From<&'static str>, { let port = free_local_port() .expect("Couldn't find a free local port") .to_string(); let child = Command::cargo_bin("dummyhttp")? .arg("-p") .arg(&port) .args(args.clone()) .stdout(Stdio::piped()) .spawn()?; // Wait a max of 1s for the port to become available. let start_wait = Instant::now(); while start_wait.elapsed().as_secs() < 1 && !is_port_reachable(format!("localhost:{}", port)) { sleep(Duration::from_millis(100)); } let proto = if args.into_iter().any(|x| x == "--tls-cert".into()) { "https".to_string() } else { "http".to_string() }; let url = format!("{proto}://localhost:{port}", proto = proto, port = port); Ok(Self { child, url }) } }
rust
MIT
67c13e1fabb8b01bfcac67914310fe2967ce43f5
2026-01-04T20:23:03.211264Z
false
micahrj/basedrop
https://github.com/micahrj/basedrop/blob/af93bdc15e0dd4b2df2dd856e47624a775d5761c/src/lib.rs
src/lib.rs
//! Memory-management tools for real-time audio and other latency-critical scenarios. //! //! - [`Owned`] and [`Shared`] are smart pointers analogous to `Box` and `Arc` //! which add their contents to a queue for deferred collection when dropped. //! - [`Collector`] is used to process the drop queue. //! - [`Node`] provides a lower-level interface for implementing custom smart //! pointers or data structures. //! - [`SharedCell`] implements a mutable memory location holding a [`Shared`] //! pointer that can be used by multiple readers and writers in a thread-safe //! manner. //! //! [`Owned`]: crate::Owned //! [`Shared`]: crate::Shared //! [`Collector`]: crate::Collector //! [`Node`]: crate::Node //! [`SharedCell`]: crate::SharedCell #![no_std] mod collector; mod owned; mod shared; mod shared_cell; pub use collector::*; pub use owned::*; pub use shared::*; pub use shared_cell::*;
rust
Apache-2.0
af93bdc15e0dd4b2df2dd856e47624a775d5761c
2026-01-04T20:23:13.172324Z
false
micahrj/basedrop
https://github.com/micahrj/basedrop/blob/af93bdc15e0dd4b2df2dd856e47624a775d5761c/src/shared_cell.rs
src/shared_cell.rs
use crate::{Node, Shared, SharedInner}; use core::marker::PhantomData; use core::ptr::NonNull; use core::sync::atomic::{fence, AtomicPtr, AtomicUsize, Ordering}; /// A thread-safe shared mutable memory location that holds a [`Shared<T>`]. /// /// `SharedCell` is designed to be low-overhead for readers at the expense of /// somewhat higher overhead for writers. /// /// [`Shared<T>`]: crate::Shared pub struct SharedCell<T> { readers: AtomicUsize, node: AtomicPtr<Node<SharedInner<T>>>, phantom: PhantomData<Shared<T>>, } unsafe impl<T: Send + Sync> Send for SharedCell<T> {} unsafe impl<T: Send + Sync> Sync for SharedCell<T> {} impl<T: Send + 'static> SharedCell<T> { /// Constructs a new `SharedCell` containing `value`. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared, SharedCell}; /// /// let collector = Collector::new(); /// let three = Shared::new(&collector.handle(), 3); /// let cell = SharedCell::new(three); /// ``` pub fn new(value: Shared<T>) -> SharedCell<T> { let node = value.node.as_ptr(); core::mem::forget(value); SharedCell { readers: AtomicUsize::new(0), node: AtomicPtr::new(node), phantom: PhantomData, } } } impl<T> SharedCell<T> { /// Gets a copy of the contained [`Shared<T>`], incrementing its reference /// count in the process. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared, SharedCell}; /// /// let collector = Collector::new(); /// let x = Shared::new(&collector.handle(), 3); /// let cell = SharedCell::new(x); /// /// let y = cell.get(); /// ``` /// /// [`Shared<T>`]: crate::Shared pub fn get(&self) -> Shared<T> { self.readers.fetch_add(1, Ordering::SeqCst); let shared = Shared { node: unsafe { NonNull::new_unchecked(self.node.load(Ordering::SeqCst)) }, phantom: PhantomData, }; let copy = shared.clone(); core::mem::forget(shared); self.readers.fetch_sub(1, Ordering::Relaxed); copy } /// Replaces the contained [`Shared<T>`], decrementing its reference count /// in the process. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared, SharedCell}; /// /// let collector = Collector::new(); /// let x = Shared::new(&collector.handle(), 3); /// let cell = SharedCell::new(x); /// /// let y = Shared::new(&collector.handle(), 4); /// cell.set(y); /// ``` /// /// [`Shared<T>`]: crate::Shared pub fn set(&self, value: Shared<T>) { let old = self.replace(value); core::mem::drop(old); } /// Replaces the contained [`Shared<T>`] and returns it. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared, SharedCell}; /// /// let collector = Collector::new(); /// let x = Shared::new(&collector.handle(), 3); /// let cell = SharedCell::new(x); /// /// let y = Shared::new(&collector.handle(), 4); /// let x = cell.replace(y); /// ``` /// /// [`Shared<T>`]: crate::Shared pub fn replace(&self, value: Shared<T>) -> Shared<T> { let node = value.node.as_ptr(); core::mem::forget(value); let old = self.node.swap(node, Ordering::AcqRel); while self.readers.load(Ordering::Relaxed) != 0 {} fence(Ordering::Acquire); Shared { node: unsafe { NonNull::new_unchecked(old) }, phantom: PhantomData, } } /// Consumes the `SharedCell` and returns the contained [`Shared<T>`]. This /// is safe because we are guaranteed to be the only holder of the /// `SharedCell`. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared, SharedCell}; /// /// let collector = Collector::new(); /// let x = Shared::new(&collector.handle(), 3); /// let cell = SharedCell::new(x); /// /// let x = cell.into_inner(); /// ``` /// /// [`Shared<T>`]: crate::Shared pub fn into_inner(mut self) -> Shared<T> { let node = core::mem::replace(&mut self.node, AtomicPtr::new(core::ptr::null_mut())); core::mem::forget(self); Shared { node: unsafe { NonNull::new_unchecked(node.into_inner()) }, phantom: PhantomData, } } } impl<T> Drop for SharedCell<T> { fn drop(&mut self) { let _ = Shared { node: unsafe { NonNull::new_unchecked(self.node.load(Ordering::Relaxed)) }, phantom: PhantomData, }; } } #[cfg(test)] mod tests { use crate::{Collector, Shared, SharedCell}; use core::sync::atomic::{AtomicUsize, Ordering}; #[test] fn shared_cell() { extern crate alloc; use alloc::sync::Arc; struct Test(Arc<AtomicUsize>); impl Drop for Test { fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } } let counter = Arc::new(AtomicUsize::new(0)); let mut collector = Collector::new(); let shared = Shared::new(&collector.handle(), Test(counter.clone())); let cell = SharedCell::new(shared); collector.collect(); assert_eq!(counter.load(Ordering::Relaxed), 0); let copy = cell.get(); let copy2 = cell.replace(copy); collector.collect(); assert_eq!(counter.load(Ordering::Relaxed), 0); core::mem::drop(cell); collector.collect(); assert_eq!(counter.load(Ordering::Relaxed), 0); core::mem::drop(copy2); collector.collect(); assert_eq!(counter.load(Ordering::Relaxed), 1); } }
rust
Apache-2.0
af93bdc15e0dd4b2df2dd856e47624a775d5761c
2026-01-04T20:23:13.172324Z
false
micahrj/basedrop
https://github.com/micahrj/basedrop/blob/af93bdc15e0dd4b2df2dd856e47624a775d5761c/src/owned.rs
src/owned.rs
use crate::{Handle, Node}; use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use core::ptr::NonNull; /// An owned smart pointer with deferred collection, analogous to `Box`. /// /// When an `Owned<T>` is dropped, its contents are added to the drop queue /// of the [`Collector`] whose [`Handle`] it was originally allocated with. /// As the collector may be on another thread, contents are required to be /// `Send + 'static`. /// /// [`Collector`]: crate::Collector /// [`Handle`]: crate::Handle pub struct Owned<T> { node: NonNull<Node<T>>, phantom: PhantomData<T>, } unsafe impl<T: Send> Send for Owned<T> {} unsafe impl<T: Sync> Sync for Owned<T> {} impl<T: Send + 'static> Owned<T> { /// Constructs a new `Owned<T>`. /// /// # Examples /// ``` /// use basedrop::{Collector, Owned}; /// /// let collector = Collector::new(); /// let three = Owned::new(&collector.handle(), 3); /// ``` pub fn new(handle: &Handle, data: T) -> Owned<T> { Owned { node: unsafe { NonNull::new_unchecked(Node::alloc(handle, data)) }, phantom: PhantomData, } } } impl<T: Clone + Send + 'static> Clone for Owned<T> { fn clone(&self) -> Self { let handle = unsafe { Node::handle(self.node.as_ptr()) }; Owned::new(&handle, self.deref().clone()) } } impl<T> Deref for Owned<T> { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &self.node.as_ref().data } } } impl<T> DerefMut for Owned<T> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut self.node.as_mut().data } } } impl<T> Drop for Owned<T> { fn drop(&mut self) { unsafe { Node::queue_drop(self.node.as_ptr()); } } }
rust
Apache-2.0
af93bdc15e0dd4b2df2dd856e47624a775d5761c
2026-01-04T20:23:13.172324Z
false
micahrj/basedrop
https://github.com/micahrj/basedrop/blob/af93bdc15e0dd4b2df2dd856e47624a775d5761c/src/collector.rs
src/collector.rs
use core::mem::ManuallyDrop; use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; extern crate alloc; use alloc::boxed::Box; #[repr(C)] struct NodeHeader { link: NodeLink, drop: unsafe fn(*mut NodeHeader), } #[repr(C)] union NodeLink { collector: *mut CollectorInner, next: ManuallyDrop<AtomicPtr<NodeHeader>>, } /// An allocation that can be added to its associated [`Collector`]'s drop /// queue. /// /// `Node` provides a low-level interface intended for use in the /// implementation of smart pointers and data structure internals. It is used /// in the implementations of [`Owned`] and [`Shared`]. /// /// [`Collector`]: crate::Collector /// [`Owned`]: crate::Owned /// [`Shared`]: crate::Shared #[repr(C)] pub struct Node<T> { header: NodeHeader, /// The data stored in this allocation. pub data: T, } unsafe fn drop_node<T>(node: *mut NodeHeader) { let _ = Box::from_raw(node as *mut Node<T>); } impl<T: Send + 'static> Node<T> { /// Allocates a `Node` with the given data. Note that the `Node` will not /// be added to the drop queue or freed unless [`queue_drop`] is called. /// /// # Examples /// ``` /// use basedrop::{Collector, Handle, Node}; /// /// let mut collector = Collector::new(); /// let handle = collector.handle(); /// let node = Node::alloc(&handle, 3); /// ``` /// /// [`queue_drop`]: crate::Node::queue_drop pub fn alloc(handle: &Handle, data: T) -> *mut Node<T> { unsafe { (*handle.collector).allocs.fetch_add(1, Ordering::Relaxed); } Box::into_raw(Box::new(Node { header: NodeHeader { link: NodeLink { collector: handle.collector, }, drop: drop_node::<T>, }, data, })) } } impl<T> Node<T> { /// Adds a `Node` to its associated [`Collector`]'s drop queue. The `Node` /// and its contained data may be dropped at a later time when /// [`Collector::collect`] or [`Collector::collect_one`] is called. /// /// The argument must point to a valid `Node` previously allocated with /// [`Node::alloc`]. `queue_drop` may only be called once for a given /// `Node`, and the `Node`'s data must not be accessed afterwards. /// /// # Examples /// ``` /// use basedrop::{Collector, Handle, Node}; /// /// let mut collector = Collector::new(); /// let handle = collector.handle(); /// let node = Node::alloc(&handle, 3); /// /// unsafe { /// Node::queue_drop(node); /// } /// ``` /// /// [`Collector`]: crate::Collector /// [`Collector::collect`]: crate::Collector::collect /// [`Collector::collect_one`]: crate::Collector::collect_one /// [`Node::alloc`]: crate::Node::alloc pub unsafe fn queue_drop(node: *mut Node<T>) { let collector = (*node).header.link.collector; (*node).header.link.next = ManuallyDrop::new(AtomicPtr::new(core::ptr::null_mut())); let tail = (*collector).tail.swap(node as *mut NodeHeader, Ordering::AcqRel); (*tail).link.next.store(node as *mut NodeHeader, Ordering::Release); } /// Gets a [`Handle`] to this `Node`'s associated [`Collector`]. /// /// The argument must point to a valid `Node` previously allocated with /// [`Node::alloc`], on which [`queue_drop`] has not been called. /// /// [`Handle`]: crate::Collector /// [`Collector`]: crate::Collector /// [`Node::alloc`]: crate::Node::alloc /// [`queue_drop`]: crate::Node::queue_drop pub unsafe fn handle(node: *mut Node<T>) -> Handle { let collector = (*node).header.link.collector; (*collector).handles.fetch_add(1, Ordering::Relaxed); Handle { collector } } } /// A handle to a [`Collector`], used when allocating [`Owned`] and [`Shared`] /// values. /// /// Multiple `Handle`s to a given [`Collector`] can exist at one time, and they /// can be safely moved and shared between threads. /// /// [`Collector`]: crate::Collector /// [`Owned`]: crate::Owned /// [`Shared`]: crate::Shared pub struct Handle { collector: *mut CollectorInner, } unsafe impl Send for Handle {} unsafe impl Sync for Handle {} impl Clone for Handle { fn clone(&self) -> Self { unsafe { (*self.collector).handles.fetch_add(1, Ordering::Relaxed); } Handle { collector: self.collector } } } impl Drop for Handle { fn drop(&mut self) { unsafe { (*self.collector).handles.fetch_sub(1, Ordering::Release); } } } struct CollectorInner { handles: AtomicUsize, allocs: AtomicUsize, tail: AtomicPtr<NodeHeader>, } /// A garbage collector for [`Owned`] and [`Shared`] allocations. /// /// If a `Collector` is dropped, it will leak all associated allocations as /// well as its internal data structures. To avoid this, ensure that all /// allocations have been collected and all [`Handle`]s have been dropped, then /// call [`try_cleanup`]. /// /// [`Owned`]: crate::Owned /// [`Shared`]: crate::Shared /// [`try_cleanup`]: crate::Collector::try_cleanup pub struct Collector { head: *mut NodeHeader, stub: *mut NodeHeader, inner: *mut CollectorInner, } unsafe impl Send for Collector {} impl Collector { /// Constructs a new `Collector`. pub fn new() -> Collector { let head = Box::into_raw(Box::new(Node { header: NodeHeader { link: NodeLink { next: ManuallyDrop::new(AtomicPtr::new(core::ptr::null_mut())), }, drop: drop_node::<()>, }, data: (), })) as *mut NodeHeader; let inner = Box::into_raw(Box::new(CollectorInner { handles: AtomicUsize::new(0), allocs: AtomicUsize::new(0), tail: AtomicPtr::new(head), })); Collector { head, stub: head, inner, } } /// Gets a [`Handle`] to this `Collector`. /// /// [`Handle`]: crate::Handle pub fn handle(&self) -> Handle { unsafe { (*self.inner).handles.fetch_add(1, Ordering::Relaxed); } Handle { collector: self.inner } } /// Drops all of the garbage in the queue. /// /// # Examples /// ``` /// use basedrop::{Collector, Handle, Owned}; /// use core::mem::drop; /// /// let mut collector = Collector::new(); /// let handle = collector.handle(); /// let x = Owned::new(&handle, 1); /// let y = Owned::new(&handle, 2); /// let z = Owned::new(&handle, 3); /// /// assert_eq!(collector.alloc_count(), 3); /// /// drop(x); /// drop(y); /// drop(z); /// collector.collect(); /// /// assert_eq!(collector.alloc_count(), 0); /// ``` pub fn collect(&mut self) { while self.collect_one() {} } /// Attempts to drop the first allocation in the queue. If successful, /// returns true; otherwise returns false. /// /// # Examples /// ``` /// use basedrop::{Collector, Handle, Owned}; /// use core::mem::drop; /// /// let mut collector = Collector::new(); /// let handle = collector.handle(); /// let x = Owned::new(&handle, 1); /// let y = Owned::new(&handle, 2); /// let z = Owned::new(&handle, 3); /// /// assert_eq!(collector.alloc_count(), 3); /// /// drop(x); /// drop(y); /// drop(z); /// /// assert!(collector.collect_one()); /// assert!(collector.collect_one()); /// assert!(collector.collect_one()); /// /// assert!(!collector.collect_one()); /// assert_eq!(collector.alloc_count(), 0); /// ``` pub fn collect_one(&mut self) -> bool { loop { unsafe { let next = (*self.head).link.next.load(Ordering::Acquire); if next.is_null() { return false; } let head = self.head; self.head = next; if head == self.stub { (*head).link.next.store(core::ptr::null_mut(), Ordering::Relaxed); let tail = (*self.inner).tail.swap(head, Ordering::AcqRel); (*tail).link.next.store(head, Ordering::Relaxed); } else { ((*head).drop)(head); (*self.inner).allocs.fetch_sub(1, Ordering::Relaxed); return true; } } } } /// Gets the number of live [`Handle`]s to this `Collector`. /// /// [`Handle`]: crate::Handle pub fn handle_count(&self) -> usize { unsafe { (*self.inner).handles.load(Ordering::Relaxed) } } /// Gets the number of live allocations associated with this `Collector`. pub fn alloc_count(&self) -> usize { unsafe { (*self.inner).allocs.load(Ordering::Relaxed) } } /// Attempts to free all resources associated with this `Collector`. This /// method will fail and return the original `Collector` if there are any /// live [`Handle`]s or allocations associated with it. /// /// # Examples /// ``` /// use basedrop::{Collector, Handle, Owned}; /// use core::mem::drop; /// /// let mut collector = Collector::new(); /// let handle = collector.handle(); /// let x = Owned::new(&handle, 3); /// /// let result = collector.try_cleanup(); /// assert!(result.is_err()); /// let mut collector = result.unwrap_err(); /// /// drop(handle); /// drop(x); /// collector.collect(); /// /// assert!(collector.try_cleanup().is_ok()); /// ``` /// /// [`Handle`]: crate::Handle pub fn try_cleanup(self) -> Result<(), Self> { unsafe { if (*self.inner).handles.load(Ordering::Acquire) == 0 { if (*self.inner).allocs.load(Ordering::Acquire) == 0 { let _ = Box::from_raw(self.stub); let _ = Box::from_raw(self.inner); return Ok(()); } } } Err(self) } } #[cfg(test)] mod tests { use super::*; extern crate std; use alloc::sync::Arc; use core::sync::atomic::AtomicUsize; struct Test(Arc<AtomicUsize>); impl Drop for Test { fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } } #[test] fn collector() { let counter = Arc::new(AtomicUsize::new(0)); let collector = Collector::new(); let handle = collector.handle(); let node = Node::alloc(&handle, ()); let result = collector.try_cleanup(); assert!(result.is_err()); let mut collector = result.unwrap_err(); unsafe { Node::queue_drop(node); } let mut threads = alloc::vec![]; for _ in 0..100 { let handle = handle.clone(); let counter = counter.clone(); threads.push(std::thread::spawn(move || { for _ in 0..100 { let node = Node::alloc(&handle, Test(counter.clone())); unsafe { Node::queue_drop(node); } } })); } for _ in 0..100 { collector.collect(); } for thread in threads { thread.join().unwrap(); } collector.collect(); let tail = unsafe { (*collector.inner).tail.load(Ordering::Relaxed) }; assert!(collector.head == tail); assert!(collector.head == collector.stub); let next = unsafe { (*collector.head).link.next.load(Ordering::Relaxed) }; assert!(next.is_null()); assert!(counter.load(Ordering::Relaxed) == 10000); core::mem::drop(handle); let result = collector.try_cleanup(); assert!(result.is_ok()); } }
rust
Apache-2.0
af93bdc15e0dd4b2df2dd856e47624a775d5761c
2026-01-04T20:23:13.172324Z
false
micahrj/basedrop
https://github.com/micahrj/basedrop/blob/af93bdc15e0dd4b2df2dd856e47624a775d5761c/src/shared.rs
src/shared.rs
use crate::{Handle, Node}; use core::marker::PhantomData; use core::ops::Deref; use core::ptr::NonNull; use core::sync::atomic::{AtomicUsize, Ordering, fence}; /// A reference-counted smart pointer with deferred collection, analogous to /// `Arc`. /// /// When a `Shared<T>`'s reference count goes to zero, its contents are added /// to the drop queue of the [`Collector`] whose [`Handle`] it was originally /// allocated with. As the collector may be on another thread, contents are /// required to be `Send + 'static`. /// /// [`Collector`]: crate::Collector /// [`Handle`]: crate::Handle pub struct Shared<T> { pub(crate) node: NonNull<Node<SharedInner<T>>>, pub(crate) phantom: PhantomData<SharedInner<T>>, } pub(crate) struct SharedInner<T> { count: AtomicUsize, data: T, } unsafe impl<T: Send + Sync> Send for Shared<T> {} unsafe impl<T: Send + Sync> Sync for Shared<T> {} impl<T: Send + 'static> Shared<T> { /// Constructs a new `Shared<T>`. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared}; /// /// let collector = Collector::new(); /// let three = Shared::new(&collector.handle(), 3); /// ``` pub fn new(handle: &Handle, data: T) -> Shared<T> { Shared { node: unsafe { NonNull::new_unchecked(Node::alloc(handle, SharedInner { count: AtomicUsize::new(1), data, })) }, phantom: PhantomData, } } } impl<T> Shared<T> { /// Returns a mutable reference to the contained value if there are no /// other extant `Shared` pointers to the same allocation; otherwise /// returns `None`. /// /// # Examples /// ``` /// use basedrop::{Collector, Shared}; /// /// let collector = Collector::new(); /// let mut x = Shared::new(&collector.handle(), 3); /// /// *Shared::get_mut(&mut x).unwrap() = 4; /// assert_eq!(*x, 4); /// /// let _y = Shared::clone(&x); /// assert!(Shared::get_mut(&mut x).is_none()); /// ``` pub fn get_mut(this: &mut Self) -> Option<&mut T> { unsafe { if this.node.as_ref().data.count.load(Ordering::Acquire) == 1 { Some(&mut this.node.as_mut().data.data) } else { None } } } } impl<T> Clone for Shared<T> { fn clone(&self) -> Self { unsafe { self.node.as_ref().data.count.fetch_add(1, Ordering::Relaxed); } Shared { node: self.node, phantom: PhantomData } } } impl<T> Deref for Shared<T> { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &self.node.as_ref().data.data } } } impl<T> Drop for Shared<T> { fn drop(&mut self) { unsafe { let count = self.node.as_ref().data.count.fetch_sub(1, Ordering::Release); if count == 1 { fence(Ordering::Acquire); Node::queue_drop(self.node.as_ptr()); } } } } #[cfg(test)] mod tests { use crate::{Collector, Shared}; use core::sync::atomic::{AtomicUsize, Ordering}; #[test] fn shared() { extern crate alloc; use alloc::sync::Arc; struct Test(Arc<AtomicUsize>); impl Drop for Test { fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } } let counter = Arc::new(AtomicUsize::new(0)); let mut collector = Collector::new(); let handle = collector.handle(); let shared = Shared::new(&handle, Test(counter.clone())); let mut copies = alloc::vec::Vec::new(); for _ in 0..10 { copies.push(shared.clone()); } assert_eq!(counter.load(Ordering::Relaxed), 0); core::mem::drop(shared); core::mem::drop(copies); collector.collect(); assert_eq!(counter.load(Ordering::Relaxed), 1); } #[test] fn get_mut() { let collector = Collector::new(); let mut x = Shared::new(&collector.handle(), 3); *Shared::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Shared::clone(&x); assert!(Shared::get_mut(&mut x).is_none()); } }
rust
Apache-2.0
af93bdc15e0dd4b2df2dd856e47624a775d5761c
2026-01-04T20:23:13.172324Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/lib.rs
src/lib.rs
//! Load and disply simple SVG files in Bevy. //! //! This crate provides a Bevy `Plugin` to easily load and display a simple SVG file. //! //! ## Usage //! Simply add the crate in your `Cargo.toml` and add the plugin to your app //! //! ```rust //! fn main() { //! App::new() //! .add_plugin(bevy_svg::prelude::SvgPlugin) //! .run(); //! } //! ``` // rustc #![deny(future_incompatible, nonstandard_style)] #![warn(missing_docs, rust_2018_idioms, unused)] #![allow(elided_lifetimes_in_paths)] // clippy #![warn( clippy::all, clippy::restriction, clippy::pedantic, clippy::nursery, clippy::cargo )] mod loader; #[cfg(any(feature = "2d", feature = "3d"))] mod origin; #[cfg(any(feature = "2d", feature = "3d"))] mod plugin; mod render; mod resources; mod svg; mod util; /// Import this module as `use bevy_svg::prelude::*` to get convenient imports. pub mod prelude { pub use super::{SvgPlugin, SvgSet}; #[cfg(any(feature = "2d", feature = "3d"))] pub use crate::origin::Origin; #[cfg(feature = "2d")] pub use crate::render::Svg2d; #[cfg(feature = "3d")] pub use crate::render::Svg3d; pub use crate::svg::Svg; pub use lyon_tessellation::{ FillOptions, FillRule, LineCap, LineJoin, Orientation, StrokeOptions, }; } pub use plugin::SvgSet; #[cfg(any(feature = "2d", feature = "3d"))] use crate::plugin::SvgRenderPlugin; use crate::{loader::SvgAssetLoader, svg::Svg}; use bevy::{ app::{App, Plugin}, asset::AssetApp, }; /// A plugin that provides resources and a system to draw [`Svg`]s. pub struct SvgPlugin; impl Plugin for SvgPlugin { #[inline] fn build(&self, app: &mut App) { app.init_asset::<Svg>() .init_asset_loader::<SvgAssetLoader>(); #[cfg(any(feature = "2d", feature = "3d"))] app.add_plugins(SvgRenderPlugin); } } /// A locally defined [`std::convert::Into`] surrogate to overcome orphan rules. pub trait Convert<T>: Sized { /// Converts the value to `T`. fn convert(self) -> T; }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/svg.rs
src/svg.rs
use bevy::{ asset::{Asset, Handle}, color::Color, log::{debug, trace, warn}, math::Vec2, mesh::Mesh, reflect::{Reflect, std_traits::ReflectDefault}, render::render_resource::AsBindGroup, }; use copyless::VecHelper; use lyon_path::PathEvent; use lyon_tessellation::{FillTessellator, StrokeTessellator, math::Point}; use std::{collections::VecDeque, iter::Peekable, path::PathBuf, sync::Arc}; use svgtypes::ViewBox; use usvg::{ PaintOrder, tiny_skia_path::{PathSegment, PathSegmentsIter}, }; use crate::{Convert, loader::FileSvgError, render::tessellation, util}; /// A loaded and deserialized SVG file. #[derive(AsBindGroup, Reflect, Debug, Clone, Asset)] #[reflect(Default, Debug)] pub struct Svg { /// The name of the file. pub name: String, /// Size of the SVG. pub size: Vec2, #[reflect(ignore)] /// ViewBox of the SVG. pub view_box: ViewBox, #[reflect(ignore)] /// All paths that make up the SVG. pub paths: Vec<PathDescriptor>, /// The fully tessellated paths as [`Mesh`]. pub mesh: Handle<Mesh>, } impl Default for Svg { fn default() -> Self { Self { name: Default::default(), size: Default::default(), view_box: ViewBox { x: 0., y: 0., w: 0., h: 0., }, paths: Default::default(), mesh: Default::default(), } } } impl Svg { /// Loads an SVG from bytes pub fn from_bytes( bytes: &[u8], path: impl Into<PathBuf> + Copy, fonts: Option<impl Into<PathBuf>>, ) -> Result<Svg, FileSvgError> { let mut fontdb = usvg::fontdb::Database::default(); fontdb.load_system_fonts(); let font_dir = fonts.map_or("./assets".into(), Into::into); debug!("loading fonts in {:?}", font_dir); fontdb.load_fonts_dir(font_dir); let fontdb = Arc::new(fontdb); let svg_tree = usvg::Tree::from_data( bytes, &usvg::Options { fontdb, ..Default::default() }, ) .map_err(|err| FileSvgError { error: err.into(), path: format!("{}", path.into().display()), })?; Ok(Svg::from_tree(svg_tree)) } /// Creates a bevy mesh from the SVG data. pub fn tessellate(&self) -> Mesh { let buffer = tessellation::generate_buffer( self, &mut FillTessellator::new(), &mut StrokeTessellator::new(), ); buffer.convert() } pub(crate) fn from_tree(tree: usvg::Tree) -> Svg { let view_box = tree.root().layer_bounding_box(); let size = tree.size(); let mut descriptors = Vec::new(); #[derive(Copy, Clone)] struct NodeContext<'a> { node: &'a usvg::Node, transform: usvg::Transform, is_text: bool, } let mut node_stack = tree .root() .children() .iter() // to make sure we are processing the svg with sibling > descendant priority we reverse it // and reverse the resulting descriptors before returning the final constructed svg .rev() .map(|node| NodeContext { node, transform: node.abs_transform(), is_text: false, }) .collect::<VecDeque<_>>(); while let Some(NodeContext { node, transform, is_text, }) = node_stack.pop_front() { trace!("---"); trace!("node: {:?}", node.id()); match node { usvg::Node::Group(group) => { let transform = transform.pre_concat(group.transform()); trace!("group: {:?}", group.id()); if !group.should_isolate() { for node in group.children() { node_stack.push_front(NodeContext { node, transform, is_text: false, }); } } else { todo!("group isolate not implemented") } } usvg::Node::Text(text) => { trace!("text: {:?}", text.id()); let transform = text.abs_transform(); // all transforms from here on down are identity // https://github.com/RazrFalcon/resvg/blob/1a6922d5bfcee9e69e04dc47cb0b586f1ca64a1c/crates/usvg/src/text/flatten.rs#L83-L83 let group = text.flattened(); for node in group.children() { node_stack.push_front(NodeContext { node, transform, is_text: true, }); } } usvg::Node::Path(path) => { if !path.is_visible() { trace!("path: {:?} - invisible", path.id()); continue; } trace!("path: {:?}", path.id()); let transform = if is_text { transform } else { path.abs_transform() }; trace!("{transform:?}"); let path_with_transform = PathWithTransform { path, transform, is_stroke: false, }; // inverted because we are reversing the list at the end match path.paint_order() { PaintOrder::FillAndStroke => { Self::process_stroke(&mut descriptors, path_with_transform); Self::process_fill(&mut descriptors, path_with_transform); } PaintOrder::StrokeAndFill => { Self::process_fill(&mut descriptors, path_with_transform); Self::process_stroke(&mut descriptors, path_with_transform); } } } usvg::Node::Image(image) => { warn!("image: {:?} - not implemented", image.id()); } } } descriptors.reverse(); Svg { name: Default::default(), size: Vec2::new(size.width(), size.height()), view_box: ViewBox { x: view_box.x() as f64, y: view_box.y() as f64, w: view_box.width() as f64, h: view_box.height() as f64, }, paths: descriptors, mesh: Default::default(), } } fn process_fill(descriptors: &mut Vec<PathDescriptor>, path_with_transform: PathWithTransform) { let path = path_with_transform.path; // from resvg render logic if path.data().bounds().width() == 0.0 || path.data().bounds().height() == 0.0 { // Horizontal and vertical lines cannot be filled. Skip. return; } let Some(fill) = &path.fill() else { return; }; let color = match fill.paint() { usvg::Paint::Color(c) => { Color::srgba_u8(c.red, c.green, c.blue, fill.opacity().to_u8()) } usvg::Paint::LinearGradient(g) => { // TODO: implement // just taking the average between the first and last stop so we get something to render crate::util::paint::avg_gradient(g) } usvg::Paint::RadialGradient(g) => { // TODO: implement // just taking the average between the first and last stop so we get something to render crate::util::paint::avg_gradient(g) } usvg::Paint::Pattern(_) => Color::NONE, }; descriptors.alloc().init(PathDescriptor { abs_transform: path_with_transform.transform, segments: path_with_transform.convert().collect(), color, draw_type: DrawType::Fill, is_stroke: false, }); } fn process_stroke( descriptors: &mut Vec<PathDescriptor>, path_with_transform: PathWithTransform, ) { let mut path_with_transform = path_with_transform; let path = path_with_transform.path; let Some(stroke) = &path.stroke() else { return }; let (color, draw_type) = stroke.convert(); path_with_transform.is_stroke = true; descriptors.alloc().init(PathDescriptor { segments: path_with_transform.convert().collect(), abs_transform: path_with_transform.transform, color, draw_type, is_stroke: true, }); } } #[derive(Debug, Clone)] pub struct PathDescriptor { pub segments: Vec<PathEvent>, pub color: Color, pub draw_type: DrawType, pub abs_transform: usvg::Transform, pub is_stroke: bool, } #[derive(Debug, Clone)] pub enum DrawType { Fill, Stroke(lyon_tessellation::StrokeOptions), } #[derive(Debug, Copy, Clone)] struct PathWithTransform<'a> { path: &'a usvg::Path, is_stroke: bool, transform: usvg::Transform, } // Taken from https://github.com/nical/lyon/blob/74e6b137fea70d71d3b537babae22c6652f8843e/examples/wgpu_svg/src/main.rs pub struct PathConvIter<'iter> { iter: Peekable<PathSegmentsIter<'iter>>, prev: Point, first: Point, needs_end: bool, deferred: Option<PathEvent>, } impl<'iter> Iterator for PathConvIter<'iter> { type Item = PathEvent; fn next(&mut self) -> Option<Self::Item> { if let Some(deferred) = self.deferred { if let PathEvent::Begin { .. } = deferred { // if we have nothing left return early // don't send deferred as it won't be completed and cause panic on some svgs self.iter.peek()?; } self.needs_end = match deferred { PathEvent::Begin { .. } | PathEvent::Line { .. } | PathEvent::Quadratic { .. } | PathEvent::Cubic { .. } => true, PathEvent::End { .. } => false, }; return self.deferred.take(); } let next = self.iter.next(); match next { Some(PathSegment::MoveTo(point)) => { if self.needs_end { let last = self.prev; let first = self.first; self.needs_end = false; self.prev = point.convert(); self.deferred = Some(PathEvent::Begin { at: self.prev }); self.first = self.prev; Some(PathEvent::End { last, first, close: false, }) } else if self.iter.peek().is_some() { // only bother sending begin if we have more items to process self.first = point.convert(); self.needs_end = true; Some(PathEvent::Begin { at: self.first }) } else { None } } Some(PathSegment::LineTo(point)) => { self.needs_end = true; let from = self.prev; self.prev = point.convert(); Some(PathEvent::Line { from, to: self.prev, }) } Some(PathSegment::CubicTo(point1, point2, point3)) => { self.needs_end = true; let from = self.prev; self.prev = point3.convert(); Some(PathEvent::Cubic { from, ctrl1: point1.convert(), ctrl2: point2.convert(), to: self.prev, }) } Some(PathSegment::QuadTo(point1, point2)) => { self.needs_end = true; let from = self.prev; self.prev = point2.convert(); Some(PathEvent::Quadratic { from, ctrl: point1.convert(), to: self.prev, }) } Some(PathSegment::Close) => { self.needs_end = false; self.prev = self.first; Some(PathEvent::End { last: self.prev, first: self.first, close: true, }) } None => self.needs_end.then(|| { self.needs_end = false; let last = self.prev; let first = self.first; PathEvent::End { last, first, close: false, } }), } } } impl Convert<Point> for &usvg::tiny_skia_path::Point { #[inline] fn convert(self) -> Point { Point::new(self.x, self.y) } } impl Convert<Point> for usvg::tiny_skia_path::Point { #[inline] fn convert(self) -> Point { Point::new(self.x, self.y) } } impl Convert<Color> for &usvg::Stop { #[inline] fn convert(self) -> Color { let color = self.color(); Color::srgba_u8(color.red, color.green, color.blue, self.opacity().to_u8()) } } impl<'iter> Convert<PathConvIter<'iter>> for PathWithTransform<'iter> { fn convert(self) -> PathConvIter<'iter> { return PathConvIter { iter: self.path.data().segments().peekable(), first: Point::new(0.0, 0.0), prev: Point::new(0.0, 0.0), deferred: None, needs_end: false, }; } } impl Convert<(Color, DrawType)> for &usvg::Stroke { #[inline] fn convert(self) -> (Color, DrawType) { let color = match self.paint() { usvg::Paint::Color(c) => { Color::srgba_u8(c.red, c.green, c.blue, self.opacity().to_u8()) } // TODO: implement, take average for now usvg::Paint::LinearGradient(g) => util::paint::avg_gradient(g), usvg::Paint::RadialGradient(g) => util::paint::avg_gradient(g), usvg::Paint::Pattern(_) => Color::NONE, }; let linecap = match self.linecap() { usvg::LineCap::Butt => lyon_tessellation::LineCap::Butt, usvg::LineCap::Square => lyon_tessellation::LineCap::Square, usvg::LineCap::Round => lyon_tessellation::LineCap::Round, }; let linejoin = match self.linejoin() { usvg::LineJoin::Miter => lyon_tessellation::LineJoin::Miter, usvg::LineJoin::MiterClip => lyon_tessellation::LineJoin::MiterClip, usvg::LineJoin::Bevel => lyon_tessellation::LineJoin::Bevel, usvg::LineJoin::Round => lyon_tessellation::LineJoin::Round, }; let opt = lyon_tessellation::StrokeOptions::tolerance(0.01) .with_line_width(self.width().get()) .with_line_cap(linecap) .with_line_join(linejoin); (color, DrawType::Stroke(opt)) } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/resources.rs
src/resources.rs
use bevy::prelude::{Deref, DerefMut, Resource}; #[derive(Resource, Deref, DerefMut, Default)] pub struct FillTessellator(lyon_tessellation::FillTessellator); #[derive(Resource, Deref, DerefMut, Default)] pub struct StrokeTessellator(lyon_tessellation::StrokeTessellator);
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/util.rs
src/util.rs
pub mod paint { use bevy::color::{Color, ColorToComponents, Srgba}; use usvg::BaseGradient; use crate::Convert; trait ToF32Array { fn to_f32_array(&self) -> [f32; 4]; } impl ToF32Array for Option<&usvg::Stop> { fn to_f32_array(&self) -> [f32; 4] { self.map(Convert::convert) .unwrap_or(Color::NONE) .to_srgba() .to_f32_array() } } pub fn avg_gradient(gradient: &BaseGradient) -> Color { let first = gradient.stops().first().to_f32_array(); let last = gradient.stops().last().to_f32_array(); let avg = [ first[0] + last[0], first[1] + last[1], first[2] + last[2], first[3] + last[3], ] .map(|x| x / 2.0); Color::Srgba(Srgba::from_f32_array(avg)) } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/origin.rs
src/origin.rs
#[cfg(feature = "2d")] use bevy::mesh::Mesh2d; #[cfg(feature = "3d")] use bevy::mesh::Mesh3d; use bevy::{ asset::Assets, ecs::{ change_detection::{DetectChanges, Ref}, component::Component, entity::Entity, query::{Changed, Or, With, Without}, system::{Commands, Query, Res}, }, math::{Vec2, Vec3, Vec3Swizzles}, transform::components::{GlobalTransform, Transform}, }; #[cfg(feature = "2d")] use crate::render::Svg2d; #[cfg(feature = "3d")] use crate::render::Svg3d; use crate::svg::Svg; #[derive(Clone, Component, Copy, Debug, Default, PartialEq)] /// Origin of the coordinate system. pub enum Origin { /// Bottom left of the image or viewbox. BottomLeft, /// Bottom right of the image or viewbox. BottomRight, /// Center of the image or viewbox. Center, #[default] /// Top left of the image or viewbox, this is the default for a SVG. TopLeft, /// Top right of the image or viewbox. TopRight, /// Custom origin, top left is (0, 0), bottom right is (1, 1) Custom((f32, f32)), } impl Origin { /// Computes the translation for an origin. The resulting translation needs to be added /// to the translation of the SVG. pub fn compute_translation(&self, scaled_size: Vec2) -> Vec3 { match self { Origin::BottomLeft => Vec3::new(0.0, scaled_size.y, 0.0), Origin::BottomRight => Vec3::new(-scaled_size.x, scaled_size.y, 0.0), Origin::Center => Vec3::new(-scaled_size.x * 0.5, scaled_size.y * 0.5, 0.0), // Standard SVG origin is top left, so we don't need to do anything Origin::TopLeft => Vec3::ZERO, Origin::TopRight => Vec3::new(-scaled_size.x, 0.0, 0.0), Origin::Custom(coord) => { Vec3::new(-scaled_size.x * coord.0, scaled_size.y * coord.1, 0.0) } } } } #[derive(Clone, Component, Copy, Debug, PartialEq)] pub struct OriginState { previous: Origin, } #[cfg(feature = "2d")] #[cfg(not(feature = "3d"))] type WithSvg = With<Svg2d>; #[cfg(not(feature = "2d"))] #[cfg(feature = "3d")] type WithSvg = With<Svg3d>; #[cfg(all(feature = "2d", feature = "3d"))] type WithSvg = Or<(With<Svg2d>, With<Svg3d>)>; #[cfg(feature = "2d")] #[cfg(not(feature = "3d"))] type WithMesh = With<Mesh2d>; #[cfg(not(feature = "2d"))] #[cfg(feature = "3d")] type WithMesh = With<Mesh3d>; #[cfg(all(feature = "2d", feature = "3d"))] type WithMesh = Or<(With<Mesh2d>, With<Mesh3d>)>; /// Checkes if a "new" SVG bundle was added by looking for a missing `OriginState` /// and then adds it to the entity. pub fn add_origin_state( mut commands: Commands, query: Query<Entity, (WithSvg, WithMesh, Without<OriginState>)>, ) { for entity in &query { commands.entity(entity).insert(OriginState { previous: Origin::default(), }); } } #[cfg(feature = "2d")] #[cfg(not(feature = "3d"))] type ChangedMesh = Changed<Mesh2d>; #[cfg(not(feature = "2d"))] #[cfg(feature = "3d")] type ChangedMesh = Changed<Mesh3d>; #[cfg(all(feature = "2d", feature = "3d"))] type ChangedMesh = Or<(Changed<Mesh2d>, Changed<Mesh3d>)>; /// Gets all SVGs with a changed origin or transform and checks if the origin offset /// needs to be applied. pub fn apply_origin( svgs: Res<Assets<Svg>>, mut query: Query< ( Entity, Option<&Svg2d>, Option<&Svg3d>, &Origin, &mut OriginState, Ref<Transform>, &mut GlobalTransform, ), Or<(Changed<Origin>, Changed<Transform>, ChangedMesh)>, >, ) { for ( _, svg2d_handle, svg3d_handle, origin, mut origin_state, transform, mut global_transform, ) in &mut query { let Some(svg_handle) = svg2d_handle.map_or_else(|| svg3d_handle.map(|x| &x.0), |x| Some(&x.0)) else { continue; }; if let Some(svg) = svgs.get(svg_handle) { if origin_state.previous != *origin { let scaled_size = svg.size * transform.scale.xy(); let reverse_origin_translation = origin_state.previous.compute_translation(scaled_size); let origin_translation = origin.compute_translation(scaled_size); let mut gtransf = global_transform.compute_transform(); gtransf.translation.x += origin_translation.x - reverse_origin_translation.x; gtransf.translation.y += origin_translation.y - reverse_origin_translation.y; gtransf.translation.z += origin_translation.z - reverse_origin_translation.z; *global_transform = GlobalTransform::from(gtransf); origin_state.previous = *origin; } else if transform.is_changed() { let scaled_size = svg.size * transform.scale.xy(); let origin_translation = origin.compute_translation(scaled_size); let mut gtransf = global_transform.compute_transform(); gtransf.translation.x += origin_translation.x; gtransf.translation.y += origin_translation.y; gtransf.translation.z += origin_translation.z; *global_transform = GlobalTransform::from(gtransf); } } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/loader.rs
src/loader.rs
use bevy::{ asset::{AssetLoader, LoadContext, io::Reader}, log::debug, tasks::ConditionalSendFuture, }; use thiserror::Error; use crate::svg::Svg; #[derive(Default)] pub struct SvgAssetLoader; impl AssetLoader for SvgAssetLoader { type Asset = Svg; type Settings = (); type Error = FileSvgError; fn load( &self, reader: &mut dyn Reader, _settings: &(), load_context: &mut LoadContext<'_>, ) -> impl ConditionalSendFuture<Output = Result<Self::Asset, Self::Error>> { Box::pin(async move { debug!("Parsing SVG: {} ...", load_context.path().display()); let mut bytes = Vec::new(); reader .read_to_end(&mut bytes) .await .map_err(|e| FileSvgError { error: e.into(), path: load_context.path().display().to_string(), })?; let mut svg = Svg::from_bytes(&bytes, load_context.path(), None::<&std::path::Path>)?; let name = &load_context .path() .file_name() .ok_or_else(|| FileSvgError { error: SvgError::InvalidFileName(load_context.path().display().to_string()), path: load_context.path().display().to_string(), })? .to_string_lossy(); svg.name = name.to_string(); debug!("Parsing SVG: {} ... Done", load_context.path().display()); debug!("Tessellating SVG: {} ...", load_context.path().display()); let mesh = svg.tessellate(); debug!( "Tessellating SVG: {} ... Done", load_context.path().display() ); let mesh_handle = load_context.add_labeled_asset("mesh".to_string(), mesh); svg.mesh = mesh_handle; Ok(svg) }) } fn extensions(&self) -> &[&str] { &["svg", "svgz"] } } /// An error that occurs when loading a texture #[derive(Error, Debug)] pub enum SvgError { #[error("invalid file name")] InvalidFileName(String), #[error("could not read file: {0}")] IoError(#[from] std::io::Error), #[error("failed to load an SVG: {0}")] SvgError(#[from] usvg::Error), } /// An error that occurs when loading a texture from a file. #[derive(Error, Debug)] pub struct FileSvgError { pub(crate) error: SvgError, pub(crate) path: String, } impl std::fmt::Display for FileSvgError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!( f, "Error reading SVG file {}: {}, this is an error in `bevy_svg`.", self.path, self.error ) } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/plugin.rs
src/plugin.rs
//! Contains the plugin and its helper types. //! //! The [`Svg2dBundle`](crate::bundle::Svg2dBundle) provides a way to display an `SVG`-file //! with minimal boilerplate. //! //! ## How it works //! The user creates/loades a [`Svg2dBundle`](crate::bundle::Svg2dBundle) in a system. //! //! Then, in the [`Set::SVG`](Set::SVG), a mesh is created for each loaded [`Svg`] bundle. //! Each mesh is then extracted in the [`RenderSet::Extract`](bevy::render::RenderSet) and added to the //! [`RenderWorld`](bevy::render::RenderWorld). //! Afterwards it is queued in the [`RenderSet::Queue`](bevy::render::RenderSet) for actual drawing/rendering. use bevy::{ app::{App, Plugin}, asset::{AssetEvent, Assets}, ecs::{ entity::Entity, message::MessageReader, query::{Added, Changed, Or}, schedule::{IntoScheduleConfigs, SystemSet}, system::{Commands, Query, Res, ResMut}, }, log::debug, mesh::Mesh, prelude::{Last, PostUpdate}, }; #[cfg(feature = "2d")] use bevy::mesh::Mesh2d; #[cfg(feature = "3d")] use bevy::mesh::Mesh3d; use crate::{ origin, render::{self, Svg2d, Svg3d}, svg::Svg, }; /// Set in which [`Svg`](crate::prelude::Svg2d)s get drawn. #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub struct SvgSet; /// A plugin that makes sure your [`Svg`]s get rendered pub struct SvgRenderPlugin; impl Plugin for SvgRenderPlugin { fn build(&self, app: &mut App) { app.add_systems(PostUpdate, origin::add_origin_state.in_set(SvgSet)) .add_systems(Last, (origin::apply_origin, svg_mesh_linker.in_set(SvgSet))) .add_plugins(render::SvgPlugin); } } #[cfg(feature = "2d")] #[cfg(not(feature = "3d"))] type SvgMeshComponents = ( Entity, &'static Handle<Svg>, Option<&'static mut Mesh2dHandle>, Option<()>, ); #[cfg(not(feature = "2d"))] #[cfg(feature = "3d")] type SvgMeshComponents = ( Entity, &'static Handle<Svg>, Option<()>, Option<&'static mut Handle<Mesh>>, ); #[cfg(all(feature = "2d", feature = "3d"))] type SvgMeshComponents = ( Entity, Option<&'static Svg2d>, Option<&'static Svg3d>, Option<&'static mut Mesh2d>, Option<&'static mut Mesh3d>, ); /// Bevy system which queries for all [`Svg`] bundles and adds the correct [`Mesh`] to them. fn svg_mesh_linker( mut commands: Commands, mut svg_events: MessageReader<AssetEvent<Svg>>, mut meshes: ResMut<Assets<Mesh>>, svgs: Res<Assets<Svg>>, mut query: Query<SvgMeshComponents>, changed_handles: Query< Entity, Or<(Changed<Svg2d>, Changed<Svg3d>, Added<Svg2d>, Added<Svg3d>)>, >, ) { for event in svg_events.read() { match event { AssetEvent::Added { .. } => (), AssetEvent::LoadedWithDependencies { id } => { for (.., mesh_2d, mesh_3d) in query.iter_mut().filter(|(_, svg_2d, svg_3d, ..)| { svg_2d .map(|x| x.0.id() == *id) .or_else(|| svg_3d.map(|x| x.0.id() == *id)) .unwrap_or(false) }) { let svg = svgs.get(*id).unwrap(); debug!( "Svg `{}` created. Adding mesh component to entity.", svg.name ); #[cfg(feature = "2d")] if let Some(mut mesh) = mesh_2d { mesh.0 = svg.mesh.clone(); } #[cfg(feature = "3d")] if let Some(mut mesh) = mesh_3d { mesh.0 = svg.mesh.clone(); } } } AssetEvent::Modified { id } => { for (.., mesh_2d, mesh_3d) in query.iter_mut().filter(|(_, svg_2d, svg_3d, ..)| { svg_2d .map(|x| x.0.id() == *id) .or_else(|| svg_3d.map(|x| x.0.id() == *id)) .unwrap_or(false) }) { let svg = svgs.get(*id).unwrap(); debug!( "Svg `{}` modified. Changing mesh component of entity.", svg.name ); #[cfg(feature = "2d")] if let Some(mut mesh) = mesh_2d.filter(|mesh| mesh.0 != svg.mesh) { let old_mesh = mesh.0.clone(); mesh.0 = svg.mesh.clone(); meshes.remove(&old_mesh); } #[cfg(feature = "3d")] if let Some(mut mesh) = mesh_3d.filter(|mesh| mesh.0 != svg.mesh) { let old_mesh = mesh.clone(); mesh.0 = svg.mesh.clone(); meshes.remove(&old_mesh); } } } AssetEvent::Removed { id } => { for (entity, ..) in query.iter_mut().filter(|(_, svg_2d, svg_3d, ..)| { svg_2d .map(|x| x.0.id() == *id) .or_else(|| svg_3d.map(|x| x.0.id() == *id)) .unwrap_or(false) }) { commands.entity(entity).despawn(); } } AssetEvent::Unused { .. } => { // TODO: does anything need done here? } } } // Ensure all correct meshes are set for entities which have had modified handles for entity in changed_handles.iter() { let Ok((.., svg_2d, svg_3d, mesh_2d, mesh_3d)) = query.get_mut(entity) else { continue; }; let Some(handle) = svg_2d.map_or_else(|| svg_3d.map(|x| &x.0), |x| Some(&x.0)) else { continue; }; let Some(svg) = svgs.get(handle) else { continue; }; debug!( "Svg handle for entity `{:?}` modified. Changing mesh component of entity.", entity ); #[cfg(feature = "2d")] if let Some(mut mesh) = mesh_2d { mesh.0 = svg.mesh.clone(); } #[cfg(feature = "3d")] if let Some(mut mesh) = mesh_3d { mesh.0 = svg.mesh.clone(); } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/vertex_buffer.rs
src/render/vertex_buffer.rs
use bevy::{ asset::RenderAssetUsages, color::{Color, ColorToComponents}, mesh::{Indices, Mesh, VertexAttributeValues}, render::render_resource::PrimitiveTopology, }; use copyless::VecHelper; use lyon_path::math::Point; use lyon_tessellation::{ self, FillVertex, FillVertexConstructor, StrokeVertex, StrokeVertexConstructor, }; use crate::Convert; /// A vertex with all the necessary attributes to be inserted into a Bevy /// [`Mesh`](bevy::render::mesh::Mesh). #[derive(Debug, Clone, Copy, PartialEq)] pub struct Vertex { position: [f32; 3], color: [f32; 4], } /// The index type of a Bevy [`Mesh`](bevy::render::mesh::Mesh). pub type IndexType = u32; /// Lyon's [`VertexBuffers`] generic data type defined for [`Vertex`]. pub type VertexBuffers = lyon_tessellation::VertexBuffers<Vertex, IndexType>; #[allow(clippy::single_call_fn)] fn flip_mesh_vertically(mesh: &mut Mesh) { if let Some(VertexAttributeValues::Float32x3(positions)) = mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) { for position in positions.iter_mut() { // Invert the y-coordinate to flip the mesh vertically position[1] = -position[1]; } } } impl Convert<Mesh> for VertexBuffers { fn convert(self) -> Mesh { let mut positions = Vec::with_capacity(self.vertices.len()); let mut colors = Vec::with_capacity(self.vertices.len()); for vert in self.vertices { positions.alloc().init(vert.position); colors.alloc().init(vert.color); } let mut mesh = Mesh::new( PrimitiveTopology::TriangleList, RenderAssetUsages::default(), ); mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions); mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, colors); mesh.insert_indices(Indices::U32(self.indices)); // Bevy has a different y-axis origin, so we need to flip that axis flip_mesh_vertically(&mut mesh); mesh } } /// Zero-sized type used to implement various vertex construction traits from Lyon. pub struct VertexConstructor { pub(crate) color: Color, pub(crate) transform: usvg::Transform, } impl VertexConstructor { fn process_vertex(&self, point: Point) -> Vertex { let pos = { let mut point = usvg::tiny_skia_path::Point::from_xy(point.x, point.y); self.transform.map_point(&mut point); Point::new(point.x, point.y) }; Vertex { position: [pos.x, pos.y, 0.0], color: self.color.to_linear().to_f32_array(), } } } /// Enables the construction of a [`Vertex`] when using a `FillTessellator`. impl FillVertexConstructor<Vertex> for VertexConstructor { fn new_vertex(&mut self, vertex: FillVertex) -> Vertex { self.process_vertex(vertex.position()) } } /// Enables the construction of a [`Vertex`] when using a `StrokeTessellator`. impl StrokeVertexConstructor<Vertex> for VertexConstructor { fn new_vertex(&mut self, vertex: StrokeVertex) -> Vertex { self.process_vertex(vertex.position()) } } pub trait BufferExt<A> { fn extend_one(&mut self, item: A); #[allow(dead_code)] fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T); } impl BufferExt<VertexBuffers> for VertexBuffers { fn extend_one(&mut self, item: VertexBuffers) { let offset = self.vertices.len() as u32; for vert in item.vertices { self.vertices.alloc().init(vert); } for idx in item.indices { self.indices.alloc().init(idx + offset); } } fn extend<T: IntoIterator<Item = VertexBuffers>>(&mut self, iter: T) { let mut offset = self.vertices.len() as u32; for buf in iter { let num_verts = buf.vertices.len() as u32; for vert in buf.vertices { self.vertices.alloc().init(vert); } for idx in buf.indices { self.indices.alloc().init(idx + offset); } offset += num_verts; } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/mod.rs
src/render/mod.rs
mod plugin; pub mod tessellation; mod vertex_buffer; #[cfg(feature = "2d")] mod svg2d; #[cfg(feature = "3d")] mod svg3d; #[cfg(feature = "2d")] pub use svg2d::Svg2d; #[cfg(feature = "3d")] pub use svg3d::Svg3d; pub use plugin::SvgPlugin;
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/tessellation.rs
src/render/tessellation.rs
use bevy::log::{debug, error}; use lyon_tessellation::{BuffersBuilder, FillOptions, FillTessellator, StrokeTessellator}; use crate::{ render::vertex_buffer::{BufferExt, VertexBuffers, VertexConstructor}, svg::{DrawType, Svg}, }; pub fn generate_buffer( svg: &Svg, fill_tess: &mut FillTessellator, stroke_tess: &mut StrokeTessellator, ) -> VertexBuffers { debug!("Tessellating SVG: {}", svg.name); let mut buffers = VertexBuffers::new(); let mut color = None; for path in &svg.paths { let mut buffer = VertexBuffers::new(); if color.is_none() { color = Some(path.color); } let segments = path.segments.clone(); match path.draw_type { DrawType::Fill => { if let Err(e) = fill_tess.tessellate( segments, &FillOptions::tolerance(0.001), &mut BuffersBuilder::new( &mut buffer, VertexConstructor { color: path.color, transform: path.abs_transform, }, ), ) { error!("FillTessellator error: {:?}", e); } } DrawType::Stroke(opts) => { if let Err(e) = stroke_tess.tessellate( segments, &opts, &mut BuffersBuilder::new( &mut buffer, VertexConstructor { color: path.color, transform: path.abs_transform, }, ), ) { error!("StrokeTessellator error: {:?}", e); } } } buffers.extend_one(buffer); } debug!("Tessellating SVG: {} ... Done", svg.name); buffers }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/plugin.rs
src/render/plugin.rs
use crate::resources::{FillTessellator, StrokeTessellator}; use bevy::app::{App, Plugin}; #[cfg(feature = "2d")] use crate::render::svg2d; #[cfg(feature = "3d")] use crate::render::svg3d; /// Plugin that renders [`Svg`](crate::svg::Svg)s in 2D pub struct SvgPlugin; impl Plugin for SvgPlugin { fn build(&self, app: &mut App) { let fill_tess = FillTessellator::default(); let stroke_tess = StrokeTessellator::default(); app.insert_resource(fill_tess).insert_resource(stroke_tess); #[cfg(feature = "2d")] app.add_plugins(svg2d::RenderPlugin); #[cfg(feature = "3d")] app.add_plugins(svg3d::RenderPlugin); } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/svg3d/mod.rs
src/render/svg3d/mod.rs
use bevy::{ asset::{Handle, uuid_handle}, ecs::{component::Component, lifecycle::HookContext, world::DeferredWorld}, mesh::Mesh3d, pbr::MeshMaterial3d, shader::Shader, }; mod plugin; /// Handle to the custom shader with a unique random ID pub const SVG_3D_SHADER_HANDLE: Handle<Shader> = uuid_handle!("00000000-0000-0000-762a-bdb74c2a5c66"); pub use plugin::RenderPlugin; use crate::{origin::Origin, svg::Svg}; /// A component for 3D SVGs. #[derive(Component, Default)] #[require(Mesh3d, Origin, MeshMaterial3d<Svg>)] #[component(on_insert = svg_3d_on_insert)] pub struct Svg3d(pub Handle<Svg>); fn svg_3d_on_insert(mut world: DeferredWorld, ctx: HookContext) { let component = world.entity(ctx.entity).get_components::<&Svg3d>().unwrap(); let handle = component.0.clone(); let entity = world.entity(ctx.entity).id(); let mut commands = world.commands(); commands.entity(entity).insert(MeshMaterial3d(handle)); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/svg3d/plugin.rs
src/render/svg3d/plugin.rs
use super::SVG_3D_SHADER_HANDLE; use crate::svg::Svg; use bevy::{ app::{App, Plugin}, asset::{AssetApp, load_internal_asset}, mesh::MeshVertexBufferLayoutRef, pbr::{Material, MaterialPipeline, MaterialPipelineKey, MaterialPlugin}, render::render_resource::{RenderPipelineDescriptor, SpecializedMeshPipelineError}, shader::{Shader, ShaderRef}, }; /// Plugin that renders [`Svg`](crate::svg::Svg)s in 2D pub struct RenderPlugin; impl Plugin for RenderPlugin { fn build(&self, app: &mut App) { load_internal_asset!(app, SVG_3D_SHADER_HANDLE, "svg_3d.wgsl", Shader::from_wgsl); app.add_plugins(MaterialPlugin::<Svg>::default()) .register_asset_reflect::<Svg>(); } } impl Material for Svg { fn fragment_shader() -> ShaderRef { SVG_3D_SHADER_HANDLE.into() } fn specialize( _pipeline: &MaterialPipeline, descriptor: &mut RenderPipelineDescriptor, _layout: &MeshVertexBufferLayoutRef, _key: MaterialPipelineKey<Self>, ) -> bevy::prelude::Result<(), SpecializedMeshPipelineError> { descriptor.primitive.cull_mode = None; Ok(()) } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/svg2d/mod.rs
src/render/svg2d/mod.rs
use crate::{origin::Origin, svg::Svg}; use bevy::{ asset::{Handle, uuid_handle}, ecs::{component::Component, lifecycle::HookContext, world::DeferredWorld}, mesh::Mesh2d, shader::Shader, sprite_render::MeshMaterial2d, }; mod plugin; /// Handle to the custom shader with a unique random ID pub const SVG_2D_SHADER_HANDLE: Handle<Shader> = uuid_handle!("00000000-0000-0000-762a-bdb29826d266"); pub use plugin::RenderPlugin; /// A component for 2D SVGs. #[derive(Component, Default)] #[require(Mesh2d, Origin)] #[component(on_insert = svg_2d_on_insert)] pub struct Svg2d(pub Handle<Svg>); fn svg_2d_on_insert(mut world: DeferredWorld, ctx: HookContext) { let component = world.entity(ctx.entity).get_components::<&Svg2d>().unwrap(); let handle = component.0.clone(); let entity = world.entity(ctx.entity).id(); let mut commands = world.commands(); commands.entity(entity).insert(MeshMaterial2d(handle)); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/src/render/svg2d/plugin.rs
src/render/svg2d/plugin.rs
use crate::{render::svg2d::SVG_2D_SHADER_HANDLE, svg::Svg}; use bevy::{ app::{App, Plugin}, asset::{AssetApp, load_internal_asset}, shader::{Shader, ShaderRef}, sprite_render::{Material2d, Material2dPlugin}, }; /// Plugin that renders [`Svg`](crate::svg::Svg)s in 2D pub struct RenderPlugin; impl Plugin for RenderPlugin { fn build(&self, app: &mut App) { load_internal_asset!(app, SVG_2D_SHADER_HANDLE, "svg_2d.wgsl", Shader::from_wgsl); app.add_plugins(Material2dPlugin::<Svg>::default()) .register_asset_reflect::<Svg>(); } } impl Material2d for Svg { fn fragment_shader() -> ShaderRef { SVG_2D_SHADER_HANDLE.into() } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/origin_check.rs
examples/3d/origin_check.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "origin_check".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("box.svg"); commands.spawn(Camera3d::default()); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -600.0), ..Default::default() }, )); commands.spawn(( Svg3d(svg.clone()), Origin::TopLeft, Transform { translation: Vec3::new(0.0, 0.0, -600.0), ..Default::default() }, common::DontChange, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/complex_one_color.rs
examples/3d/complex_one_color.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "3d_complex_one_color".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("asteroid_field.svg"); commands.spawn(Camera3d::default()); commands.spawn(( Svg3d(svg), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -600.0), scale: Vec3::new(2.0, 2.0, 1.0), ..Default::default() }, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/two_colors.rs
examples/3d/two_colors.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "3d_two_colors".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("neutron_star.svg"); commands.spawn(Camera3d::default()); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -600.0), ..Default::default() }, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/multiple_translation.rs
examples/3d/multiple_translation.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "3d_multiple_translation".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .add_systems(Update, svg_movement) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("asteroid_field.svg"); commands.spawn(Camera3d::default()); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(100.0, 0.0, -600.0), scale: Vec3::new(2.0, 2.0, 1.0), ..Default::default() }, Direction::Up, )); let svg = asset_server.load("neutron_star.svg"); commands.spawn(( Svg3d(svg.clone()), Transform { translation: Vec3::new(0.0, 0.0, -600.0), ..Default::default() }, Direction::Up, )); } #[derive(Component)] enum Direction { Up, Down, } fn svg_movement( time: Res<Time>, mut svg_position: Query<(&mut Direction, &mut Transform), With<Svg3d>>, ) { for (mut direction, mut transform) in &mut svg_position { match *direction { Direction::Up => transform.translation.y += 150.0 * time.delta_secs(), Direction::Down => transform.translation.y -= 150.0 * time.delta_secs(), } if transform.translation.y > 200.0 { *direction = Direction::Down; } else if transform.translation.y < -200.0 { *direction = Direction::Up; } } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/multiple_perspective.rs
examples/3d/multiple_perspective.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "3d_multiple_perspective".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("neutron_star.svg"); commands.spawn(( Camera3d::default(), Transform::from_xyz(100.0, 175.0, 0.0).looking_at(Vec3::new(0.0, 0.0, -600.0), Vec3::Y), )); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -600.0), rotation: Quat::from_rotation_x(-std::f32::consts::PI * 3.0), ..Default::default() }, )); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -700.0), rotation: Quat::from_rotation_x(-std::f32::consts::PI * 3.0), ..Default::default() }, )); commands.spawn(( Svg3d(svg), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -800.0), rotation: Quat::from_rotation_x(-std::f32::consts::PI * 3.0), ..Default::default() }, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/3d/twinkle.rs
examples/3d/twinkle.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "3d_twinkle".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("twinkle.svg"); commands.spawn(( Camera3d::default(), Transform::from_xyz(5.0, 8.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y), )); commands.spawn(( Svg3d(svg.clone()), Origin::Center, Transform { translation: Vec3::new(0.0, 0.0, -1.0), scale: Vec3::new(0.01, 0.01, 1.0), rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0), }, )); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/origin_check.rs
examples/2d/origin_check.rs
use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "origin_check".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .run(); } fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { let svg = asset_server.load("box.svg"); commands.spawn(Camera2d); commands.spawn((Svg2d(svg.clone()), Origin::Center)); commands.spawn((Svg2d(svg), Origin::TopLeft, common::DontChange)); }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false
Weasy666/bevy_svg
https://github.com/Weasy666/bevy_svg/blob/c0ede2b5481bf65ede166c6dc39e6a376bf05010/examples/2d/preloading.rs
examples/2d/preloading.rs
use bevy::asset::LoadState; use bevy::prelude::*; use bevy_svg::prelude::*; #[path = "../common/lib.rs"] mod common; fn main() { App::new() .add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(Window { title: "preloading".to_string(), resolution: (600, 600).into(), ..Default::default() }), ..Default::default() })) .add_plugins((common::CommonPlugin, bevy_svg::prelude::SvgPlugin)) .add_systems(Startup, setup) .add_systems(Update, run) .run(); } fn setup(mut commands: Commands) { commands.spawn(Camera2d); } #[derive(Default, Eq, PartialEq)] enum TutorialFsm { #[default] Ready, StartedLoad(Handle<Svg>), Wait(Handle<Svg>, u8), Loaded, } fn run(mut commands: Commands, asset_server: Res<AssetServer>, mut fsm: Local<TutorialFsm>) { match &*fsm { TutorialFsm::Ready => { let handle = asset_server.load("neutron_star.svg"); *fsm = TutorialFsm::StartedLoad(handle); } TutorialFsm::StartedLoad(handle) => { if let Some(LoadState::Loaded) = asset_server.get_load_state(handle) { *fsm = TutorialFsm::Wait(handle.clone(), 60); } } TutorialFsm::Wait(handle, frames) => { if *frames > 0 { *fsm = TutorialFsm::Wait(handle.clone(), *frames - 1); } else if let Some(svg) = asset_server.get_handle("neutron_star.svg") { commands.spawn((Svg2d(svg), Origin::Center)); *fsm = TutorialFsm::Loaded; dbg!("We loaded"); } } TutorialFsm::Loaded => {} } }
rust
Apache-2.0
c0ede2b5481bf65ede166c6dc39e6a376bf05010
2026-01-04T20:23:13.998577Z
false