Skip to content
This repository
tree: ac17dc1764
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 856 lines (706 sloc) 30.919 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
// V8 Typed Array implementation.
// (c) Dean McNamee <dean@gmail.com>, 2011.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include <stdlib.h> // calloc, etc
#include <string.h> // memmove

#include "v8_typed_array.h"
#include "node_buffer.h"
#include "node.h"
#include "v8.h"

namespace {

using node::ThrowRangeError;
using node::ThrowTypeError;
using node::ThrowError;

int SizeOfArrayElementForType(v8::ExternalArrayType type) {
  switch (type) {
    case v8::kExternalByteArray:
    case v8::kExternalUnsignedByteArray:
      return 1;
    case v8::kExternalShortArray:
    case v8::kExternalUnsignedShortArray:
      return 2;
    case v8::kExternalIntArray:
    case v8::kExternalUnsignedIntArray:
    case v8::kExternalFloatArray:
      return 4;
    case v8::kExternalDoubleArray:
      return 8;
    default:
      return 0;
  }
}

struct BatchedMethods {
  const char* name;
  v8::Handle<v8::Value> (*func)(const v8::Arguments& args);
};

class ArrayBuffer {
 public:
  static v8::Persistent<v8::FunctionTemplate> GetTemplate() {
    static v8::Persistent<v8::FunctionTemplate> ft_cache;
    if (!ft_cache.IsEmpty())
      return ft_cache;

    v8::HandleScope scope;
    ft_cache = v8::Persistent<v8::FunctionTemplate>::New(
        v8::FunctionTemplate::New(&ArrayBuffer::V8New));
    ft_cache->SetClassName(v8::String::New("ArrayBuffer"));
    v8::Local<v8::ObjectTemplate> instance = ft_cache->InstanceTemplate();
    instance->SetInternalFieldCount(1); // Buffer.

    return ft_cache;
  }

  static bool HasInstance(v8::Handle<v8::Value> value) {
    return GetTemplate()->HasInstance(value);
  }

 private:
  static void WeakCallback(v8::Persistent<v8::Value> value, void* data) {
    v8::Object* obj = v8::Object::Cast(*value);

    void* ptr = obj->GetIndexedPropertiesExternalArrayData();
    int element_size = SizeOfArrayElementForType(
        obj->GetIndexedPropertiesExternalArrayDataType());
    int size =
        obj->GetIndexedPropertiesExternalArrayDataLength() * element_size;

    v8::V8::AdjustAmountOfExternalAllocatedMemory(-size);

    value.ClearWeak();
    value.Dispose();

    free(ptr);
  }

  static v8::Handle<v8::Value> V8New(const v8::Arguments& args) {
    if (!args.IsConstructCall())
      return ThrowTypeError("Constructor cannot be called as a function.");

    // To match Chrome, we allow "new ArrayBuffer()".
    // if (args.Length() != 1)
    // return ThrowError("Wrong number of arguments.");

    if (args[0]->Int32Value() < 0) {
      return ThrowRangeError("ArrayBufferView size is not a small enough "
                             "positive integer.");
    }

    size_t num_bytes = args[0]->Uint32Value();
    if (num_bytes > node::Buffer::kMaxLength) {
      return ThrowRangeError("length > kMaxLength");
    }

    void* buf = calloc(num_bytes, 1);
    if (!buf)
      return ThrowError("Unable to allocate ArrayBuffer.");

    args.This()->SetPointerInInternalField(0, buf);

    args.This()->Set(v8::String::New("byteLength"),
                     v8::Integer::NewFromUnsigned(num_bytes),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));

    // NOTE(deanm): This is not in the spec, you shouldn't be able to index
    // the ArrayBuffer. However, it currently simplifies some handling in our
    // implementation, so we make ArrayView operator[] act like an Uint8Array.
    // , This allows DataView to work with both ArrayBuffers and TypedArrays.
    args.This()->SetIndexedPropertiesToExternalArrayData(
        buf, v8::kExternalUnsignedByteArray, num_bytes);

    v8::V8::AdjustAmountOfExternalAllocatedMemory(num_bytes);

    v8::Persistent<v8::Object> persistent =
        v8::Persistent<v8::Object>::New(args.This());
    persistent.MakeWeak(NULL, &ArrayBuffer::WeakCallback);

    return args.This();
  }
};

static bool checkAlignment(size_t val, unsigned int bytes) {
  return (val & (bytes - 1)) == 0; // Handles bytes == 0.
}

template <unsigned int TBytes, v8::ExternalArrayType TEAType>
class TypedArray {
 public:
  static v8::Persistent<v8::FunctionTemplate> GetTemplate() {
    static v8::Persistent<v8::FunctionTemplate> ft_cache;
    if (!ft_cache.IsEmpty())
      return ft_cache;

    v8::HandleScope scope;
    ft_cache = v8::Persistent<v8::FunctionTemplate>::New(
        v8::FunctionTemplate::New(&TypedArray<TBytes, TEAType>::V8New));
    ft_cache->SetClassName(v8::String::New(TypeName()));
    v8::Local<v8::ObjectTemplate> instance = ft_cache->InstanceTemplate();
    instance->SetInternalFieldCount(0);

    ft_cache->Set(v8::String::New("BYTES_PER_ELEMENT"),
                  v8::Uint32::New(TBytes), v8::ReadOnly);
    instance->Set(v8::String::New("BYTES_PER_ELEMENT"),
                  v8::Uint32::New(TBytes), v8::ReadOnly);

    v8::Local<v8::Signature> default_signature = v8::Signature::New(ft_cache);

    static BatchedMethods methods[] = {
      { "get", &TypedArray<TBytes, TEAType>::get },
      { "set", &TypedArray<TBytes, TEAType>::set },
      { "slice", &TypedArray<TBytes, TEAType>::subarray },
      { "subarray", &TypedArray<TBytes, TEAType>::subarray },
    };

    for (size_t i = 0; i < sizeof(methods) / sizeof(*methods); ++i) {
      instance->Set(v8::String::New(methods[i].name),
                    v8::FunctionTemplate::New(methods[i].func,
                                              v8::Handle<v8::Value>(),
                                              default_signature));
    }

    return ft_cache;
  }

  static bool HasInstance(v8::Handle<v8::Value> value) {
    return GetTemplate()->HasInstance(value);
  }

 private:
  static v8::Handle<v8::Value> V8New(const v8::Arguments& args) {
    if (!args.IsConstructCall())
      return ThrowTypeError("Constructor cannot be called as a function.");

    // To match Chrome, we allow "new Float32Array()".
    // if (args.Length() != 1)
    // return ThrowError("Wrong number of arguments.");

    v8::Local<v8::Object> buffer;
    unsigned int length = 0;
    unsigned int byte_offset = 0;

    // [m1k3] added support for Buffer constructor
    if (node::Buffer::HasInstance(args[0])
        || ArrayBuffer::HasInstance(args[0])) { // ArrayBuffer constructor.
      buffer = v8::Local<v8::Object>::Cast(args[0]);
      size_t buflen =
          buffer->GetIndexedPropertiesExternalArrayDataLength();

      if (!args[1]->IsUndefined() && args[1]->Int32Value() < 0)
        return ThrowRangeError("Byte offset out of range.");
      byte_offset = args[1]->IsUndefined() ? 0 : args[1]->Uint32Value();

      if (args.Length() > 2) {
        if (args[2]->Int32Value() < 0)
          return ThrowRangeError("Length out of range.");
        length = args[2]->Uint32Value();
      } else {
        if (buflen < byte_offset ||
            !checkAlignment(buflen - byte_offset, TBytes)) {
          return ThrowRangeError("Byte offset / length is not aligned.");
        }
        length = (buflen - byte_offset) / TBytes;
      }

      // NOTE(deanm): Sloppy integer overflow checks.
      if (byte_offset > buflen || byte_offset + length > buflen ||
          byte_offset + length * TBytes > buflen) {
        return ThrowRangeError("Length is out of range.");
      }

      void* buf = buffer->GetIndexedPropertiesExternalArrayData();
      char* begin = reinterpret_cast<char*>(buf) + byte_offset;

      if (!checkAlignment(reinterpret_cast<uintptr_t>(begin), TBytes))
        return ThrowRangeError("Byte offset is not aligned.");

      args.This()->SetIndexedPropertiesToExternalArrayData(
        begin, TEAType, length);
    }
    else if (args[0]->IsObject()) { // TypedArray / type[] constructor.
      v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(args[0]);
      length = obj->Get(v8::String::New("length"))->Uint32Value();

      // TODO(deanm): Handle integer overflow.
      v8::Local<v8::Value> argv[1] = {
          v8::Integer::NewFromUnsigned(length * TBytes)};
      buffer = ArrayBuffer::GetTemplate()->
                 GetFunction()->NewInstance(1, argv);
      if (buffer.IsEmpty()) return v8::Undefined(); // constructor failed

      void* buf = buffer->GetPointerFromInternalField(0);
      args.This()->SetIndexedPropertiesToExternalArrayData(
          buf, TEAType, length);
      // TODO(deanm): check for failure.
      for (uint32_t i = 0; i < length; ++i) {
        // Use the v8 setter to deal with typing. Maybe slow?
        args.This()->Set(i, obj->Get(i));
      }
    } else { // length constructor.
      // Try to match Chrome, Float32Array(""), Float32Array(true/false) is
      // okay, but Float32Array(null) throws a TypeError and
      // Float32Array(undefined) throw a RangeError.
      if (args.Length() > 0 && (args[0]->IsUndefined() || args[0]->IsNull()))
        return ThrowTypeError("Type error");

      if (args[0]->Int32Value() < 0) {
        return ThrowRangeError("ArrayBufferView size is not a small enough "
                               "positive integer.");
      }

      length = args[0]->Uint32Value();
      // TODO(deanm): Handle integer overflow.
      v8::Local<v8::Value> argv[1] = {
          v8::Integer::NewFromUnsigned(length * TBytes)};

      buffer = ArrayBuffer::GetTemplate()->
                 GetFunction()->NewInstance(1, argv);
      if (buffer.IsEmpty()) return v8::Undefined(); // constructor failed

      void* buf = buffer->GetPointerFromInternalField(0);
      args.This()->SetIndexedPropertiesToExternalArrayData(
          buf, TEAType, length);
      // TODO(deanm): check for failure.
    }

    args.This()->Set(v8::String::New("buffer"),
                     buffer,
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    args.This()->Set(v8::String::New("length"),
                     v8::Integer::NewFromUnsigned(length),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    args.This()->Set(v8::String::New("byteOffset"),
                     v8::Integer::NewFromUnsigned(byte_offset),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    args.This()->Set(v8::String::New("byteLength"),
                     v8::Integer::NewFromUnsigned(length * TBytes),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));

    return args.This();
  }

  static v8::Handle<v8::Value> get(const v8::Arguments& args) {
    if (args.Length() < 1)
      return ThrowError("Wrong number of arguments.");

    if (args[0]->IsNumber()) {
      unsigned int index = args[0]->Uint32Value();
      void* ptr = args.This()->GetIndexedPropertiesExternalArrayData();

      if (TEAType == v8::kExternalByteArray)
        return v8::Integer::New(reinterpret_cast<char*>(ptr)[index]);
      else if (TEAType == v8::kExternalUnsignedByteArray)
        return v8::Integer::New(reinterpret_cast<unsigned char*>(ptr)[index]);
      else if (TEAType == v8::kExternalShortArray)
        return v8::Integer::New(reinterpret_cast<short*>(ptr)[index]);
      else if (TEAType == v8::kExternalUnsignedShortArray)
        return v8::Integer::New(reinterpret_cast<unsigned short*>(ptr)[index]);
      else if (TEAType == v8::kExternalIntArray)
        return v8::Integer::New(reinterpret_cast<int*>(ptr)[index]);
      else if (TEAType == v8::kExternalUnsignedIntArray)
        return v8::Integer::New(reinterpret_cast<unsigned int*>(ptr)[index]);
      else if (TEAType == v8::kExternalFloatArray)
        return v8::Number::New(reinterpret_cast<float*>(ptr)[index]);
      else if (TEAType == v8::kExternalDoubleArray)
        return v8::Number::New(reinterpret_cast<double*>(ptr)[index]);
    }
    return v8::Undefined();
  }

  static v8::Handle<v8::Value> set(const v8::Arguments& args) {
    if (args.Length() < 1)
      return ThrowError("Wrong number of arguments.");

    //if (!args[0]->IsObject())
    // return ThrowTypeError("Type error.");

    if (args[0]->IsNumber()) {
      // index, <type> value
      unsigned int index = args[0]->Uint32Value();
      void* ptr = args.This()->GetIndexedPropertiesExternalArrayData();
      if (TEAType == v8::kExternalByteArray)
        reinterpret_cast<char*>(ptr)[index] = (char) args[1]->Int32Value();
      else if (TEAType == v8::kExternalUnsignedByteArray)
        reinterpret_cast<unsigned char*>(ptr)[index] =
            (unsigned char) args[1]->Int32Value();
      else if (TEAType == v8::kExternalShortArray)
        reinterpret_cast<short*>(ptr)[index] = (short) args[1]->Int32Value();
      else if (TEAType == v8::kExternalUnsignedShortArray)
        reinterpret_cast<unsigned short*>(ptr)[index] =
            (unsigned short) args[1]->Int32Value();
      else if (TEAType == v8::kExternalIntArray)
        reinterpret_cast<int*>(ptr)[index] = (int) args[1]->Int32Value();
      else if (TEAType == v8::kExternalUnsignedIntArray)
        reinterpret_cast<unsigned int*>(ptr)[index] =
            (unsigned int) args[1]->Int32Value();
      else if (TEAType == v8::kExternalFloatArray)
        reinterpret_cast<float*>(ptr)[index] = (float) args[1]->NumberValue();
      else if (TEAType == v8::kExternalDoubleArray)
        reinterpret_cast<double*>(ptr)[index] = (double) args[1]->NumberValue();
      else if (TEAType == v8::kExternalPixelArray) {
        int value = args[1]->Int32Value();
        if (value < 0)
          value = 0;
        else if (value > 255)
          value = 255;
        reinterpret_cast<unsigned char*>(ptr)[index] =
            (unsigned char) value;
      }
    } else if (args[0]->IsObject()) {
      v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(args[0]);

      if (TypedArray<TBytes, TEAType>::HasInstance(obj)) { // ArrayBufferView.
        if (args[1]->Int32Value() < 0)
          return ThrowRangeError("Offset may not be negative.");

        unsigned int offset = args[1]->Uint32Value();
        unsigned int src_length =
            obj->Get(v8::String::New("length"))->Uint32Value();
        unsigned int dst_length =
            args.This()->Get(v8::String::New("length"))->Uint32Value();
        if (offset > dst_length)
          return ThrowRangeError("Offset out of range.");

        if (src_length > dst_length - offset)
          return ThrowRangeError("Offset/length out of range.");

        // We don't want to get the buffer pointer, because that means we'll have
        // to just do the calculations for byteOffset / byteLength again.
        // Instead just use the pointer on the external array data.
        void* src_ptr = obj->GetIndexedPropertiesExternalArrayData();
        void* dst_ptr = args.This()->GetIndexedPropertiesExternalArrayData();

        // From the spec:
        // If the input array is a TypedArray, the two arrays may use the same
        // underlying ArrayBuffer. In this situation, setting the values takes
        // place as if all the data is first copied into a temporary buffer that
        // does not overlap either of the arrays, and then the data from the
        // temporary buffer is copied into the current array.
        memmove(reinterpret_cast<char*>(dst_ptr) + offset * TBytes, src_ptr,
            src_length * TBytes);
      } else { // type[]
        if (args[1]->Int32Value() < 0)
          return ThrowRangeError("Offset may not be negative.");

        unsigned int src_length =
            obj->Get(v8::String::New("length"))->Uint32Value();
        unsigned int dst_length =
            args.This()->Get(v8::String::New("length"))->Uint32Value();
        unsigned int offset = args[1]->Uint32Value();

        if (offset > dst_length)
          return ThrowRangeError("Offset out of range.");

        if (src_length > dst_length - offset)
          return ThrowRangeError("Offset/length out of range.");

        for (uint32_t i = 0; i < src_length; ++i) {
          // Use the v8 setter to deal with typing. Maybe slow?
          args.This()->Set(i + offset, obj->Get(i));
        }
      }
    }

    return v8::Undefined();
  }

  static v8::Handle<v8::Value> subarray(const v8::Arguments& args) {
    // TODO(deanm): The unsigned / signed type mixing makes me super nervous.

    unsigned int length =
        args.This()->Get(v8::String::New("length"))->Uint32Value();
    int begin = args[0]->Int32Value();
    int end = length;
    if (args.Length() > 1)
      end = args[1]->Int32Value();

    if (begin < 0) begin = length + begin;
    if (begin < 0) begin = 0;
    if ((unsigned)begin > length) begin = length;

    if (end < 0) end = length + end;
    if (end < 0) end = 0;
    if ((unsigned)end > length) end = length;

    if (begin > end) begin = end;

    int byte_offset = begin * TBytes +
        args.This()->Get(v8::String::New("byteOffset"))->Uint32Value();

    // Call through to the ArrayBuffer, byteOffset, length constructor.
    v8::Local<v8::Value> argv[] = {
        args.This()->Get(v8::String::New("buffer")),
        v8::Integer::New(byte_offset),
        v8::Integer::New(end - begin)};
    return TypedArray<TBytes, TEAType>::GetTemplate()->
        GetFunction()->NewInstance(3, argv);
  }

  static const char* TypeName() {
    switch (TEAType) {
      case v8::kExternalByteArray: return "Int8Array";
      case v8::kExternalUnsignedByteArray: return "Uint8Array";
      case v8::kExternalShortArray: return "Int16Array";
      case v8::kExternalUnsignedShortArray: return "Uint16Array";
      case v8::kExternalIntArray: return "Int32Array";
      case v8::kExternalUnsignedIntArray: return "Uint32Array";
      case v8::kExternalFloatArray: return "Float32Array";
      case v8::kExternalDoubleArray: return "Float64Array";
      case v8::kExternalPixelArray: return "Uint8ClampedArray";
    }
    abort();
    // Please the compiler
    return "";
  }
};

class Int8Array : public TypedArray<1, v8::kExternalByteArray> { };
class Uint8Array : public TypedArray<1, v8::kExternalUnsignedByteArray> { };
class Uint8ClampedArray : public TypedArray<1, v8::kExternalPixelArray> { };
class Int16Array : public TypedArray<2, v8::kExternalShortArray> { };
class Uint16Array : public TypedArray<2, v8::kExternalUnsignedShortArray> { };
class Int32Array : public TypedArray<4, v8::kExternalIntArray> { };
class Uint32Array : public TypedArray<4, v8::kExternalUnsignedIntArray> { };
class Float32Array : public TypedArray<4, v8::kExternalFloatArray> { };
class Float64Array : public TypedArray<8, v8::kExternalDoubleArray> { };

template <typename T>
v8::Handle<v8::Value> cTypeToValue(T) {
  return v8::Undefined();
}

template <>
v8::Handle<v8::Value> cTypeToValue(unsigned char val) {
  return v8::Integer::NewFromUnsigned(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(char val) {
  return v8::Integer::New(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(unsigned short val) {
  return v8::Integer::NewFromUnsigned(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(short val) {
  return v8::Integer::New(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(unsigned int val) {
  return v8::Integer::NewFromUnsigned(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(int val) {
  return v8::Integer::New(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(float val) {
  return v8::Number::New(val);
}

template <>
v8::Handle<v8::Value> cTypeToValue(double val) {
  return v8::Number::New(val);
}


template <typename T>
T valueToCType(v8::Handle<v8::Value> value) {
  return 0;
}

template <>
unsigned char valueToCType(v8::Handle<v8::Value> value) {
  return value->Uint32Value();
}

template <>
char valueToCType(v8::Handle<v8::Value> value) {
  return value->Int32Value();
}

template <>
unsigned short valueToCType(v8::Handle<v8::Value> value) {
  return value->Uint32Value();
}

template <>
short valueToCType(v8::Handle<v8::Value> value) {
  return value->Int32Value();
}

template <>
unsigned int valueToCType(v8::Handle<v8::Value> value) {
  return value->Uint32Value();
}

template <>
int valueToCType(v8::Handle<v8::Value> value) {
  return value->Int32Value();
}

template <>
float valueToCType(v8::Handle<v8::Value> value) {
  return static_cast<float>(value->NumberValue());
}

template <>
double valueToCType(v8::Handle<v8::Value> value) {
  return value->NumberValue();
}


class DataView {
 public:
  static v8::Persistent<v8::FunctionTemplate> GetTemplate() {
    static v8::Persistent<v8::FunctionTemplate> ft_cache;
    if (!ft_cache.IsEmpty())
      return ft_cache;

    v8::HandleScope scope;
    ft_cache = v8::Persistent<v8::FunctionTemplate>::New(
        v8::FunctionTemplate::New(&DataView::V8New));
    ft_cache->SetClassName(v8::String::New("DataView"));
    v8::Local<v8::ObjectTemplate> instance = ft_cache->InstanceTemplate();
    instance->SetInternalFieldCount(0);

    v8::Local<v8::Signature> default_signature = v8::Signature::New(ft_cache);

    static BatchedMethods methods[] = {
      { "getUint8", &DataView::getUint8 },
      { "getInt8", &DataView::getInt8 },
      { "getUint16", &DataView::getUint16 },
      { "getInt16", &DataView::getInt16 },
      { "getUint32", &DataView::getUint32 },
      { "getInt32", &DataView::getInt32 },
      { "getFloat32", &DataView::getFloat32 },
      { "getFloat64", &DataView::getFloat64 },
      { "setUint8", &DataView::setUint8 },
      { "setInt8", &DataView::setInt8 },
      { "setUint16", &DataView::setUint16 },
      { "setInt16", &DataView::setInt16 },
      { "setUint32", &DataView::setUint32 },
      { "setInt32", &DataView::setInt32 },
      { "setFloat32", &DataView::setFloat32 },
      { "setFloat64", &DataView::setFloat64 },
    };

    for (size_t i = 0; i < sizeof(methods) / sizeof(*methods); ++i) {
      instance->Set(v8::String::New(methods[i].name),
                    v8::FunctionTemplate::New(methods[i].func,
                                              v8::Handle<v8::Value>(),
                                              default_signature));
    }

    return ft_cache;
  }

  static bool HasInstance(v8::Handle<v8::Value> value) {
    return GetTemplate()->HasInstance(value);
  }

 private:
  static v8::Handle<v8::Value> V8New(const v8::Arguments& args) {
    if (!args.IsConstructCall())
      return ThrowTypeError("Constructor cannot be called as a function.");

    if (args.Length() < 1)
      return ThrowError("Wrong number of arguments.");

    if (!args[0]->IsObject())
      return ThrowError("Object must be an ArrayBuffer.");

    v8::Handle<v8::Object> buffer = v8::Handle<v8::Object>::Cast(args[0]);
    if (!buffer->HasIndexedPropertiesInExternalArrayData())
      return ThrowError("Object must be an ArrayBuffer.");

    unsigned int byte_length =
        buffer->GetIndexedPropertiesExternalArrayDataLength();
    unsigned int byte_offset =
        args[1]->IsUndefined() ? 0 : args[1]->Uint32Value();

    if (args[1]->Int32Value() < 0 || byte_offset >= byte_length)
      return ThrowRangeError("byteOffset out of range.");

    if (!args[2]->IsUndefined()) {
      if (args[2]->Int32Value() < 0)
        return ThrowRangeError("byteLength out of range.");
      unsigned int new_byte_length = args[2]->Uint32Value();
      if (new_byte_length > byte_length)
        return ThrowRangeError("byteLength out of range.");
      if (byte_offset + new_byte_length > byte_length)
        return ThrowRangeError("byteOffset/byteLength out of range.");
      byte_length = new_byte_length;
    } else {
      // Adjust the original byte_length from total length to length to end.
      byte_length -= byte_offset;
    }

    void* buf = buffer->GetIndexedPropertiesExternalArrayData();

    // Like ArrayBuffer, we violate the spec and add an operator[].
    args.This()->SetIndexedPropertiesToExternalArrayData(
        reinterpret_cast<char*>(buf) + byte_offset,
        v8::kExternalUnsignedByteArray, byte_length);

    args.This()->Set(v8::String::New("buffer"),
                     buffer,
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    args.This()->Set(v8::String::New("byteOffset"),
                     v8::Integer::NewFromUnsigned(byte_offset),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    args.This()->Set(v8::String::New("byteLength"),
                     v8::Integer::NewFromUnsigned(byte_length),
                     (v8::PropertyAttribute)(v8::ReadOnly|v8::DontDelete));
    return args.This();
  }

  // TODO(deanm): This isn't beautiful or optimal.
  static void swizzle(char* buf, size_t len) {
    for (size_t i = 0; i < len / 2; ++i) {
      char t = buf[i];
      buf[i] = buf[len - i - 1];
      buf[len - i - 1] = t;
    }
  }

  template <typename T>
  static T getValue(void* ptr, unsigned int index, bool swiz) {
    char buf[sizeof(T)];
    memcpy(buf, reinterpret_cast<char*>(ptr) + index, sizeof(T));
    if (swiz)
      swizzle(buf, sizeof(T));
    T val;
    memcpy(&val, buf, sizeof(T));
    return val;
  }

  template <typename T>
  static void setValue(void* ptr, unsigned int index, T val, bool swiz) {
    char buf[sizeof(T)];
    memcpy(buf, &val, sizeof(T));
    if (swiz)
      swizzle(buf, sizeof(T));
    memcpy(reinterpret_cast<char*>(ptr) + index, buf, sizeof(T));
  }

  template <typename T>
  static v8::Handle<v8::Value> getGeneric(const v8::Arguments& args) {
    if (args.Length() < 1)
      return ThrowError("Wrong number of arguments.");

    unsigned int index = args[0]->Uint32Value();
    bool little_endian = args[1]->BooleanValue();
    // TODO(deanm): All of these things should be cacheable.
    int element_size = SizeOfArrayElementForType(
        args.This()->GetIndexedPropertiesExternalArrayDataType());
    int size = args.This()->GetIndexedPropertiesExternalArrayDataLength() *
               element_size;

    if (index + sizeof(T) > (unsigned)size) // TODO(deanm): integer overflow.
      return ThrowError("Index out of range.");

    void* ptr = args.This()->GetIndexedPropertiesExternalArrayData();
    return cTypeToValue<T>(getValue<T>(ptr, index, !little_endian));
  }

  template <typename T>
  static v8::Handle<v8::Value> setGeneric(const v8::Arguments& args) {
    if (args.Length() < 2)
      return ThrowError("Wrong number of arguments.");

    unsigned int index = args[0]->Int32Value();
    bool little_endian = args[2]->BooleanValue();
    // TODO(deanm): All of these things should be cacheable.
    int element_size = SizeOfArrayElementForType(
        args.This()->GetIndexedPropertiesExternalArrayDataType());
    int size = args.This()->GetIndexedPropertiesExternalArrayDataLength() *
               element_size;

    if (index + sizeof(T) > (unsigned)size) // TODO(deanm): integer overflow.
      return ThrowError("Index out of range.");

    void* ptr = args.This()->GetIndexedPropertiesExternalArrayData();
    setValue<T>(ptr, index, valueToCType<T>(args[1]), !little_endian);
    return v8::Undefined();
  }

  static v8::Handle<v8::Value> getUint8(const v8::Arguments& args) {
    return getGeneric<unsigned char>(args);
  }

  static v8::Handle<v8::Value> getInt8(const v8::Arguments& args) {
    return getGeneric<char>(args);
  }

  static v8::Handle<v8::Value> getUint16(const v8::Arguments& args) {
    return getGeneric<unsigned short>(args);
  }

  static v8::Handle<v8::Value> getInt16(const v8::Arguments& args) {
    return getGeneric<short>(args);
  }

  static v8::Handle<v8::Value> getUint32(const v8::Arguments& args) {
    return getGeneric<unsigned int>(args);
  }

  static v8::Handle<v8::Value> getInt32(const v8::Arguments& args) {
    return getGeneric<int>(args);
  }

  static v8::Handle<v8::Value> getFloat32(const v8::Arguments& args) {
    return getGeneric<float>(args);
  }

  static v8::Handle<v8::Value> getFloat64(const v8::Arguments& args) {
    return getGeneric<double>(args);
  }

  static v8::Handle<v8::Value> setUint8(const v8::Arguments& args) {
    return setGeneric<unsigned char>(args);
  }

  static v8::Handle<v8::Value> setInt8(const v8::Arguments& args) {
    return setGeneric<char>(args);
  }

  static v8::Handle<v8::Value> setUint16(const v8::Arguments& args) {
    return setGeneric<unsigned short>(args);
  }

  static v8::Handle<v8::Value> setInt16(const v8::Arguments& args) {
    return setGeneric<short>(args);
  }

  static v8::Handle<v8::Value> setUint32(const v8::Arguments& args) {
    return setGeneric<unsigned int>(args);
  }

  static v8::Handle<v8::Value> setInt32(const v8::Arguments& args) {
    return setGeneric<int>(args);
  }

  static v8::Handle<v8::Value> setFloat32(const v8::Arguments& args) {
    return setGeneric<float>(args);
  }

  static v8::Handle<v8::Value> setFloat64(const v8::Arguments& args) {
    return setGeneric<double>(args);
  }
};


} // namespace

namespace v8_typed_array {

void AttachBindings(v8::Handle<v8::Object> obj) {
  v8::HandleScope scope;

  obj->Set(v8::String::New("ArrayBuffer"),
           ArrayBuffer::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Int8Array"),
           Int8Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Uint8Array"),
           Uint8Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Uint8ClampedArray"),
           Uint8ClampedArray::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Int16Array"),
           Int16Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Uint16Array"),
           Uint16Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Int32Array"),
           Int32Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Uint32Array"),
           Uint32Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Float32Array"),
           Float32Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("Float64Array"),
           Float64Array::GetTemplate()->GetFunction());
  obj->Set(v8::String::New("DataView"),
           DataView::GetTemplate()->GetFunction());
}

} // namespace v8_typed_array

NODE_MODULE(node_typed_array, v8_typed_array::AttachBindings)
Something went wrong with that request. Please try again.