Skip to content

Commit

Permalink
Add IBlob::slice and IBlob::slice_with_content_type (#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gowee authored and koute committed Jul 15, 2019
1 parent aabdf4b commit af02fb4
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/webapi/blob.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
use std::ops::{RangeBounds, Bound};

use webcore::value::Reference;
use webcore::try_from::TryInto;
use webcore::reference_type::ReferenceType;
use webcore::number::Number;
use webcore::optional_arg::OptionalArg;

// https://w3c.github.io/FileAPI/#ref-for-dfn-slice
fn slice_blob< T, U >( blob: &T, range: U, content_type: Option< &str > ) -> Blob
where T: IBlob, U: RangeBounds< u64 >
{
let start: Number = match range.start_bound() {
Bound::Included(&n) => n,
Bound::Excluded(&n) => n + 1,
Bound::Unbounded => 0
}.try_into().unwrap();

let end: OptionalArg< Number > = match range.end_bound() {
Bound::Included(&n) => Some(n + 1),
Bound::Excluded(&n) => Some(n),
Bound::Unbounded => None
}.try_into().unwrap();

let content_type: OptionalArg< &str > = content_type.into();
let reference = blob.as_ref();
js! (
return @{reference}.slice(@{start}, @{end}, @{content_type});
).try_into().unwrap()
}

/// A blob object represents a file-like object of immutable, raw data.
/// Blobs represent data that isn't necessarily in a JavaScript-native format.
Expand Down Expand Up @@ -31,6 +58,25 @@ pub trait IBlob: ReferenceType {
Some( mime )
}
}

/// Create a new `Blob` object containing the data in the specified range of bytes of the
/// source `Blob`.
///
/// See also [slice_with_content_type](IBlob::slice_with_content_type).
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice)
fn slice< T >( &self, range: T ) -> Blob
where T: RangeBounds<u64>
{
slice_blob(self, range, None)
}

/// [slice](IBlob::slice) `Blob` with the provided `content_type`.
fn slice_with_content_type< T >( &self, range: T, content_type: &str ) -> Blob
where T: RangeBounds<u64>
{
slice_blob(self, range, Some(content_type))
}
}

/// A reference to a JavaScript object which implements the [IBlob](trait.IBlob.html)
Expand Down

0 comments on commit af02fb4

Please sign in to comment.