From b8add1cd694ced5bc4b2c8ccf22d7716491b9ea3 Mon Sep 17 00:00:00 2001 From: Akuli Date: Wed, 11 Dec 2024 23:25:35 +0200 Subject: [PATCH] Finish documenting memswap() and implement it --- stdlib/mem.jou | 11 ++++++++++- tests/should_succeed/memlibtest.jou | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 tests/should_succeed/memlibtest.jou diff --git a/stdlib/mem.jou b/stdlib/mem.jou index e7c3f6f5..890cf53b 100644 --- a/stdlib/mem.jou +++ b/stdlib/mem.jou @@ -26,4 +26,13 @@ declare memcpy(dest: void*, source: void*, size: long) -> void* # copy memory, declare memmove(dest: void*, source: void*, size: long) -> void* # copy memory, overlaps are ok # Swaps the contents of two memory regions of the same size. -# This does nothing if the memory regions +# This does nothing if the same memory region is passed twice. +# This may not work correctly if two different but overlapping regions are given. +def memswap(a: void*, b: void*, size: long) -> None: + a_bytes: byte* = a + b_bytes: byte* = b + + for i = 0L; i < size; i++: + old_a = a_bytes[i] + a_bytes[i] = b_bytes[i] + b_bytes[i] = old_a diff --git a/tests/should_succeed/memlibtest.jou b/tests/should_succeed/memlibtest.jou new file mode 100644 index 00000000..3954d80b --- /dev/null +++ b/tests/should_succeed/memlibtest.jou @@ -0,0 +1,15 @@ +import "stdlib/mem.jou" +import "stdlib/io.jou" + + +def main() -> int: + a = 123 + b = 456 + + memswap(&a, &b, sizeof(a)) + printf("%d %d\n", a, b) # Output: 456 123 + + memswap(&a, &a, sizeof(a)) # does nothing + printf("%d %d\n", a, b) # Output: 456 123 + + return 0