40322e19f3b23d4161c92924fcfcff8b8a65af98
[platform/framework/web/crosswalk-tizen.git] /
1 var constant = require('../utility/constant'),
2     isNative = require('../lang/isNative');
3
4 /** Native method references. */
5 var ArrayBuffer = isNative(ArrayBuffer = global.ArrayBuffer) && ArrayBuffer,
6     bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice,
7     floor = Math.floor,
8     Uint8Array = isNative(Uint8Array = global.Uint8Array) && Uint8Array;
9
10 /** Used to clone array buffers. */
11 var Float64Array = (function() {
12   // Safari 5 errors when using an array buffer to initialize a typed array
13   // where the array buffer's `byteLength` is not a multiple of the typed
14   // array's `BYTES_PER_ELEMENT`.
15   try {
16     var func = isNative(func = global.Float64Array) && func,
17         result = new func(new ArrayBuffer(10), 0, 1) && func;
18   } catch(e) {}
19   return result;
20 }());
21
22 /** Used as the size, in bytes, of each `Float64Array` element. */
23 var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0;
24
25 /**
26  * Creates a clone of the given array buffer.
27  *
28  * @private
29  * @param {ArrayBuffer} buffer The array buffer to clone.
30  * @returns {ArrayBuffer} Returns the cloned array buffer.
31  */
32 function bufferClone(buffer) {
33   return bufferSlice.call(buffer, 0);
34 }
35 if (!bufferSlice) {
36   // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`.
37   bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) {
38     var byteLength = buffer.byteLength,
39         floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0,
40         offset = floatLength * FLOAT64_BYTES_PER_ELEMENT,
41         result = new ArrayBuffer(byteLength);
42
43     if (floatLength) {
44       var view = new Float64Array(result, 0, floatLength);
45       view.set(new Float64Array(buffer, 0, floatLength));
46     }
47     if (byteLength != offset) {
48       view = new Uint8Array(result, offset);
49       view.set(new Uint8Array(buffer, offset));
50     }
51     return result;
52   };
53 }
54
55 module.exports = bufferClone;