Skip to content

Commit

Permalink
Add ByteArray.reverse
Browse files Browse the repository at this point in the history
Similar to Array.reverse this reverses the values in-place.

Changelog: added
  • Loading branch information
yorickpeterse committed Oct 11, 2022
1 parent 110dd0a commit d9c0d64
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
23 changes: 23 additions & 0 deletions libstd/src/std/byte_array.inko
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,29 @@ class builtin ByteArray {
fn pub iter -> Bytes {
Bytes { @bytes = self, @index = 0 }
}

# Reverses `self` in-place
#
# # Examples
#
# let a = ByteArray.from_array([10, 20, 30])
#
# a.reverse
#
# a # => ByteArray.from_array([30, 20, 10])
fn pub mut reverse {
let mut a = 0
let mut b = length - 1

while a < b {
let a_val = _INKO.byte_array_get(self, a)

_INKO.byte_array_set(self, a, _INKO.byte_array_set(self, b, a_val))

a += 1
b -= 1
}
}
}

impl Drop for ByteArray {
Expand Down
8 changes: 8 additions & 0 deletions libstd/test/std/test_byte_array.inko
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,12 @@ fn pub tests(t: mut Tests) {
t.equal(iter.read_all(buff), 0)
t.equal(buff.to_string, 'foo')
}

t.test('ByteArray.reverse') fn (t) {
let vals = ByteArray.from_array([10, 20, 30])

vals.reverse

t.equal(vals, ByteArray.from_array([30, 20, 10]))
}
}

0 comments on commit d9c0d64

Please sign in to comment.