ArrayBufferConstructor.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // Re-throw more specific RangeError
  41. vm.clear_exception();
  42. vm.throw_exception<RangeError>(global_object(), ErrorType::InvalidLength, "array buffer");
  43. return {};
  44. }
  45. return ArrayBuffer::create(global_object(), byte_length);
  46. }
  47. JS_DEFINE_NATIVE_FUNCTION(ArrayBufferConstructor::is_view)
  48. {
  49. auto arg = vm.argument(0);
  50. if (!arg.is_object())
  51. return Value(false);
  52. if (arg.as_object().is_typed_array())
  53. return Value(true);
  54. // FIXME: Check for DataView as well
  55. return Value(false);
  56. }
  57. JS_DEFINE_NATIVE_GETTER(ArrayBufferConstructor::symbol_species_getter)
  58. {
  59. return vm.this_value(global_object);
  60. }
  61. }