Skip to content

Commit

Permalink
Add memcmp() function to stdlib/mem.jou (#748)
Browse files Browse the repository at this point in the history
  • Loading branch information
Akuli authored Feb 5, 2025
1 parent 210b353 commit c9ff834
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 8 deletions.
4 changes: 0 additions & 4 deletions compiler/tokenizer.jou
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,6 @@ def flip_paren(c: byte) -> byte:
assert False


# TODO: put to stdlib
declare memcmp(s1: void*, s2: void*, n: long) -> int


def detect_banned_whitespace_characters(last_3_bytes: byte[3]) -> byte*:
last_2_bytes = [last_3_bytes[1], last_3_bytes[2]]

Expand Down
4 changes: 0 additions & 4 deletions compiler/uvg_analyze.jou
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,6 @@ def update_statuses_based_on_instructions(uvg: Uvg*, statuses: VarStatus*, block
statuses[ins->var] = VarStatus.DontAnalyze


# TODO: put to stdlib
declare memcmp(s1: void*, s2: void*, n: long) -> int


def analyze_block(uvg: Uvg*, statuses_at_end: VarStatus**, blockidx: int, warn: bool) -> bool:
statuses = build_statuses_at_start_of_block(uvg, statuses_at_end, blockidx)
update_statuses_based_on_instructions(uvg, statuses, uvg->blocks[blockidx], warn)
Expand Down
14 changes: 14 additions & 0 deletions stdlib/mem.jou
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ declare memcpy(dest: void*, source: void*, size: long) -> void* # copy memory,
@public
declare memmove(dest: void*, source: void*, size: long) -> void* # copy memory, overlaps are ok

# Compare two memory regions of the same size. Return 0 if they contain the
# same bytes, nonzero if different bytes.
#
# This can be used to e.g. check if two arrays of ints are equal:
#
# a = [1, 2, 3]
# b = [1, 2, 4]
# if memcmp(a, b, sizeof(a)) != 0:
# printf("Different\n")
#
# This is somewhat similar to strcmp() in stdlib/str.jou.
@public
declare memcmp(a: void*, b: void*, size: long) -> int

# Swaps the contents of two memory regions of the same size.
# This does nothing if the same memory region is passed twice.
# This probably doesn't do what you want if the memory regions overlap in some other way.
Expand Down
8 changes: 8 additions & 0 deletions tests/should_succeed/memlibtest.jou
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@ def main() -> int:
memswap(&a, &a, sizeof(a)) # does nothing
printf("%d %d\n", a, b) # Output: 456 123

arr1 = [1, 2, 3]
arr2 = [1, 2, 3]
printf("%d\n", memcmp(arr1, arr2, sizeof(arr1))) # Output: 0
arr1[1]++
printf("%d\n", memcmp(arr1, arr2, sizeof(arr1))) # Output: 1
arr2[0]++
printf("%d\n", memcmp(arr1, arr2, sizeof(arr1))) # Output: -1

return 0

0 comments on commit c9ff834

Please sign in to comment.