Skip to content

Commit

Permalink
Merge pull request ethereum#898 from g-r-a-n-t/buf-simplification
Browse files Browse the repository at this point in the history
Buf write simplification
  • Loading branch information
g-r-a-n-t authored Jun 21, 2023
2 parents 54934fd + b67e25b commit c7015d1
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 23 deletions.
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.

0 comments on commit c7015d1

Please sign in to comment.