ArrayBufferConstructor.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. define_native_property(vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  25. }
  26. ArrayBufferConstructor::~ArrayBufferConstructor()
  27. {
  28. }
  29. Value ArrayBufferConstructor::call()
  30. {
  31. auto& vm = this->vm();
  32. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.ArrayBuffer);
  33. return {};
  34. }
  35. Value ArrayBufferConstructor::construct(Function&)
  36. {
  37. auto& vm = this->vm();
  38. auto byte_length = vm.argument(0).to_index(global_object());
  39. if (vm.exception()) {
  40. if (vm.exception()->value().is_object() && is<RangeError>(vm.exception()->value().as_object())) {
  41. // Re-throw more specific RangeError
  42. vm.clear_exception();
  43. vm.throw_exception<RangeError>(global_object(), ErrorType::InvalidLength, "array buffer");
  44. }
  45. return {};
  46. }
  47. return ArrayBuffer::create(global_object(), byte_length);
  48. }
  49. JS_DEFINE_NATIVE_FUNCTION(ArrayBufferConstructor::is_view)
  50. {
  51. auto arg = vm.argument(0);
  52. if (!arg.is_object())
  53. return Value(false);
  54. if (arg.as_object().is_typed_array())
  55. return Value(true);
  56. // FIXME: Check for DataView as well
  57. return Value(false);
  58. }
  59. JS_DEFINE_NATIVE_GETTER(ArrayBufferConstructor::symbol_species_getter)
  60. {
  61. return vm.this_value(global_object);
  62. }
  63. }