Skip to content

Commit

Permalink
New Bytes type module for the stdlib (FuelLabs#3454)
Browse files Browse the repository at this point in the history
Adds a new heap type `Bytes` to the stdlib which holds an arbitrary
number of packed bytes.
  • Loading branch information
nfurfaro authored Dec 10, 2022
1 parent c9565f8 commit 71a33f9
Show file tree
Hide file tree
Showing 5 changed files with 979 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions sway-lib-core/src/raw_ptr.sw
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,43 @@ impl raw_ptr {
};
}
}

/// Writes the given byte to the address.
pub fn write_byte(self, val: u8) {
let val_ptr = asm(r1: val) { r1: raw_ptr };
asm(ptr: self, val: val_ptr) {
sb ptr val i0;
};
}

/// reads a byte from the given address.
pub fn read_byte(self) -> u8 {
asm(r1: self, r2) {
lb r2 r1 i0;
r2: u8
}
}

/// Copies `count` bytes from `self` to `dst`
pub fn copy_bytes_to(self, dst: raw_ptr, count: u64) {
asm(dst: dst, src: self, len: count) {
mcp dst src len;
};
}

/// Add a u64 offset to a raw_ptr
pub fn add_uint_offset(self, offset: u64) -> raw_ptr {
asm(ptr: self, offset: offset, new) {
add new ptr offset;
new: raw_ptr
}
}

/// Subtract a u64 offset from a raw_ptr
pub fn sub_uint_offset(self, offset: u64) -> raw_ptr {
asm(ptr: self, offset: offset, new) {
sub new ptr offset;
new: raw_ptr
}
}
}
22 changes: 22 additions & 0 deletions sway-lib-std/src/alloc.sw
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,25 @@ pub fn realloc<T>(ptr: raw_ptr, count: u64, new_count: u64) -> raw_ptr {
ptr
}
}

/// Allocates zeroed memory on the heap in individual bytes
pub fn alloc_bytes(count: u64) -> raw_ptr {
asm(size: count, ptr) {
aloc size;
addi ptr hp i1;
ptr: raw_ptr
}
}

/// Reallocates the given area of memory in individual bytes
pub fn realloc_bytes(ptr: raw_ptr, count: u64, new_count: u64) -> raw_ptr {
if new_count > count {
let new_ptr = alloc_bytes(new_count);
if count > 0 {
ptr.copy_bytes_to(new_ptr, count);
}
new_ptr
} else {
ptr
}
}
Loading

0 comments on commit 71a33f9

Please sign in to comment.