use std::alloc::{GlobalAlloc, Layout, System}; use std::sync::atomic::{AtomicUsize, Ordering}; static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0); struct CountAllocations; unsafe impl GlobalAlloc for CountAllocations { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ALLOCATIONS.fetch_add(1, Ordering::Relaxed); unsafe { System.alloc(layout) } } unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { unsafe { System.dealloc(pointer, layout) } } unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 { ALLOCATIONS.fetch_add(1, Ordering::Relaxed); unsafe { System.realloc(pointer, layout, size) } } } #[global_allocator] static ALLOCATOR: CountAllocations = CountAllocations; let before_constant = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(std::hint::black_box(@constantSize@()), 3); assert_eq!(ALLOCATIONS.load(Ordering::Relaxed) - before_constant, 0); assert_eq!(@size@("你好🌍"), 3); assert_eq!(@flowNested@(Some("你好".to_owned())).unwrap(), "你好!"); assert!(matches!(@flowNested@(None), Err(Failure::Api(ApiError::Invalid)))); assert_eq!(@flowChecked@(2).unwrap(), 3); assert!(matches!(@flowChecked@(0), Err(Failure::@Problem@(_)))); let doubled = @twice@(String::from("two")); assert_eq!((doubled.f0, doubled.f1), ("two".into(), "two".into())); let item = @Item@ { f0: "item".into(), f1: 2 }; assert_eq!(@count@(&item), 2); assert_eq!(@nameSize@(&item), 4); let pair = @unchanged@(item); assert_eq!(pair.f0.f1, 3); assert_eq!(pair.f1.f1, 2); assert_eq!(@name@(pair.f1), "item"); assert_eq!(@requireText@(Some("ok".into())).unwrap(), "ok"); assert!(matches!(@requireText@(None), Err(Failure::Api(ApiError::Invalid)))); assert_eq!(@nullableSize@(Some("你好")).unwrap(), 2); assert_eq!(@freshSize@().unwrap(), 2); assert_eq!(@add@(3, 4), 7); assert_eq!(@divide@(Decimal::from_int(1), Decimal::from_int(4)).to_string(), "0.25"); assert_eq!(@fraction@().to_string(), "0.3333333333333333333333333333333333"); assert_eq!(@join@("first".into(), "second"), "firstsecond"); let values = @addItem@(vec!["a".into()], "b".into()); assert_eq!(@getItem@(&values, 1), Some("b".into())); assert_eq!(@getItem@(&values, -1), None); assert_eq!(@lookup@(&@map@(), "second"), Some(2)); assert_eq!(@capture@(2), @Reply@::Ready(2)); assert_eq!(@capture@(0), @Reply@::Failed(@Problem@::Missing("small".into()))); assert!(matches!(@parameterFailure@(), Err(Failure::@Problem@(@Problem@::Missing(message))) if message == "missing")); assert_eq!(@choose@(true, "chosen".into()), "chosen"); assert_eq!(@choose@(false, "other".into()), "other"); let split = @split@(@Pair@::Both("a".into(), "b".into())); assert_eq!((split.f0, split.f1), ("a".into(), "b".into())); let kept = @keep@(@Pair@::Both("a".into(), "b".into())); assert_eq!(kept.f0, "a"); assert_eq!(kept.f1, @Pair@::Both("a".into(), "b".into())); let mixed = @mixed@(@Pair@::Both("a".into(), "你好".into())); assert_eq!((mixed.f0, mixed.f1), ("a".into(), 2)); assert_eq!(@payload@(&@Choice@::Small(2)), 2); assert_eq!(@payload@(&@Choice@::Large(5)), 5); assert_eq!(@absolute@(-2), 2); assert_eq!(@absolute@(0), 0); assert_eq!(@nullable@(None), "absent"); assert_eq!(@nullable@(Some("text".into())), "text"); assert_eq!(@nullablePayload@(Some(@Pair@::Both("a".into(), "b".into()))), "a"); assert_eq!(@read@(Some(@Reply@::Ready(8))).unwrap(), 8); assert_eq!(@read@(None).unwrap(), 0); assert!(matches!(@read@(Some(@Reply@::Failed(@Problem@::Missing("bad".into())))), Err(Failure::@Reply@(_)))); let fault = std::panic::catch_unwind(|| @add@(i64::MAX, 1)).unwrap_err(); let info = fault.downcast_ref::<&'static FaultInfo>().unwrap(); assert_eq!(info.source, @source_path@); assert!(info.line > 0 && info.column > 0); assert_eq!(@add@(1, 2), 3); for (operation, left, right) in [ (@subtract@ as fn(i64, i64) -> i64, i64::MIN, 1), (@multiply@, i64::MAX, 2), (@quotient@, 1, 0), (@quotient@, i64::MIN, -1), (@remainder@, 1, 0), (@remainder@, i64::MIN, -1), ] { let error = std::panic::catch_unwind(|| operation(left, right)).unwrap_err(); let info = error.downcast_ref::<&'static FaultInfo>().unwrap(); assert_eq!(info.source, @source_path@); assert_eq!(info.message, "arithmetic fault"); assert!(info.line > 0 && info.column > 0); } let error = std::panic::catch_unwind(|| @negate@(i64::MIN)).unwrap_err(); assert_eq!(error.downcast_ref::<&'static FaultInfo>().unwrap().message, "integer overflow"); let error = std::panic::catch_unwind(|| @divide@(Decimal::from_int(1), Decimal::ZERO)).unwrap_err(); assert_eq!(error.downcast_ref::<&'static FaultInfo>().unwrap().message, "arithmetic fault"); assert_eq!(@subtract@(9, 2), 7); assert_eq!(@multiply@(3, 4), 12); assert_eq!(@quotient@(-9, 2), -4); assert_eq!(@remainder@(-9, 2), -1); assert_eq!(@negate@(2), -2); assert!(@requireOnly@(Some("ok")).is_ok()); assert!(@requireOnly@(None).is_err()); let nullable = vec![Some("first".into()), None]; assert_eq!(@getNullable@(&nullable, 0), Some("first".into())); assert_eq!(@getNullable@(&nullable, 1), None); assert_eq!(@getNullable@(&nullable, 2), None); assert_eq!(@getNullableInt@(&[None, Some(4)], 1), Some(4)); assert_eq!(@getNullableInt@(&[None, Some(4)], 0), None); let mut map = Map::with_capacity(2); assert!(map.insert_unique("first".into(), Some("one".into()))); assert!(map.insert_unique("second".into(), None)); assert_eq!(@lookupNullable@(&map, "first"), Some("one".into())); assert_eq!(@lookupNullable@(&map, "second"), None); assert_eq!(@lookupNullable@(&map, "absent"), None); assert_eq!(@temporaryGet@().unwrap(), 9); assert_eq!(@borrowNullable@(&nullable).unwrap(), 5); assert_eq!(@borrowPayload@(Some(&@Pair@::Both("你好".into(), "b".into()))), 2); assert_eq!(@dynamicMap@("a".into(), "b".into()).len(), 2); let duplicate = std::panic::catch_unwind(|| @dynamicMap@("a".into(), "a".into())).unwrap_err(); assert_eq!(duplicate.downcast_ref::<&'static FaultInfo>().unwrap().message, "duplicate Map key"); let alias = @aliasAfterMove@("你好".into()); assert_eq!((alias.f0, alias.f1), ("你好".into(), 2)); let whole = @payloadAfterMove@(@Pair@::Both("你好".into(), "b".into())); assert_eq!(whole.f0, @Pair@::Both("你好".into(), "b".into())); assert_eq!(whole.f1, 2); let field = @fieldAliasAfterMove@(@Item@ { f0: "你好".into(), f1: 9 }); assert_eq!((field.f0.f0, field.f1), ("你好".into(), 2)); let nullable = @nonnullAliasAfterMove@(Some("你好".into())).unwrap(); assert_eq!((nullable.f0, nullable.f1), (Some("你好".into()), 2)); assert!(@nonnullAliasAfterMove@(None).is_err()); let before = @aliasBeforeMove@("你好".into()); assert_eq!((before.f0, before.f1), ("你好".into(), 2)); let empty = @nullEquality@(); assert!(empty.f0); assert!(!empty.f1); assert!(@containsText@(&["你好".into(), "world".into()], "你好")); assert!(!@containsText@(&[], "你好")); assert!(!@containsText@(&["你好".into()], "你")); assert!(@containsNullable@(&[None, Some("你好".into())], None)); assert!(@containsNullable@(&[None, Some("你好".into())], Some("你好"))); assert!(@containsRecord@(&[@Item@ { f0: "你好".into(), f1: 1 }], &@Item@ { f0: "你好".into(), f1: 1 })); assert!(@containsNested@(&[vec![1, 2], vec![3]], &[1, 2])); assert_eq!(@lookupSize@(&["你好".into()], 0).unwrap(), 2); assert!(@lookupSize@(&[], 0).is_err()); assert!(@lookupSize@(&["name".into()], -1).is_err()); let before = @lookupBeforeMove@(vec!["你好".into()]).unwrap(); let after = @lookupAfterMove@(vec!["你好".into()]).unwrap(); assert_eq!(before.f0, vec!["你好", "tail"]); assert_eq!(after.f0, before.f0); assert_eq!(after.f1, 2); let mut values = Map::with_capacity(2); values.put("present".to_owned(), Some("你好".to_owned())); values.put("empty".to_owned(), None); assert_eq!(@lookupMapSize@(&values, "present").unwrap(), 2); assert!(@lookupMapSize@(&values, "empty").is_err()); assert!(@lookupMapSize@(&values, "missing").is_err()); let mut map = Map::with_capacity(3); map.put("first".to_owned(), "one".to_owned()); map.put("middle".to_owned(), "two".to_owned()); map.put("last".to_owned(), "three".to_owned()); let kept = @keepMap@(map.clone()); assert_eq!(kept.f1, map); let mut expected = map.clone(); expected.put("first".to_owned(), "changed".to_owned()); assert_eq!(kept.f0, expected); assert_eq!(@putMap@(map.clone(), "first".into(), "changed".into()), expected); let mut deleted = Map::with_capacity(2); deleted.put("first".to_owned(), "one".to_owned()); deleted.put("last".to_owned(), "three".to_owned()); assert_eq!(@removeMap@(map.clone(), "middle"), deleted); assert_eq!(@removeMap@(map.clone(), "absent"), map); let mut numeric = Map::with_capacity(1); numeric.put(3i64, "three".to_owned()); assert!(@removeIntKey@(numeric, 3).is_empty()); // 实际生成程序和直接 Rust 都只读借用;统计只覆盖操作,不包含输入准备。 let probe = vec!["你好🌍".repeat(1024), "other".to_owned()]; let before = ALLOCATIONS.load(Ordering::Relaxed); let size = @lookupSize@(&probe, 0).unwrap(); let found = @containsText@(&probe, &probe[0]); let generated_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; let before = ALLOCATIONS.load(Ordering::Relaxed); let reference_size = probe.first().unwrap().chars().count() as i64; let reference_found = probe.iter().any(|value| value == &probe[0]); let reference_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!((size, found), (reference_size, reference_found)); assert_eq!(generated_allocations, 0); assert_eq!(reference_allocations, 0); let before = ALLOCATIONS.load(Ordering::Relaxed); let loop_size = @loopMeasured@(&probe); let filter_size = @filterMeasured@(&probe); let range_total = @rangeMeasured@(0, 1024); let loop_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(loop_size, probe.iter().map(|v| v.chars().count() as i64).sum::()); assert_eq!(range_total, (0..1024).sum::()); assert_eq!(filter_size, loop_size); assert_eq!(loop_allocations, 0, "borrowed loop and lazy range need no intermediate allocation"); let messages = [@Message@::Named(probe[0].clone()), @Message@::Empty]; let before = ALLOCATIONS.load(Ordering::Relaxed); let message_size = @payloadMeasured@(&messages); let message_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(message_size, reference_size); assert_eq!(message_allocations, 0, "choice filter borrows payloads instead of copying messages"); let before = ALLOCATIONS.load(Ordering::Relaxed); let empty_kept = @emptyKeep@(&probe); let empty_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert!(empty_kept.f0.is_empty()); assert_eq!(empty_kept.f1, 2); assert_eq!(empty_allocations, 0, "constant take zero does not clone a retained source"); let source = (0..4096).map(|index| "中文".repeat(index * 19 % 97)).collect::>(); let reference = source.clone(); let before = ALLOCATIONS.load(Ordering::Relaxed); let sorted = @sortedMeasured@(source); let sorted_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; let before = ALLOCATIONS.load(Ordering::Relaxed); let mut keyed = reference.into_iter().map(|text| ((text.chars().count() as i64,), text)).collect::>(); keyed.sort_by(|left, right| left.0.cmp(&right.0)); let reference = keyed.into_iter().map(|(_, text)| text).collect::>(); let reference_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(sorted, reference); assert_eq!(sorted_allocations, reference_allocations, "stable cached-key sorting has no extra allocation over direct Rust"); let before = ALLOCATIONS.load(Ordering::Relaxed); let entries = @mapEntries@(map); let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(allocations, 1, "collect entries once, move keys and values without cloning"); assert_eq!(entries.iter().map(|e| e.f0.as_str()).collect::>(), vec!["first", "middle", "last"]); assert_eq!(@entryValueSize@(&entries[0]), 3); let renamed = @renamedEntry@(entries.into_iter().next().unwrap()); assert_eq!(renamed.f0, "renamed"); assert_eq!(renamed.f1, "one"); assert_eq!(@entryIntValue@(dever_runtime::collection::MapEntry { f0: 1, f1: 2 }), 2); let result = @handlerNative@("hello".to_owned()); assert_eq!(result.f0, "hello"); assert_eq!(result.f1, "hello!"); assert_eq!(@handlerRuled@("table".to_owned()), "table!"); assert!(matches!(@handlerCaptured@(3), @HandlerResult@::Done(3))); assert!(matches!(@handlerCaptured@(0), @HandlerResult@::Rejected(f0) if f0 == "positive required")); assert_eq!(@handlerPaired@(4), 9); let before = ALLOCATIONS.load(Ordering::Relaxed); let actual = @handlerMeasured@(&probe[0]); let handler_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(actual, probe[0].chars().count() as i64); assert_eq!(handler_allocations, 0, "static callbacks borrow without heap allocation"); let before = ALLOCATIONS.load(Ordering::Relaxed); let flow_size = @flowMeasured@(&probe[0]); let flow_allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(flow_size, actual); assert_eq!(flow_allocations, 0, "sequential flow borrows without a runtime workflow object"); assert_eq!(@handlerGuardedNative@(2).unwrap(), 1); assert!(matches!(@handlerGuardedNative@(0), Err(Failure::Api(ApiError::Invalid)))); let state = String::from("累积状态不在每轮复制"); let pointer = state.as_ptr(); let before = ALLOCATIONS.load(Ordering::Relaxed); let size = @foldMeasured@(&probe); let kept = @foldMove@(&[1, 2, 3], state); let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(size, probe.iter().map(|s| s.chars().count() as i64).sum::()); assert_eq!(kept.as_ptr(), pointer); assert_eq!(allocations, 0, "fold borrows source values and moves state without allocating"); let before = ALLOCATIONS.load(Ordering::Relaxed); let walked = @walkMeasured@(std::hint::black_box(100)); let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(walked, 5050); assert_eq!(allocations, 0, "walk directly advances state without a queue or boxed iterator"); let pair = @FieldPair@ { f0: "左字段".into(), f1: "右字段".into(), f2: 3 }; let pointers = [pair.f0.as_ptr(), pair.f1.as_ptr()]; let before = ALLOCATIONS.load(Ordering::Relaxed); let swapped = @swapFields@(pair); let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!([swapped.f0.as_ptr(), swapped.f1.as_ptr()], [pointers[1], pointers[0]]); assert_eq!(swapped.f2, 3); assert_eq!(allocations, 0, "disjoint record fields move independently"); let kept = @keepFields@(swapped); assert_eq!((&kept.f0.f0, &kept.f1.f0), (&String::from("左字段"), &String::from("右字段"))); let original = kept.f1.f0.as_ptr(); let before = ALLOCATIONS.load(Ordering::Relaxed); let copied = @copyField@(kept.f1); let allocations = ALLOCATIONS.load(Ordering::Relaxed) - before; assert_eq!(copied.f0, copied.f1); assert_eq!(copied.f1.as_ptr(), original); assert_eq!(allocations, 1, "reusing the same field copies it exactly once"); let mut capacity_map = Map::with_capacity(8); capacity_map.put(0, 5); let before = ALLOCATIONS.load(Ordering::Relaxed); let capacity_map = @putAtLength@(capacity_map); let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(capacity_map.get(&1), Some(&17)); assert_eq!(after - before, 0, "updating from the same map must reuse its storage"); let mut capacity_list = Vec::with_capacity(8); capacity_list.push(5); let before = ALLOCATIONS.load(Ordering::Relaxed); let capacity_list = @appendOwnLength@(capacity_list); let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(capacity_list, [5, 1]); assert_eq!(after - before, 0, "reading length must not clone the list"); { let mut values = Vec::with_capacity(8); values.push(5); let pointer = values.as_ptr(); let state = @CollectionRecord@ { f0: values, f1: Map::with_capacity(0) }; let before = ALLOCATIONS.load(Ordering::Relaxed); let values = @appendFieldLength@(state).f0; let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(values, [5, 1]); assert_eq!(values.as_ptr(), pointer, "local field updates reuse the owned buffer"); assert_eq!(after - before, 0, "reading a local field must not clone its list"); } let mut lookup = Map::with_capacity(8); lookup.put(0, 5); let state = @CollectionRecord@ { f0: vec![5, 6], f1: lookup }; let before = ALLOCATIONS.load(Ordering::Relaxed); let lookup = @putFieldLength@(state).f0; let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(lookup.get(&1), Some(&2)); assert_eq!(after - before, 0, "local field updates reuse the owned map"); let state = @CollectionRecord@ { f0: vec![5], f1: Map::with_capacity(0) }; let pointer = state.f0.as_ptr(); let preserved = @appendFieldKeepOriginal@(state); assert_eq!(preserved.f0, [5, 1]); assert_eq!(preserved.f1.f0, [5]); assert_eq!(preserved.f1.f0.as_ptr(), pointer); assert_ne!(preserved.f0.as_ptr(), pointer); assert!(matches!(@appendEvaluatedField@(), Err(Failure::Api(ApiError::Forbidden))), "a computed receiver still fails before its item expression"); let mut entries = Map::with_capacity(2); entries.put(3, 11); entries.put(1, 17); let before = ALLOCATIONS.load(Ordering::Relaxed); let total = @sumMap@(&entries); let first = @firstMapKey@(&entries); let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!((total, first), (28, Some(3))); assert_eq!(after - before, 0, "direct traversal must not materialize or clone entries"); assert_eq!(entries.get(&1), Some(&17)); assert_eq!(@sumTemporaryMap@(), 28); assert_eq!(@sumMap@(&Map::with_capacity(0)), 0); assert_eq!(@firstMapKey@(&Map::with_capacity(0)), None); let copied = @copyMapEntries@(&entries); assert_eq!(copied.iter().map(|entry| (entry.f0, entry.f1)).collect::>(), [(3,11), (1,17)]); let mut buffer = Vec::with_capacity(8); buffer.push(4); let pointer = buffer.as_ptr(); let initial = @FoldRecord@ { f0: buffer, f1: 11, f2: 23 }; let before = ALLOCATIONS.load(Ordering::Relaxed); let result = @recordFields@(&[7, 8, 9], initial); let after = ALLOCATIONS.load(Ordering::Relaxed); assert_eq!(result.f0, [4, 8, 10, 12]); assert_eq!((result.f1, result.f2), (23, 11), "field swaps read the previous state"); assert_eq!(result.f0.as_ptr(), pointer); assert_eq!(after - before, 0, "record fold retains its existing buffer"); let empty = @recordFields@(&[], result); assert_eq!(empty.f0.as_ptr(), pointer); assert_eq!((empty.f1, empty.f2), (23, 11)); let preserved = @recordOldSize@(&[7, 8, 9]); assert_eq!(preserved.f0, [7, 8, 9]); assert_eq!(preserved.f1, 2, "reading an old buffer after append must preserve value semantics"); let state = || @FoldRecord@ { f0: Vec::new(), f1: i64::MAX, f2: 0 }; let direct = std::panic::catch_unwind(|| @recordFault@(i64::MAX, state())).err().expect("direct overflow"); let folded = std::panic::catch_unwind(|| @foldedFault@(&[i64::MAX], state())).err().expect("folded overflow"); let direct = direct.downcast_ref::<&'static FaultInfo>().unwrap(); let folded = folded.downcast_ref::<&'static FaultInfo>().unwrap(); assert_eq!((direct.source, direct.line, direct.column), (folded.source, folded.line, folded.column), "fold retains field evaluation and first fault location");