stdweb/webapi/
array_buffer.rs

1use webcore::value::Reference;
2use webcore::try_from::TryInto;
3use webcore::value::Value;
4use webapi::typed_array::TypedArray;
5use private::TODO;
6
7/// The `ArrayBuffer` object is used to represent a generic, fixed-length raw binary data buffer.
8/// You cannot directly manipulate the contents of an ArrayBuffer; instead, you create an [TypedArray](struct.TypedArray.html)
9/// to do it.
10///
11/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
12// https://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor
13#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
14#[reference(instance_of = "ArrayBuffer")]
15pub struct ArrayBuffer( Reference );
16
17impl ArrayBuffer {
18    /// Creates a new `ArrayBuffer` with the given length in bytes.
19    // https://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-length
20    pub fn new( length: u64 ) -> Result< Self, TODO > {
21        let length: Value = length.try_into().unwrap();
22        Ok( js!( return new ArrayBuffer( @{length} ); ).try_into().unwrap() )
23    }
24
25    /// Returns the length of the buffer, in bytes.
26    // https://www.ecma-international.org/ecma-262/6.0/#sec-get-arraybuffer.prototype.bytelength
27    pub fn len( &self ) -> u64 {
28        let reference = self.as_ref();
29        let length = js!( return @{reference}.byteLength; ).try_into().unwrap();
30        length
31    }
32}
33
34// TODO: Implement for other types.
35// TODO: Implement slightly more efficiently than going through the TypedArray.
36impl From< ArrayBuffer > for Vec< u8 > {
37    fn from( buffer: ArrayBuffer ) -> Self {
38        let typed_array: TypedArray< u8 > = buffer.into();
39        typed_array.into()
40    }
41}
42
43impl< 'a > From< &'a ArrayBuffer > for Vec< u8 > {
44    fn from( buffer: &'a ArrayBuffer ) -> Self {
45        let typed_array: TypedArray< u8 > = buffer.into();
46        typed_array.into()
47    }
48}