Skip to content

Commit

Permalink
Update write.
Browse files Browse the repository at this point in the history
  • Loading branch information
AureliaDolo committed Dec 8, 2021
1 parent 14cf6e9 commit 564d539
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub trait Read<T> {

pub trait Write<T> {
fn alloc(value: &str, memory: &Env) -> anyhow::Result<Box<Self>>;
fn write(&self, value: &str, env: &Env) -> anyhow::Result<()>;
fn write(&mut self, value: &str, env: &Env) -> anyhow::Result<Box<Self>>;
fn free(memory: &Env) -> anyhow::Result<()>;
}

Expand Down
19 changes: 15 additions & 4 deletions src/string_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,29 @@ impl Write<String> for StringPtr {
Ok(Box::new(StringPtr::new(offset)))
}

fn write(&self, value: &str, env: &Env) -> anyhow::Result<()> {
fn write(&mut self, value: &str, env: &Env) -> anyhow::Result<Box<StringPtr>> {
let prev_size = size(
self.offset(),
env.memory.get_ref().expect("Failed to load memory"),
)?;
let new_size = u32::try_from(value.len())? << 1;
if prev_size == new_size {
write_str(self.offset(), value, env)?
write_str(self.offset(), value, env)?;
Ok(Box::new(*self))
} else {
todo!("Remove this and reallocate of bigger or smaller space")
// unpin old ptr
let unpin = export_asr!(fn_pin, env);
unpin
.call(&[Value::I32(self.offset().try_into().unwrap())])
.expect("Failed to call __unpin");

// collect
let collect = export_asr!(fn_collect, env);
collect.call(&[]).expect("failed to call __collect");

// alloc with new size
StringPtr::alloc(value, env)
}
Ok(())
}

fn free(_env: &Env) -> anyhow::Result<()> {
Expand Down
2 changes: 1 addition & 1 deletion tests/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ fn read_write_strings() -> Result<(), Box<dyn Error>> {
.exports
.get_native_function::<(), StringPtr>("getString")?;

let str_ptr = get_string.call()?;
let mut str_ptr = get_string.call()?;
let string = str_ptr.read(memory)?;

assert_eq!(string, "hello test");
Expand Down

0 comments on commit 564d539

Please sign in to comment.