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
#![allow(unstable_name_collisions)]

use std::{
    alloc,
    sync::{atomic::Ordering, Arc},
};

use boa_profiler::Profiler;
use portable_atomic::{AtomicU8, AtomicUsize};

use boa_gc::{Finalize, Trace};
use sptr::Strict;

use crate::{
    builtins::{Array, BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject},
    context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
    js_string,
    object::internal_methods::get_prototype_from_constructor,
    property::Attribute,
    realm::Realm,
    string::common::StaticJsStrings,
    Context, JsArgs, JsData, JsNativeError, JsObject, JsResult, JsString, JsSymbol, JsValue,
};

use super::{get_max_byte_len, utils::copy_shared_to_shared};

/// The internal representation of a `SharedArrayBuffer` object.
///
/// This struct implements `Send` and `Sync`, meaning it can be shared between threads
/// running different JS code at the same time.
#[derive(Debug, Clone, Trace, Finalize, JsData)]
pub struct SharedArrayBuffer {
    // Shared buffers cannot be detached.
    #[unsafe_ignore_trace]
    data: Arc<Inner>,
}

#[derive(Debug, Default)]
struct Inner {
    // Technically we should have an `[[ArrayBufferData]]` internal slot,
    // `[[ArrayBufferByteLengthData]]` and `[[ArrayBufferMaxByteLength]]` slots for growable arrays
    // or `[[ArrayBufferByteLength]]` for fixed arrays, but we can save some work
    // by just using this representation instead.
    //
    // The maximum buffer length is represented by `buffer.len()`, and `current_len` has the current
    // buffer length, or `None` if this is a fixed buffer; in this case, `buffer.len()` will be
    // the true length of the buffer.
    buffer: Box<[AtomicU8]>,
    current_len: Option<AtomicUsize>,
}

impl SharedArrayBuffer {
    /// Creates a `SharedArrayBuffer` with an empty buffer.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            data: Arc::default(),
        }
    }

    /// Gets the length of this `SharedArrayBuffer`.
    pub(crate) fn len(&self, ordering: Ordering) -> usize {
        self.data
            .current_len
            .as_ref()
            .map_or_else(|| self.data.buffer.len(), |len| len.load(ordering))
    }

    /// Gets the inner bytes of this `SharedArrayBuffer`.
    pub(crate) fn bytes(&self, ordering: Ordering) -> &[AtomicU8] {
        &self.data.buffer[..self.len(ordering)]
    }

    /// Gets the inner data of the buffer without accessing the current atomic length.
    #[track_caller]
    pub(crate) fn bytes_with_len(&self, len: usize) -> &[AtomicU8] {
        &self.data.buffer[..len]
    }

    /// Gets a pointer to the internal shared buffer.
    pub(crate) fn as_ptr(&self) -> *const AtomicU8 {
        (*self.data.buffer).as_ptr()
    }

    pub(crate) fn is_fixed_len(&self) -> bool {
        self.data.current_len.is_none()
    }
}

impl IntrinsicObject for SharedArrayBuffer {
    fn init(realm: &Realm) {
        let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init");

        let flag_attributes = Attribute::CONFIGURABLE | Attribute::NON_ENUMERABLE;

        let get_species = BuiltInBuilder::callable(realm, Self::get_species)
            .name(js_string!("get [Symbol.species]"))
            .build();

        let get_byte_length = BuiltInBuilder::callable(realm, Self::get_byte_length)
            .name(js_string!("get byteLength"))
            .build();

        let get_growable = BuiltInBuilder::callable(realm, Self::get_growable)
            .name(js_string!("get growable"))
            .build();

        let get_max_byte_length = BuiltInBuilder::callable(realm, Self::get_max_byte_length)
            .name(js_string!("get maxByteLength"))
            .build();

        BuiltInBuilder::from_standard_constructor::<Self>(realm)
            .static_accessor(
                JsSymbol::species(),
                Some(get_species),
                None,
                Attribute::CONFIGURABLE,
            )
            .accessor(
                js_string!("byteLength"),
                Some(get_byte_length),
                None,
                flag_attributes,
            )
            .accessor(
                js_string!("growable"),
                Some(get_growable),
                None,
                flag_attributes,
            )
            .accessor(
                js_string!("maxByteLength"),
                Some(get_max_byte_length),
                None,
                flag_attributes,
            )
            .method(Self::slice, js_string!("slice"), 2)
            .method(Self::grow, js_string!("grow"), 1)
            .property(
                JsSymbol::to_string_tag(),
                Self::NAME,
                Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
            )
            .build();
    }

    fn get(intrinsics: &Intrinsics) -> JsObject {
        Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
    }
}

impl BuiltInObject for SharedArrayBuffer {
    const NAME: JsString = StaticJsStrings::SHARED_ARRAY_BUFFER;
}

impl BuiltInConstructor for SharedArrayBuffer {
    const LENGTH: usize = 1;

    const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
        StandardConstructors::shared_array_buffer;

    /// `25.1.3.1 SharedArrayBuffer ( length [ , options ] )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-sharedarraybuffer-constructor
    fn constructor(
        new_target: &JsValue,
        args: &[JsValue],
        context: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. If NewTarget is undefined, throw a TypeError exception.
        if new_target.is_undefined() {
            return Err(JsNativeError::typ()
                .with_message("ArrayBuffer.constructor called with undefined new target")
                .into());
        }

        // 2. Let byteLength be ? ToIndex(length).
        let byte_len = args.get_or_undefined(0).to_index(context)?;

        // 3. Let requestedMaxByteLength be ? GetArrayBufferMaxByteLengthOption(options).
        let max_byte_len = get_max_byte_len(args.get_or_undefined(1), context)?;

        // 4. Return ? AllocateSharedArrayBuffer(NewTarget, byteLength, requestedMaxByteLength).
        Ok(Self::allocate(new_target, byte_len, max_byte_len, context)?
            .upcast()
            .into())
    }
}

impl SharedArrayBuffer {
    /// `get SharedArrayBuffer [ @@species ]`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-sharedarraybuffer-@@species
    #[allow(clippy::unnecessary_wraps)]
    fn get_species(this: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
        // 1. Return the this value.
        Ok(this.clone())
    }

    /// `get SharedArrayBuffer.prototype.byteLength`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-get-sharedarraybuffer.prototype.bytelength
    pub(crate) fn get_byte_length(
        this: &JsValue,
        _args: &[JsValue],
        _: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. Let O be the this value.
        // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
        // 3. If IsSharedArrayBuffer(O) is true, throw a TypeError exception.
        let buf = this
            .as_object()
            .and_then(JsObject::downcast_ref::<Self>)
            .ok_or_else(|| {
                JsNativeError::typ()
                    .with_message("SharedArrayBuffer.byteLength called with invalid value")
            })?;

        // 4. Let length be ArrayBufferByteLength(O, seq-cst).
        let len = buf.bytes(Ordering::SeqCst).len() as u64;

        // 5. Return 𝔽(length).
        Ok(len.into())
    }

    /// [`get SharedArrayBuffer.prototype.growable`][spec].
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-get-sharedarraybuffer.prototype.growable
    pub(crate) fn get_growable(
        this: &JsValue,
        _args: &[JsValue],
        _context: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. Let O be the this value.
        // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
        // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception.
        let buf = this
            .as_object()
            .and_then(JsObject::downcast_ref::<Self>)
            .ok_or_else(|| {
                JsNativeError::typ()
                    .with_message("get SharedArrayBuffer.growable called with invalid `this`")
            })?;

        // 4. If IsFixedLengthArrayBuffer(O) is false, return true; otherwise return false.
        Ok(JsValue::from(!buf.is_fixed_len()))
    }

    /// [`get SharedArrayBuffer.prototype.maxByteLength`][spec].
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-get-sharedarraybuffer.prototype.maxbytelength
    pub(crate) fn get_max_byte_length(
        this: &JsValue,
        _args: &[JsValue],
        _context: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. Let O be the this value.
        // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
        // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception.
        let buf = this
            .as_object()
            .and_then(JsObject::downcast_ref::<Self>)
            .ok_or_else(|| {
                JsNativeError::typ()
                    .with_message("get SharedArrayBuffer.maxByteLength called with invalid value")
            })?;

        // 4. If IsFixedLengthArrayBuffer(O) is true, then
        //     a. Let length be O.[[ArrayBufferByteLength]].
        // 5. Else,
        //     a. Let length be O.[[ArrayBufferMaxByteLength]].
        // 6. Return 𝔽(length).
        Ok(buf.data.buffer.len().into())
    }

    /// [`SharedArrayBuffer.prototype.grow ( newLength )`][spec].
    ///
    /// [spec]: https://tc39.es/ecma262/sec-sharedarraybuffer.prototype.grow
    pub(crate) fn grow(
        this: &JsValue,
        args: &[JsValue],
        context: &mut Context,
    ) -> JsResult<JsValue> {
        // 1. Let O be the this value.
        // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception.
        let Some(buf) = this
            .as_object()
            .and_then(|o| o.clone().downcast::<Self>().ok())
        else {
            return Err(JsNativeError::typ()
                .with_message("SharedArrayBuffer.grow called with non-object value")
                .into());
        };

        // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferMaxByteLength]]).
        if buf.borrow().data.is_fixed_len() {
            return Err(JsNativeError::typ()
                .with_message("SharedArrayBuffer.grow: cannot grow a fixed-length buffer")
                .into());
        }

        // 4. Let newByteLength be ? ToIndex(newLength).
        let new_byte_len = args.get_or_undefined(0).to_index(context)?;

        // TODO: 5. Let hostHandled be ? HostGrowSharedArrayBuffer(O, newByteLength).
        // 6. If hostHandled is handled, return undefined.
        // Used in engines to handle WASM buffers in a special way, but we don't
        // have a WASM interpreter in place yet.

        // 7. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
        // 8. Let byteLengthBlock be O.[[ArrayBufferByteLengthData]].
        // 9. Let currentByteLengthRawBytes be GetRawBytesFromSharedBlock(byteLengthBlock, 0, biguint64, true, seq-cst).
        // 10. Let newByteLengthRawBytes be NumericToRawBytes(biguint64, ℤ(newByteLength), isLittleEndian).

        let buf = buf.borrow();
        let buf = &buf.data;

        // d. If newByteLength < currentByteLength or newByteLength > O.[[ArrayBufferMaxByteLength]], throw a RangeError exception.
        // Extracting this condition outside the CAS since throwing early doesn't affect the correct
        // behaviour of the loop.
        if new_byte_len > buf.data.buffer.len() as u64 {
            return Err(JsNativeError::range()
                .with_message(
                    "SharedArrayBuffer.grow: new length cannot be bigger than `maxByteLength`",
                )
                .into());
        }
        let new_byte_len = new_byte_len as usize;

        // If we used let-else above to avoid the expect, we would carry a borrow through the `to_index`
        // call, which could mutably borrow. Another alternative would be to clone the whole
        // `SharedArrayBuffer`, but it's better to avoid contention with the counter in the `Arc` pointer.
        let atomic_len = buf
            .data
            .current_len
            .as_ref()
            .expect("already checked that the buffer is not fixed-length");

        // 11. Repeat,
        //     a. NOTE: This is a compare-and-exchange loop to ensure that parallel, racing grows of the same buffer are
        //        totally ordered, are not lost, and do not silently do nothing. The loop exits if it was able to attempt
        //        to grow uncontended.
        //     b. Let currentByteLength be ℝ(RawBytesToNumeric(biguint64, currentByteLengthRawBytes, isLittleEndian)).
        //     c. If newByteLength = currentByteLength, return undefined.
        //     d. If newByteLength < currentByteLength or newByteLength > O.[[ArrayBufferMaxByteLength]], throw a
        //        RangeError exception.
        //     e. Let byteLengthDelta be newByteLength - currentByteLength.
        //     f. If it is impossible to create a new Shared Data Block value consisting of byteLengthDelta bytes, throw
        //        a RangeError exception.
        //     g. NOTE: No new Shared Data Block is constructed and used here. The observable behaviour of growable
        //        SharedArrayBuffers is specified by allocating a max-sized Shared Data Block at construction time, and
        //        this step captures the requirement that implementations that run out of memory must throw a RangeError.
        //     h. Let readByteLengthRawBytes be AtomicCompareExchangeInSharedBlock(byteLengthBlock, 0, 8,
        //        currentByteLengthRawBytes, newByteLengthRawBytes).
        //     i. If ByteListEqual(readByteLengthRawBytes, currentByteLengthRawBytes) is true, return undefined.
        //     j. Set currentByteLengthRawBytes to readByteLengthRawBytes.

        // We require SEQ-CST operations because readers of the buffer also use SEQ-CST operations.
        atomic_len
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |prev_byte_len| {
                (prev_byte_len <= new_byte_len).then_some(new_byte_len)
            })
            .map_err(|_| {
                JsNativeError::range()
                    .with_message("SharedArrayBuffer.grow: failed to grow buffer to new length")
            })?;

        Ok(JsValue::undefined())
    }

    /// `SharedArrayBuffer.prototype.slice ( start, end )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-sharedarraybuffer.prototype.slice
    fn slice(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
        // 1. Let O be the this value.
        // 2. Perform ? RequireInternalSlot(O, [[ArrayBufferData]]).
        // 3. If IsSharedArrayBuffer(O) is false, throw a TypeError exception.
        let buf = this
            .as_object()
            .and_then(|o| o.clone().downcast::<Self>().ok())
            .ok_or_else(|| {
                JsNativeError::typ()
                    .with_message("SharedArrayBuffer.slice called with invalid `this` value")
            })?;

        // 4. Let len be ArrayBufferByteLength(O, seq-cst).
        let len = buf.borrow().data.len(Ordering::SeqCst);

        // 5. Let relativeStart be ? ToIntegerOrInfinity(start).
        // 6. If relativeStart = -∞, let first be 0.
        // 7. Else if relativeStart < 0, let first be max(len + relativeStart, 0).
        // 8. Else, let first be min(relativeStart, len).
        let first = Array::get_relative_start(context, args.get_or_undefined(0), len as u64)?;

        // 9. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end).
        // 10. If relativeEnd = -∞, let final be 0.
        // 11. Else if relativeEnd < 0, let final be max(len + relativeEnd, 0).
        // 12. Else, let final be min(relativeEnd, len).
        let final_ = Array::get_relative_end(context, args.get_or_undefined(1), len as u64)?;

        // 13. Let newLen be max(final - first, 0).
        let new_len = final_.saturating_sub(first);

        // 14. Let ctor be ? SpeciesConstructor(O, %SharedArrayBuffer%).
        let ctor = buf
            .clone()
            .upcast()
            .species_constructor(StandardConstructors::shared_array_buffer, context)?;

        // 15. Let new be ? Construct(ctor, « 𝔽(newLen) »).
        let new = ctor.construct(&[new_len.into()], Some(&ctor), context)?;

        {
            let buf = buf.borrow();
            let buf = &buf.data;
            // 16. Perform ? RequireInternalSlot(new, [[ArrayBufferData]]).
            // 17. If IsSharedArrayBuffer(new) is false, throw a TypeError exception.
            let new = new.downcast_ref::<Self>().ok_or_else(|| {
                JsNativeError::typ()
                    .with_message("SharedArrayBuffer constructor returned invalid object")
            })?;

            // 18. If new.[[ArrayBufferData]] is O.[[ArrayBufferData]], throw a TypeError exception.
            if std::ptr::eq(buf.as_ptr(), new.as_ptr()) {
                return Err(JsNativeError::typ()
                    .with_message("cannot reuse the same SharedArrayBuffer for a slice operation")
                    .into());
            }

            // 19. If ArrayBufferByteLength(new, seq-cst) < newLen, throw a TypeError exception.
            if (new.len(Ordering::SeqCst) as u64) < new_len {
                return Err(JsNativeError::typ()
                    .with_message("invalid size of constructed SharedArrayBuffer")
                    .into());
            }

            let first = first as usize;
            let new_len = new_len as usize;

            // 20. Let fromBuf be O.[[ArrayBufferData]].
            let from_buf = &buf.bytes_with_len(len)[first..];

            // 21. Let toBuf be new.[[ArrayBufferData]].
            let to_buf = new;

            // Sanity check to ensure there is enough space inside `from_buf` for
            // `new_len` elements.
            debug_assert!(from_buf.len() >= new_len);

            // 22. Perform CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLen).
            // SAFETY: `get_slice_range` will always return indices that are in-bounds.
            // This also means that the newly created buffer will have at least `new_len` elements
            // to write to.
            unsafe { copy_shared_to_shared(from_buf.as_ptr(), to_buf.as_ptr(), new_len) }
        }

        // 23. Return new.
        Ok(new.into())
    }

    /// `AllocateSharedArrayBuffer ( constructor, byteLength [ , maxByteLength ] )`
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-allocatesharedarraybuffer
    pub(crate) fn allocate(
        constructor: &JsValue,
        byte_len: u64,
        max_byte_len: Option<u64>,
        context: &mut Context,
    ) -> JsResult<JsObject<SharedArrayBuffer>> {
        // 1. Let slots be « [[ArrayBufferData]] ».
        // 2. If maxByteLength is present and maxByteLength is not empty, let allocatingGrowableBuffer
        //    be true; otherwise let allocatingGrowableBuffer be false.
        // 3. If allocatingGrowableBuffer is true, then
        //     a. If byteLength > maxByteLength, throw a RangeError exception.
        //     b. Append [[ArrayBufferByteLengthData]] and [[ArrayBufferMaxByteLength]] to slots.
        // 4. Else,
        //     a. Append [[ArrayBufferByteLength]] to slots.
        if let Some(max_byte_len) = max_byte_len {
            if byte_len > max_byte_len {
                return Err(JsNativeError::range()
                    .with_message("`length` cannot be bigger than `maxByteLength`")
                    .into());
            }
        }

        // 5. Let obj be ? OrdinaryCreateFromConstructor(constructor, "%SharedArrayBuffer.prototype%", slots).
        let prototype = get_prototype_from_constructor(
            constructor,
            StandardConstructors::shared_array_buffer,
            context,
        )?;

        // 6. If allocatingGrowableBuffer is true, let allocLength be maxByteLength;
        //    otherwise let allocLength be byteLength.
        let alloc_len = max_byte_len.unwrap_or(byte_len);

        // 7. Let block be ? CreateSharedByteDataBlock(allocLength).
        // 8. Set obj.[[ArrayBufferData]] to block.
        let block = create_shared_byte_data_block(alloc_len, context)?;

        // 9. If allocatingGrowableBuffer is true, then
        // `byte_len` must fit inside an `usize` thanks to the checks inside
        // `create_shared_byte_data_block`.
        // a. Assert: byteLength ≤ maxByteLength.
        // b. Let byteLengthBlock be ? CreateSharedByteDataBlock(8).
        // c. Perform SetValueInBuffer(byteLengthBlock, 0, biguint64, ℤ(byteLength), true, seq-cst).
        // d. Set obj.[[ArrayBufferByteLengthData]] to byteLengthBlock.
        // e. Set obj.[[ArrayBufferMaxByteLength]] to maxByteLength.
        let current_len = max_byte_len.map(|_| AtomicUsize::new(byte_len as usize));

        // 10. Else,
        //     a. Set obj.[[ArrayBufferByteLength]] to byteLength.
        let obj = JsObject::new(
            context.root_shape(),
            prototype,
            Self {
                data: Arc::new(Inner {
                    buffer: block,
                    current_len,
                }),
            },
        );

        // 11. Return obj.
        Ok(obj)
    }
}

/// [`CreateSharedByteDataBlock ( size )`][spec] abstract operation.
///
/// Creates a new `Arc<Vec<AtomicU8>>` that can be used as a backing buffer for a [`SharedArrayBuffer`].
///
/// For more information, check the [spec][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-createsharedbytedatablock
pub(crate) fn create_shared_byte_data_block(
    size: u64,
    context: &mut Context,
) -> JsResult<Box<[AtomicU8]>> {
    if size > context.host_hooks().max_buffer_size(context) {
        return Err(JsNativeError::range()
            .with_message(
                "cannot allocate a buffer that exceeds the maximum buffer size".to_string(),
            )
            .into());
    }

    // 1. Let db be a new Shared Data Block value consisting of size bytes. If it is impossible to
    //    create such a Shared Data Block, throw a RangeError exception.
    let size = size.try_into().map_err(|e| {
        JsNativeError::range().with_message(format!("couldn't allocate the data block: {e}"))
    })?;

    if size == 0 {
        // Must ensure we don't allocate a zero-sized buffer.
        return Ok(Box::default());
    }

    // 2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
    // 3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose
    //    [[AgentSignifier]] is AgentSignifier().
    // 4. Let zero be « 0 ».
    // 5. For each index i of db, do
    //     a. Append WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db,
    //        [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero } to eventsRecord.[[EventList]].
    // 6. Return db.

    // Initializing a boxed slice of atomics is almost impossible using safe code.
    // This replaces that with a simple `alloc` and some casts to convert the allocation
    // to `Box<[AtomicU8]>`.

    let layout = alloc::Layout::array::<AtomicU8>(size).map_err(|e| {
        JsNativeError::range().with_message(format!("couldn't allocate the data block: {e}"))
    })?;

    // SAFETY: We already returned if `size == 0`, making this safe.
    let ptr: *mut AtomicU8 = unsafe { alloc::alloc_zeroed(layout).cast() };

    if ptr.is_null() {
        return Err(JsNativeError::range()
            .with_message("memory allocator failed to allocate buffer")
            .into());
    }

    // SAFETY:
    // - It is ensured by the layout that `buffer` has `size` contiguous elements
    // on its allocation.
    // - The original `ptr` doesn't escape outside this function.
    // - `buffer` is a valid pointer by the null check above.
    let buffer = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(ptr, size)) };

    // Just for good measure, since our implementation depends on having a pointer aligned
    // to the alignment of `u64`.
    // This could be replaced with a custom `Box` implementation, but most architectures
    // already align pointers to 8 bytes, so it's a lot of work for such a small
    // compatibility improvement.
    assert_eq!(buffer.as_ptr().addr() % std::mem::align_of::<u64>(), 0);

    // 3. Return db.
    Ok(buffer)
}