Skip to content

Commit

Permalink
Finish documenting memswap() and implement it
Browse files Browse the repository at this point in the history
  • Loading branch information
Akuli committed Dec 11, 2024
1 parent 2b75b3f commit 1deeb7c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
21 changes: 15 additions & 6 deletions stdlib/mem.jou
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

# Heap allocations
# TODO: write a tutorial about using these and add a link
declare malloc(size: long) -> void*
declare calloc(a: long, b: long) -> void*
declare realloc(ptr: void*, new_size: long) -> void*
declare free(ptr: void*) -> None
declare malloc(size: long) -> void* # allocate memory
declare calloc(a: long, b: long) -> void* # allocate a*b bytes of memory and zero it
declare realloc(ptr: void*, new_size: long) -> void* # grow/shrink allocated memory
declare free(ptr: void*) -> None # release allocated memory so it can be reused

# Fill a memory region with the given byte.
# This function fills a memory region with the given byte.
# The most common way use case for this function is zeroing memory:
#
# memset(&foo, 0, sizeof(foo))
Expand All @@ -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
15 changes: 15 additions & 0 deletions tests/should_succeed/memlibtest.jou
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 1deeb7c

Please sign in to comment.