1# this is based on jsarray.py 2 3from ..base import * 4try: 5 import numpy 6except: 7 pass 8 9 10@Js 11def Int16Array(): 12 TypedArray = (PyJsInt8Array, PyJsUint8Array, PyJsUint8ClampedArray, 13 PyJsInt16Array, PyJsUint16Array, PyJsInt32Array, 14 PyJsUint32Array, PyJsFloat32Array, PyJsFloat64Array) 15 a = arguments[0] 16 if isinstance(a, PyJsNumber): # length 17 length = a.to_uint32() 18 if length != a.value: 19 raise MakeError('RangeError', 'Invalid array length') 20 temp = Js(numpy.full(length, 0, dtype=numpy.int16)) 21 temp.put('length', a) 22 return temp 23 elif isinstance(a, PyJsString): # object (string) 24 temp = Js(numpy.array(list(a.value), dtype=numpy.int16)) 25 temp.put('length', Js(len(list(a.value)))) 26 return temp 27 elif isinstance(a, PyJsArray) or isinstance(a, TypedArray) or isinstance( 28 a, PyJsArrayBuffer): # object (Array, TypedArray) 29 array = a.to_list() 30 array = [(int(item.value) if item.value != None else 0) 31 for item in array] 32 temp = Js(numpy.array(array, dtype=numpy.int16)) 33 temp.put('length', Js(len(array))) 34 return temp 35 elif isinstance(a, PyObjectWrapper): # object (ArrayBuffer, etc) 36 if len(a.obj) % 2 != 0: 37 raise MakeError( 38 'RangeError', 39 'Byte length of Int16Array should be a multiple of 2') 40 if len(arguments) > 1: 41 offset = int(arguments[1].value) 42 if offset % 2 != 0: 43 raise MakeError( 44 'RangeError', 45 'Start offset of Int16Array should be a multiple of 2') 46 else: 47 offset = 0 48 if len(arguments) > 2: 49 length = int(arguments[2].value) 50 else: 51 length = int((len(a.obj) - offset) / 2) 52 array = numpy.frombuffer( 53 a.obj, dtype=numpy.int16, count=length, offset=offset) 54 temp = Js(array) 55 temp.put('length', Js(length)) 56 temp.buff = array 57 return temp 58 temp = Js(numpy.full(0, 0, dtype=numpy.int16)) 59 temp.put('length', Js(0)) 60 return temp 61 62 63Int16Array.create = Int16Array 64Int16Array.own['length']['value'] = Js(3) 65 66Int16Array.define_own_property( 67 'prototype', { 68 'value': Int16ArrayPrototype, 69 'enumerable': False, 70 'writable': False, 71 'configurable': False 72 }) 73 74Int16ArrayPrototype.define_own_property( 75 'constructor', { 76 'value': Int16Array, 77 'enumerable': False, 78 'writable': True, 79 'configurable': True 80 }) 81 82Int16ArrayPrototype.define_own_property('BYTES_PER_ELEMENT', { 83 'value': Js(2), 84 'enumerable': False, 85 'writable': False, 86 'configurable': False 87}) 88