Skip to content

Commit

Permalink
feat: (wnfs-wasm) add read_at to PrivateFile and add `get_content…
Browse files Browse the repository at this point in the history
…` to `PublicFile`
  • Loading branch information
icidasset committed Dec 20, 2023
1 parent 2b95b97 commit 7049f38
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 94 deletions.
37 changes: 27 additions & 10 deletions wnfs-wasm/src/fs/private/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
value,
};
use chrono::{DateTime, Utc};
use js_sys::{Date, Promise, Uint8Array};
use js_sys::{Date, Number, Promise, Uint8Array};
use std::rc::Rc;
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen_futures::future_to_promise;
Expand Down Expand Up @@ -86,23 +86,40 @@ impl PrivateFile {
/// Gets the entire content of a file.
#[wasm_bindgen(js_name = "getContent")]
pub fn get_content(&self, forest: &PrivateForest, store: BlockStore) -> JsResult<Promise> {
self.read_at(value!(0).into(), None, forest, store)
}

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
}

/// Gets the content of the file at given offset & with an optional byte limit.
#[wasm_bindgen(js_name = "readAt")]
pub fn read_at(
&self,
byte_offset: Number,
limit: Option<Number>,
forest: &PrivateForest,
store: BlockStore,
) -> JsResult<Promise> {
let file = Rc::clone(&self.0);
let store = ForeignBlockStore(store);
let forest = Rc::clone(&forest.0);

let byte_offset = f64::from(byte_offset) as usize;
let limit = limit.map(|lim| f64::from(lim) as usize);

Ok(future_to_promise(async move {
let content = file
.get_content(&forest, &store)
let result = file
.read_at(byte_offset, limit, &forest, &store)
.await
.map_err(error("Cannot get content of file"))?;
.map_err(error("Cannot read file"))?;

Ok(value!(Uint8Array::from(content.as_slice())))
}))
}
let uint8array = Uint8Array::from(result.as_ref());

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
Ok(value!(uint8array))
}))
}

/// Gets a unique id for node.
Expand Down
6 changes: 6 additions & 0 deletions wnfs-wasm/src/fs/public/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ impl PublicFile {
arr
}

/// Gets the entire content of a file.
#[wasm_bindgen(js_name = "getContent")]
pub fn get_content(&self, store: BlockStore) -> JsResult<Promise> {
self.read_at(value!(0).into(), None, store)
}

/// Gets the metadata of this file.
pub fn metadata(&self) -> JsResult<JsValue> {
JsMetadata(self.0.get_metadata()).try_into()
Expand Down
Loading

0 comments on commit 7049f38

Please sign in to comment.