Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buf write simplification #898

Merged
merged 1 commit into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 3 additions & 23 deletions crates/library/std/src/buf.fe
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub struct MemoryBuffer {

pub fn new(len: u256) -> Self {
unsafe {
return MemoryBuffer(offset: alloc(len), len)
return MemoryBuffer(offset: alloc(len: len + 30), len)
}
}

Expand Down Expand Up @@ -103,7 +103,8 @@ pub struct MemoryBufferWriter {

pub fn write_n(mut self, value: u256, len: u256) {
let offset: u256 = self.write_offset(len)
unsafe { rewrite_slot(offset, value, len) }
let shifted_value: u256 = evm::shl(bits: 256 - len * 8, value)
unsafe { evm::mstore(offset, value: shifted_value) }
}

pub fn write_buf(mut self, buf: MemoryBuffer) {
Expand Down Expand Up @@ -174,27 +175,6 @@ impl MemoryBufferWrite for () {
fn write_buf(self, mut writer: MemoryBufferWriter) {}
}

/// Rewrites the left-most `len` bytes in slot with the right-most `len` bytes of `value`.
unsafe fn rewrite_slot(offset: u256, value: u256, len: u256) {
// bit mask for right side of 256 bit slot
let mask: u256 = evm::shr(
bits: len * 8,
value: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
// new value shifted to left
let shifted_value: u256 = evm::shl(
bits: 256 - len * 8,
value
)

let old_value: u256 = evm::mload(offset)
let new_value: u256 = evm::bitwise_or(
evm::bitwise_and(mask, old_value),
shifted_value
)
evm::mstore(offset, value: new_value)
}

/// Memory buffer reader abstraction.
pub struct MemoryBufferReader {
buf: MemoryBuffer
Expand Down
1 change: 1 addition & 0 deletions newsfragments/898.performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`MemoryBuffer` now allocates an extra 31 bytes. This removes the need for runtime checks and bitshifting needed to ensure safe writing to a `MemoryBuffer`'s region.