ArrayBufferConstructor.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/ArrayBuffer.h>
  7. #include <LibJS/Runtime/ArrayBufferConstructor.h>
  8. #include <LibJS/Runtime/Error.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/TypedArray.h>
  11. namespace JS {
  12. ArrayBufferConstructor::ArrayBufferConstructor(GlobalObject& global_object)
  13. : NativeFunction(vm().names.ArrayBuffer, *global_object.function_prototype())
  14. {
  15. }
  16. void ArrayBufferConstructor::initialize(GlobalObject& global_object)
  17. {
  18. auto& vm = this->vm();
  19. NativeFunction::initialize(global_object);
  20. u8 attr = Attribute::Writable | Attribute::Configurable;
  21. define_property(vm.names.prototype, global_object.array_buffer_prototype(), 0);
  22. define_property(vm.names.length, Value(1), Attribute::Configurable);
  23. define_native_function(vm.names.isView, is_view, 1, attr);
  24. }
  25. ArrayBufferConstructor::~ArrayBufferConstructor()
  26. {
  27. }
  28. Value ArrayBufferConstructor::call()
  29. {
  30. auto& vm = this->vm();
  31. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.ArrayBuffer);
  32. return {};
  33. }
  34. Value ArrayBufferConstructor::construct(Function&)
  35. {
  36. auto& vm = this->vm();
  37. auto byte_length = vm.argument(0).to_index(global_object());
  38. if (vm.exception()) {
  39. // Re-throw more specific RangeError
  40. vm.clear_exception();
  41. vm.throw_exception<RangeError>(global_object(), ErrorType::InvalidLength, "array buffer");
  42. return {};
  43. }
  44. return ArrayBuffer::create(global_object(), byte_length);
  45. }
  46. JS_DEFINE_NATIVE_FUNCTION(ArrayBufferConstructor::is_view)
  47. {
  48. auto arg = vm.argument(0);
  49. if (!arg.is_object())
  50. return Value(false);
  51. if (arg.as_object().is_typed_array())
  52. return Value(true);
  53. // FIXME: Check for DataView as well
  54. return Value(false);
  55. }
  56. }