/* Copyright 2017-present Renesas Electronics Corporation and other contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var util = require('util');


isAlignedBuffer = function(arg) {
  return arg instanceof AlignedBuffer;
}


// AlignedBuffer constructor
// [1] new AlignedBuffer(size, alignment)
// [2] new AlignedBuffer(buffer, alignment)
function AlignedBuffer(subject, alignment) {
  if (!isAlignedBuffer(this)) {
    return new AlignedBuffer(subject, alignment);
  }

  if (util.isNumber(subject)) {
    this.length = subject > 0 ? subject >>> 0 : 0;
  } else if (util.isBuffer(subject) || isAlignedBuffer(subject)) {
    this.length = subject.length;
  } else {
    throw new TypeError('Bad arguments: AlignedBuffer(number|Buffer|AlignedBuffer, number)');
  }

  if (util.isNumber(alignment)) {
    this.alignment = alignment;
  } else {
    throw new TypeError('Bad arguments: AlignedBuffer(number|Buffer|AlignedBuffer, number)');
  }

  // 'native' is the aligned_buffer object created via the C API.
  native(this, this.length, alignment);

  if (util.isBuffer(subject)) {
    native.copyFromBuffer(this, subject);
  } else if (isAlignedBuffer(subject)) {
    native.copyFromAlignedBuffer(this, subject);
  }
}


AlignedBuffer.prototype.toBuffer = function(start, end) {
  start = start === undefined ? 0 : ~~start;
  end = end === undefined ? this.length : ~~end;

  return native.toBuffer(this, start, end);
};


AlignedBuffer.isAlignedBuffer = isAlignedBuffer;

global.AlignedBuffer = AlignedBuffer;

module.exports = AlignedBuffer;
module.exports.AlignedBuffer = AlignedBuffer;
