Skip to content

Commit 2229045

Browse files
committed
Add a small utility converter.
1 parent 5609fc9 commit 2229045

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

crates/file/src/file_reader.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,19 @@ pub mod callbacks {
142142
}
143143
}
144144

145+
/// Read the contents of `blob` into a `Vec<u8>`, and then run the callback.
146+
///
147+
/// If the returned `FileReader` is dropped before the callback is invoked, the read will be
148+
/// cancelled.
149+
pub fn read_as_bytes<F>(blob: &Blob, callback: F) -> FileReader
150+
where
151+
F: FnOnce(Result<Vec<u8>, FileReadError>) + 'static,
152+
{
153+
read_as_array_buffer(blob, move |result| {
154+
callback(result.map(|buffer| js_sys::Uint8Array::new(&buffer).to_vec()));
155+
})
156+
}
157+
145158
/// Get the event from the reader target, doing necessary casting.
146159
fn reader_from_event(event: &web_sys::Event) -> web_sys::FileReader {
147160
let target = event.target().unwrap_throw();
@@ -192,6 +205,15 @@ pub mod futures {
192205
});
193206
receiver.await.unwrap_throw()
194207
}
208+
209+
/// Read the contents of `blob` into a Vec<u8>.
210+
pub async fn read_as_bytes(blob: &Blob) -> Result<Vec<u8>, FileReadError> {
211+
let (sender, receiver) = futures_channel::oneshot::channel();
212+
let _reader = super::callbacks::read_as_bytes(blob, |result| {
213+
sender.send(result).unwrap_throw();
214+
});
215+
receiver.await.unwrap_throw()
216+
}
195217
}
196218

197219
enum ReadyState {

crates/file/tests/web.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,16 @@ async fn data_url_future() {
6363
);
6464
}
6565

66+
#[cfg(feature = "futures")]
67+
#[wasm_bindgen_test]
68+
async fn bytes_future() {
69+
let blob = Blob::new_with_options(PNG_FILE, Some("image/png"));
70+
assert_eq!(
71+
gloo_file::futures::read_as_bytes(&blob).await.unwrap(),
72+
PNG_FILE
73+
);
74+
}
75+
6676
const PNG_FILE: &'static [u8] = &[
6777
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
6878
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56,

0 commit comments

Comments
 (0)