cast_buffer.js (1708B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var bufferCtors = require( './../../base/buffer-ctors' ); 24 var allocUnsafe = require( '@stdlib/buffer/alloc-unsafe' ); 25 26 27 // MAIN // 28 29 /** 30 * Casts buffer elements by copying those elements to a buffer of another data type. 31 * 32 * @private 33 * @param {(Array|TypedArray|Buffer)} buffer - input buffer 34 * @param {NonNegativeInteger} len - number of elements to cast 35 * @param {string} dtype - data type 36 * @returns {(Array|TypedArray|Buffer)} output buffer 37 * 38 * @example 39 * var b = castBuffer( [ 1.0, 2.0, 3.0 ], 3, 'float64' ); 40 * // returns <Float64Array>[ 1.0, 2.0, 3.0 ] 41 */ 42 function castBuffer( buffer, len, dtype ) { 43 var ctor; 44 var out; 45 var i; 46 47 ctor = bufferCtors( dtype ); 48 if ( dtype === 'generic') { 49 out = []; 50 for ( i = 0; i < len; i++ ) { 51 out.push( buffer[ i ] ); 52 } 53 } else if ( dtype === 'binary' ) { 54 out = allocUnsafe( len ); 55 for ( i = 0; i < len; i++ ) { 56 out[ i ] = buffer[ i ]; 57 } 58 } else { 59 out = new ctor( len ); 60 for ( i = 0; i < len; i++ ) { 61 out[ i ] = buffer[ i ]; 62 } 63 } 64 return out; 65 } 66 67 68 // EXPORTS // 69 70 module.exports = castBuffer;