'use strict';

// MODULES //

var bufferCtors = require( '@stdlib/types/ndarray/base/buffer-ctors' );


// VARIABLES //

var MAX_FAST_ELEMENTS_LENGTH = 64000;


// MAIN //

/**
* Casts buffer elements by copying those elements to a buffer of another data type.
*
* @private
* @param {(Array|TypedArray|Buffer)} buffer - input buffer
* @param {NonNegativeInteger} len - number of elements to cast
* @param {string} dtype - data type
* @returns {(Array|TypedArray|Buffer)} output buffer
*
* @example
* var b = castBuffer( [ 1.0, 2.0, 3.0 ], 2, 'float64' );
* // returns <Float64Array>[ 1.0, 2.0 ]
*/
function castBuffer( buffer, len, dtype ) {
	/* eslint-disable no-new-cap */
	var ctor;
	var out;
	var i;

	// TODO: move to separate pkg? Yes, because this is not trivial. For performance, need to ensure element access minimizes cache misses. Although, in fairness, we don't need to iterate according to the view. We need to iterate from the perspective of the underlying buffer. Meaning, in this case, we don't need to consider strides. Note, however, if we copy based on the view, then the strides may no longer correspond to the copied buffer (e.g., the original strides indicated to skip elements; in other words, a non-single-segment buffer). The larger question is whether we should copy the view or the entire buffer?

	ctor = bufferCtors( dtype );

	// In some engines, we need to ensure "fast elements" for generic arrays...
	if ( dtype === 'generic' && len > MAX_FAST_ELEMENTS_LENGTH ) {
		out = new ctor( MAX_FAST_ELEMENTS_LENGTH );
		for ( i = 0; i < len; i++ ) {
			out[ i ] = 0; // TODO: index into buffer
		}
		for ( i = MAX_FAST_ELEMENTS_LENGTH; i < len; i++ ) {
			out.push( 0 ); // TODO: index into buffer
		}
	} else {
		out = new ctor( len );
		for ( i = 0; i < len; i++ ) {
			out[ i ] = 0; // TODO: index into buffer
		}
	}
	return out;
} // end FUNCTION castBuffer()


// EXPORTS //

module.exports = castBuffer;

@@ -99,63 +99,72 @@
  );%0A
-%0A%0A// VARIABLES //%0A%0Avar MAX_FAST_ELEMENTS_LENGTH = 64000
+var allocUnsafe = require( '@stdlib/types/buffer/alloc-unsafe' )
 ;%0A%0A%0A
@@ -1361,194 +1361,47 @@
  );%0A
-%0A%09// In some engines, we need to ensure %22fast elements%22 for generic arrays...%0A%09if ( dtype === 'generic' && len %3E MAX_FAST_ELEMENTS_LENGTH ) %7B%0A%09%09out = new ctor( MAX_FAST_ELEMENTS_LENGTH )
+%09if ( dtype === 'generic') %7B%0A%09%09out = %5B%5D
 ;%0A%09%09
@@ -1432,33 +1432,34 @@
 + ) %7B%0A%09%09%09out
-%5B i %5D = 0
+.push( 0 )
 ; // TODO: i
@@ -1484,43 +1484,84 @@
 %09%7D%0A%09
-%09for ( i = MAX_FAST_ELEMENTS_LENGTH
+%7D else if ( dtype === 'binary' ) %7B%0A%09%09out = allocUnsafe( len );%0A%09%09for ( i = 0
 ; i 
@@ -1577,34 +1577,33 @@
 + ) %7B%0A%09%09%09out
-.push( 0 )
+%5B i %5D = 0
 ; // TODO: i

Remove "fast" elements logic