25 Structured Data
25.1 ArrayBuffer Objects
25.1.1 Notation
The descriptions below in this section,
A read-modify-write modification function is a mathematical function that is notationally represented as an abstract closure that takes two
- They perform all their algorithm steps atomically.
- Their individual algorithm steps are not observable.
To aid verifying that a read-modify-write modification function's algorithm steps constitute a pure, mathematical function, the following editorial conventions are recommended:
- They do not access, directly or transitively via invoked
abstract operations and abstract closures, any language or specification values except their parameters and captured values. - They do not return
Completion Records .
25.1.2 Abstract Operations For ArrayBuffer Objects
25.1.2.1 AllocateArrayBuffer ( constructor, byteLength )
The abstract operation AllocateArrayBuffer takes arguments constructor and byteLength (a non-negative
- Let obj be ?
OrdinaryCreateFromConstructor (constructor," , « [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] »).%ArrayBuffer.prototype% " - Let block be ?
CreateByteDataBlock (byteLength). - Set obj.[[ArrayBufferData]] to block.
- Set obj.[[ArrayBufferByteLength]] to byteLength.
- Return obj.
25.1.2.2 IsDetachedBuffer ( arrayBuffer )
The abstract operation IsDetachedBuffer takes argument arrayBuffer (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. It performs the following steps when called:
- If arrayBuffer.[[ArrayBufferData]] is
null , returntrue . - Return
false .
25.1.2.3 DetachArrayBuffer ( arrayBuffer [ , key ] )
The abstract operation DetachArrayBuffer takes argument arrayBuffer (an ArrayBuffer) and optional argument key and returns either a
Assert :IsSharedArrayBuffer (arrayBuffer) isfalse .- If key is not present, set key to
undefined . - If
SameValue (arrayBuffer.[[ArrayBufferDetachKey]], key) isfalse , throw aTypeError exception. - Set arrayBuffer.[[ArrayBufferData]] to
null . - Set arrayBuffer.[[ArrayBufferByteLength]] to 0.
- Return
unused .
Detaching an ArrayBuffer instance disassociates the
25.1.2.4 CloneArrayBuffer ( srcBuffer, srcByteOffset, srcLength, cloneConstructor )
The abstract operation CloneArrayBuffer takes arguments srcBuffer (an ArrayBuffer or a SharedArrayBuffer), srcByteOffset (a non-negative
- Let targetBuffer be ?
AllocateArrayBuffer (cloneConstructor, srcLength). - If
IsDetachedBuffer (srcBuffer) istrue , throw aTypeError exception. - Let srcBlock be srcBuffer.[[ArrayBufferData]].
- Let targetBlock be targetBuffer.[[ArrayBufferData]].
- Perform
CopyDataBlockBytes (targetBlock, 0, srcBlock, srcByteOffset, srcLength). - Return targetBuffer.
25.1.2.5 IsUnsignedElementType ( type )
The abstract operation IsUnsignedElementType takes argument type and returns a Boolean. It verifies if the argument type is an unsigned
- If type is
Uint8 ,Uint8C ,Uint16 ,Uint32 , orBigUint64 , returntrue . - Return
false .
25.1.2.6 IsUnclampedIntegerElementType ( type )
The abstract operation IsUnclampedIntegerElementType takes argument type and returns a Boolean. It verifies if the argument type is an
- If type is
Int8 ,Uint8 ,Int16 ,Uint16 ,Int32 , orUint32 , returntrue . - Return
false .
25.1.2.7 IsBigIntElementType ( type )
The abstract operation IsBigIntElementType takes argument type and returns a Boolean. It verifies if the argument type is a BigInt
- If type is
BigUint64 orBigInt64 , returntrue . - Return
false .
25.1.2.8 IsNoTearConfiguration ( type, order )
The abstract operation IsNoTearConfiguration takes arguments type and order and returns a Boolean. It performs the following steps when called:
- If
IsUnclampedIntegerElementType (type) istrue , returntrue . - If
IsBigIntElementType (type) istrue and order is notInit orUnordered , returntrue . - Return
false .
25.1.2.9 RawBytesToNumeric ( type, rawBytes, isLittleEndian )
The abstract operation RawBytesToNumeric takes arguments type (a
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If isLittleEndian is
false , reverse the order of the elements of rawBytes. - If type is
Float32 , then- Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an
IEEE 754-2019 binary32 value. - If value is an
IEEE 754-2019 binary32 NaN value, return theNaN Number value . - Return the
Number value that corresponds to value.
- Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an
- If type is
Float64 , then- Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an
IEEE 754-2019 binary64 value. - If value is an
IEEE 754-2019 binary64 NaN value, return theNaN Number value . - Return the
Number value that corresponds to value.
- Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an
- If
IsUnsignedElementType (type) istrue , then- Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.
- Else,
- Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian two's complement number of bit length elementSize × 8.
- If
IsBigIntElementType (type) istrue , return the BigInt value that corresponds to intValue. - Otherwise, return the
Number value that corresponds to intValue.
25.1.2.10 GetValueFromBuffer ( arrayBuffer, byteIndex, type, isTypedArray, order [ , isLittleEndian ] )
The abstract operation GetValueFromBuffer takes arguments arrayBuffer (an ArrayBuffer or SharedArrayBuffer), byteIndex (a non-negative
Assert :IsDetachedBuffer (arrayBuffer) isfalse .Assert : There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.- Let block be arrayBuffer.[[ArrayBufferData]].
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If
IsSharedArrayBuffer (arrayBuffer) istrue , then- Let execution be the [[CandidateExecution]] field of the
surrounding agent 'sAgent Record . - Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is
AgentSignifier (). - If isTypedArray is
true andIsNoTearConfiguration (type, order) istrue , let noTear betrue ; otherwise let noTear befalse . - Let rawValue be a
List of length elementSize whose elements are nondeterministically chosenbyte values . - NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the
memory model to describe observable behaviour of hardware with weak consistency. - Let readEvent be
ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }. - Append readEvent to eventList.
- Append
Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
- Let execution be the [[CandidateExecution]] field of the
- Else, let rawValue be a
List whose elements are bytes from block at indices byteIndex (inclusive) through byteIndex + elementSize (exclusive). Assert : The number of elements in rawValue is elementSize.- If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Return
RawBytesToNumeric (type, rawValue, isLittleEndian).
25.1.2.11 NumericToRawBytes ( type, value, isLittleEndian )
The abstract operation NumericToRawBytes takes arguments type (a
- If type is
Float32 , then- Let rawBytes be a
List whose elements are the 4 bytes that are the result of converting value toIEEE 754-2019 binary32 format using roundTiesToEven mode. If isLittleEndian isfalse , the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value isNaN , rawBytes may be set to any implementation chosenIEEE 754-2019 binary32 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishableNaN value.
- Let rawBytes be a
- Else if type is
Float64 , then- Let rawBytes be a
List whose elements are the 8 bytes that are theIEEE 754-2019 binary64 format encoding of value. If isLittleEndian isfalse , the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value isNaN , rawBytes may be set to any implementation chosenIEEE 754-2019 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishableNaN value.
- Let rawBytes be a
- Else,
- Let n be the Element Size value specified in
Table 71 for Element Type type. - Let convOp be the abstract operation named in the Conversion Operation column in
Table 71 for Element Type type. - Let intValue be ℝ(convOp(value)).
- If intValue ≥ 0, then
- Let rawBytes be a
List whose elements are the n-byte binary encoding of intValue. If isLittleEndian isfalse , the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
- Let rawBytes be a
- Else,
- Let rawBytes be a
List whose elements are the n-byte binary two's complement encoding of intValue. If isLittleEndian isfalse , the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
- Let rawBytes be a
- Let n be the Element Size value specified in
- Return rawBytes.
25.1.2.12 SetValueInBuffer ( arrayBuffer, byteIndex, type, value, isTypedArray, order [ , isLittleEndian ] )
The abstract operation SetValueInBuffer takes arguments arrayBuffer (an ArrayBuffer or SharedArrayBuffer), byteIndex (a non-negative
Assert :IsDetachedBuffer (arrayBuffer) isfalse .Assert : There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.Assert :Type (value) is BigInt ifIsBigIntElementType (type) istrue ; otherwise,Type (value) is Number.- Let block be arrayBuffer.[[ArrayBufferData]].
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Let rawBytes be
NumericToRawBytes (type, value, isLittleEndian). - If
IsSharedArrayBuffer (arrayBuffer) istrue , then- Let execution be the [[CandidateExecution]] field of the
surrounding agent 'sAgent Record . - Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is
AgentSignifier (). - If isTypedArray is
true andIsNoTearConfiguration (type, order) istrue , let noTear betrue ; otherwise let noTear befalse . - Append
WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
- Let execution be the [[CandidateExecution]] field of the
- Else, store the individual bytes of rawBytes into block, starting at block[byteIndex].
- Return
unused .
25.1.2.13 GetModifySetValueInBuffer ( arrayBuffer, byteIndex, type, value, op [ , isLittleEndian ] )
The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (an ArrayBuffer or a SharedArrayBuffer), byteIndex (a non-negative
Assert :IsDetachedBuffer (arrayBuffer) isfalse .Assert : There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.Assert :Type (value) is BigInt ifIsBigIntElementType (type) istrue ; otherwise,Type (value) is Number.- Let block be arrayBuffer.[[ArrayBufferData]].
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Let rawBytes be
NumericToRawBytes (type, value, isLittleEndian). - If
IsSharedArrayBuffer (arrayBuffer) istrue , then- Let execution be the [[CandidateExecution]] field of the
surrounding agent 'sAgent Record . - Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is
AgentSignifier (). - Let rawBytesRead be a
List of length elementSize whose elements are nondeterministically chosenbyte values . - NOTE: In implementations, rawBytesRead is the result of a load-link, of a load-exclusive, or of an operand of a read-modify-write instruction on the underlying hardware. The nondeterminism is a semantic prescription of the
memory model to describe observable behaviour of hardware with weak consistency. - Let rmwEvent be
ReadModifyWriteSharedMemory { [[Order]]:SeqCst , [[NoTear]]:true , [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op }. - Append rmwEvent to eventList.
- Append
Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead } to execution.[[ChosenValues]].
- Let execution be the [[CandidateExecution]] field of the
- Else,
- Let rawBytesRead be a
List of length elementSize whose elements are the sequence of elementSize bytes starting with block[byteIndex]. - Let rawBytesModified be op(rawBytesRead, rawBytes).
- Store the individual bytes of rawBytesModified into block, starting at block[byteIndex].
- Let rawBytesRead be a
- Return
RawBytesToNumeric (type, rawBytesRead, isLittleEndian).
25.1.3 The ArrayBuffer Constructor
The ArrayBuffer
- is
%ArrayBuffer% . - is the initial value of the
"ArrayBuffer" property of theglobal object . - creates and initializes a new ArrayBuffer when called as a
constructor . - is not intended to be called as a function and will throw an exception when called in that manner.
- may be used as the value of an
extendsclause of a class definition. Subclassconstructors that intend to inherit the specified ArrayBuffer behaviour must include asupercall to the ArrayBufferconstructor to create and initialize subclass instances with the internal state necessary to support theArrayBuffer.prototypebuilt-in methods.
25.1.3.1 ArrayBuffer ( length )
When the ArrayBuffer function is called with argument length, the following steps are taken:
- If NewTarget is
undefined , throw aTypeError exception. - Let byteLength be ?
ToIndex (length). - Return ?
AllocateArrayBuffer (NewTarget, byteLength).
25.1.4 Properties of the ArrayBuffer Constructor
The ArrayBuffer
- has a [[Prototype]] internal slot whose value is
%Function.prototype% . - has the following properties:
25.1.4.1 ArrayBuffer.isView ( arg )
The isView function takes one argument arg, and performs the following steps:
- If
Type (arg) is not Object, returnfalse . - If arg has a [[ViewedArrayBuffer]] internal slot, return
true . - Return
false .
25.1.4.2 ArrayBuffer.prototype
The initial value of ArrayBuffer.prototype is the
This property has the attributes { [[Writable]]:
25.1.4.3 get ArrayBuffer [ @@species ]
ArrayBuffer[@@species] is an
- Return the
this value.
The value of the
ArrayBuffer prototype methods normally use their
25.1.5 Properties of the ArrayBuffer Prototype Object
The ArrayBuffer prototype object:
- is
%ArrayBuffer.prototype% . - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object . - does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] internal slot.
25.1.5.1 get ArrayBuffer.prototype.byteLength
ArrayBuffer.prototype.byteLength is an
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (O) istrue , throw aTypeError exception. - If
IsDetachedBuffer (O) istrue , return+0 𝔽. - Let length be O.[[ArrayBufferByteLength]].
- Return 𝔽(length).
25.1.5.2 ArrayBuffer.prototype.constructor
The initial value of ArrayBuffer.prototype.constructor is
25.1.5.3 ArrayBuffer.prototype.slice ( start, end )
The following steps are taken:
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (O) istrue , throw aTypeError exception. - If
IsDetachedBuffer (O) istrue , throw aTypeError exception. - Let len be O.[[ArrayBufferByteLength]].
- Let relativeStart be ?
ToIntegerOrInfinity (start). - If relativeStart is -∞, let first be 0.
- Else if relativeStart < 0, let first be
max (len + relativeStart, 0). - Else, let first be
min (relativeStart, len). - If end is
undefined , let relativeEnd be len; else let relativeEnd be ?ToIntegerOrInfinity (end). - If relativeEnd is -∞, let final be 0.
- Else if relativeEnd < 0, let final be
max (len + relativeEnd, 0). - Else, let final be
min (relativeEnd, len). - Let newLen be
max (final - first, 0). - Let ctor be ?
SpeciesConstructor (O,%ArrayBuffer% ). - Let new be ?
Construct (ctor, « 𝔽(newLen) »). - Perform ?
RequireInternalSlot (new, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (new) istrue , throw aTypeError exception. - If
IsDetachedBuffer (new) istrue , throw aTypeError exception. - If
SameValue (new, O) istrue , throw aTypeError exception. - If new.[[ArrayBufferByteLength]] < newLen, throw a
TypeError exception. - NOTE: Side-effects of the above steps may have detached O.
- If
IsDetachedBuffer (O) istrue , throw aTypeError exception. - Let fromBuf be O.[[ArrayBufferData]].
- Let toBuf be new.[[ArrayBufferData]].
- Perform
CopyDataBlockBytes (toBuf, 0, fromBuf, first, newLen). - Return new.
25.1.5.4 ArrayBuffer.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
25.1.6 Properties of ArrayBuffer Instances
ArrayBuffer instances inherit properties from the
ArrayBuffer instances whose [[ArrayBufferData]] is
ArrayBuffer instances whose [[ArrayBufferDetachKey]] is set to a value other than
25.2 SharedArrayBuffer Objects
25.2.1 Abstract Operations for SharedArrayBuffer Objects
25.2.1.1 AllocateSharedArrayBuffer ( constructor, byteLength )
The abstract operation AllocateSharedArrayBuffer takes arguments constructor and byteLength (a non-negative
- Let obj be ?
OrdinaryCreateFromConstructor (constructor," , « [[ArrayBufferData]], [[ArrayBufferByteLength]] »).%SharedArrayBuffer.prototype% " - Let block be ?
CreateSharedByteDataBlock (byteLength). - Set obj.[[ArrayBufferData]] to block.
- Set obj.[[ArrayBufferByteLength]] to byteLength.
- Return obj.
25.2.1.2 IsSharedArrayBuffer ( obj )
The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. It tests whether an object is an ArrayBuffer, a SharedArrayBuffer, or a subtype of either. It performs the following steps when called:
- Let bufferData be obj.[[ArrayBufferData]].
- If bufferData is
null , returnfalse . - If bufferData is a
Data Block , returnfalse . Assert : bufferData is aShared Data Block .- Return
true .
25.2.2 The SharedArrayBuffer Constructor
The SharedArrayBuffer
- is
%SharedArrayBuffer% . - is the initial value of the
"SharedArrayBuffer" property of theglobal object , if that property is present (see below). - creates and initializes a new SharedArrayBuffer when called as a
constructor . - is not intended to be called as a function and will throw an exception when called in that manner.
- may be used as the value of an
extendsclause of a class definition. Subclassconstructors that intend to inherit the specified SharedArrayBuffer behaviour must include asupercall to the SharedArrayBufferconstructor to create and initialize subclass instances with the internal state necessary to support theSharedArrayBuffer.prototypebuilt-in methods.
Whenever a
Unlike an ArrayBuffer, a SharedArrayBuffer cannot become detached, and its internal [[ArrayBufferData]] slot is never
25.2.2.1 SharedArrayBuffer ( length )
When the SharedArrayBuffer function is called with argument length, the following steps are taken:
- If NewTarget is
undefined , throw aTypeError exception. - Let byteLength be ?
ToIndex (length). - Return ?
AllocateSharedArrayBuffer (NewTarget, byteLength).
25.2.3 Properties of the SharedArrayBuffer Constructor
The SharedArrayBuffer
- has a [[Prototype]] internal slot whose value is
%Function.prototype% . - has the following properties:
25.2.3.1 SharedArrayBuffer.prototype
The initial value of SharedArrayBuffer.prototype is the
This property has the attributes { [[Writable]]:
25.2.3.2 get SharedArrayBuffer [ @@species ]
SharedArrayBuffer[@@species] is an
- Return the
this value.
The value of the
25.2.4 Properties of the SharedArrayBuffer Prototype Object
The SharedArrayBuffer prototype object:
- is
%SharedArrayBuffer.prototype% . - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object . - does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] internal slot.
25.2.4.1 get SharedArrayBuffer.prototype.byteLength
SharedArrayBuffer.prototype.byteLength is an
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (O) isfalse , throw aTypeError exception. - Let length be O.[[ArrayBufferByteLength]].
- Return 𝔽(length).
25.2.4.2 SharedArrayBuffer.prototype.constructor
The initial value of SharedArrayBuffer.prototype.constructor is
25.2.4.3 SharedArrayBuffer.prototype.slice ( start, end )
The following steps are taken:
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (O) isfalse , throw aTypeError exception. - Let len be O.[[ArrayBufferByteLength]].
- Let relativeStart be ?
ToIntegerOrInfinity (start). - If relativeStart is -∞, let first be 0.
- Else if relativeStart < 0, let first be
max (len + relativeStart, 0). - Else, let first be
min (relativeStart, len). - If end is
undefined , let relativeEnd be len; else let relativeEnd be ?ToIntegerOrInfinity (end). - If relativeEnd is -∞, let final be 0.
- Else if relativeEnd < 0, let final be
max (len + relativeEnd, 0). - Else, let final be
min (relativeEnd, len). - Let newLen be
max (final - first, 0). - Let ctor be ?
SpeciesConstructor (O,%SharedArrayBuffer% ). - Let new be ?
Construct (ctor, « 𝔽(newLen) »). - Perform ?
RequireInternalSlot (new, [[ArrayBufferData]]). - If
IsSharedArrayBuffer (new) isfalse , throw aTypeError exception. - If new.[[ArrayBufferData]] and O.[[ArrayBufferData]] are the same
Shared Data Block values, throw aTypeError exception. - If new.[[ArrayBufferByteLength]] < newLen, throw a
TypeError exception. - Let fromBuf be O.[[ArrayBufferData]].
- Let toBuf be new.[[ArrayBufferData]].
- Perform
CopyDataBlockBytes (toBuf, 0, fromBuf, first, newLen). - Return new.
25.2.4.4 SharedArrayBuffer.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
25.2.5 Properties of SharedArrayBuffer Instances
SharedArrayBuffer instances inherit properties from the
SharedArrayBuffer instances, unlike ArrayBuffer instances, are never detached.
25.3 DataView Objects
25.3.1 Abstract Operations For DataView Objects
25.3.1.1 GetViewValue ( view, requestIndex, isLittleEndian, type )
The abstract operation GetViewValue takes arguments view, requestIndex, isLittleEndian, and type and returns either a
- Perform ?
RequireInternalSlot (view, [[DataView]]). Assert : view has a [[ViewedArrayBuffer]] internal slot.- Let getIndex be ?
ToIndex (requestIndex). - Set isLittleEndian to
ToBoolean (isLittleEndian). - Let buffer be view.[[ViewedArrayBuffer]].
- If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Let viewOffset be view.[[ByteOffset]].
- Let viewSize be view.[[ByteLength]].
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If getIndex + elementSize > viewSize, throw a
RangeError exception. - Let bufferIndex be getIndex + viewOffset.
- Return
GetValueFromBuffer (buffer, bufferIndex, type,false ,Unordered , isLittleEndian).
25.3.1.2 SetViewValue ( view, requestIndex, isLittleEndian, type, value )
The abstract operation SetViewValue takes arguments view, requestIndex, isLittleEndian, type, and value and returns either a
- Perform ?
RequireInternalSlot (view, [[DataView]]). Assert : view has a [[ViewedArrayBuffer]] internal slot.- Let getIndex be ?
ToIndex (requestIndex). - If
IsBigIntElementType (type) istrue , let numberValue be ?ToBigInt (value). - Otherwise, let numberValue be ?
ToNumber (value). - Set isLittleEndian to
ToBoolean (isLittleEndian). - Let buffer be view.[[ViewedArrayBuffer]].
- If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Let viewOffset be view.[[ByteOffset]].
- Let viewSize be view.[[ByteLength]].
- Let elementSize be the Element Size value specified in
Table 71 for Element Type type. - If getIndex + elementSize > viewSize, throw a
RangeError exception. - Let bufferIndex be getIndex + viewOffset.
- Perform
SetValueInBuffer (buffer, bufferIndex, type, numberValue,false ,Unordered , isLittleEndian). - Return
undefined .
25.3.2 The DataView Constructor
The DataView
- is
%DataView% . - is the initial value of the
"DataView" property of theglobal object . - creates and initializes a new DataView when called as a
constructor . - is not intended to be called as a function and will throw an exception when called in that manner.
- may be used as the value of an
extendsclause of a class definition. Subclassconstructors that intend to inherit the specified DataView behaviour must include asupercall to the DataViewconstructor to create and initialize subclass instances with the internal state necessary to support theDataView.prototypebuilt-in methods.
25.3.2.1 DataView ( buffer [ , byteOffset [ , byteLength ] ] )
When the DataView function is called with at least one argument buffer, the following steps are taken:
- If NewTarget is
undefined , throw aTypeError exception. - Perform ?
RequireInternalSlot (buffer, [[ArrayBufferData]]). - Let offset be ?
ToIndex (byteOffset). - If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Let bufferByteLength be buffer.[[ArrayBufferByteLength]].
- If offset > bufferByteLength, throw a
RangeError exception. - If byteLength is
undefined , then- Let viewByteLength be bufferByteLength - offset.
- Else,
- Let viewByteLength be ?
ToIndex (byteLength). - If offset + viewByteLength > bufferByteLength, throw a
RangeError exception.
- Let viewByteLength be ?
- Let O be ?
OrdinaryCreateFromConstructor (NewTarget," , « [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] »).%DataView.prototype% " - If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Set O.[[ViewedArrayBuffer]] to buffer.
- Set O.[[ByteLength]] to viewByteLength.
- Set O.[[ByteOffset]] to offset.
- Return O.
25.3.3 Properties of the DataView Constructor
The DataView
- has a [[Prototype]] internal slot whose value is
%Function.prototype% . - has the following properties:
25.3.3.1 DataView.prototype
The initial value of DataView.prototype is the
This property has the attributes { [[Writable]]:
25.3.4 Properties of the DataView Prototype Object
The DataView prototype object:
- is
%DataView.prototype% . - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object . - does not have a [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], or [[ByteOffset]] internal slot.
25.3.4.1 get DataView.prototype.buffer
DataView.prototype.buffer is an
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[DataView]]). Assert : O has a [[ViewedArrayBuffer]] internal slot.- Let buffer be O.[[ViewedArrayBuffer]].
- Return buffer.
25.3.4.2 get DataView.prototype.byteLength
DataView.prototype.byteLength is an
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[DataView]]). Assert : O has a [[ViewedArrayBuffer]] internal slot.- Let buffer be O.[[ViewedArrayBuffer]].
- If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Let size be O.[[ByteLength]].
- Return 𝔽(size).
25.3.4.3 get DataView.prototype.byteOffset
DataView.prototype.byteOffset is an
- Let O be the
this value. - Perform ?
RequireInternalSlot (O, [[DataView]]). Assert : O has a [[ViewedArrayBuffer]] internal slot.- Let buffer be O.[[ViewedArrayBuffer]].
- If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - Let offset be O.[[ByteOffset]].
- Return 𝔽(offset).
25.3.4.4 DataView.prototype.constructor
The initial value of DataView.prototype.constructor is
25.3.4.5 DataView.prototype.getBigInt64 ( byteOffset [ , littleEndian ] )
When the getBigInt64 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - Return ?
GetViewValue (v, byteOffset, littleEndian,BigInt64 ).
25.3.4.6 DataView.prototype.getBigUint64 ( byteOffset [ , littleEndian ] )
When the getBigUint64 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - Return ?
GetViewValue (v, byteOffset, littleEndian,BigUint64 ).
25.3.4.7 DataView.prototype.getFloat32 ( byteOffset [ , littleEndian ] )
When the getFloat32 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Float32 ).
25.3.4.8 DataView.prototype.getFloat64 ( byteOffset [ , littleEndian ] )
When the getFloat64 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Float64 ).
25.3.4.9 DataView.prototype.getInt8 ( byteOffset )
When the getInt8 method is called with argument byteOffset, the following steps are taken:
- Let v be the
this value. - Return ?
GetViewValue (v, byteOffset,true ,Int8 ).
25.3.4.10 DataView.prototype.getInt16 ( byteOffset [ , littleEndian ] )
When the getInt16 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Int16 ).
25.3.4.11 DataView.prototype.getInt32 ( byteOffset [ , littleEndian ] )
When the getInt32 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Int32 ).
25.3.4.12 DataView.prototype.getUint8 ( byteOffset )
When the getUint8 method is called with argument byteOffset, the following steps are taken:
- Let v be the
this value. - Return ?
GetViewValue (v, byteOffset,true ,Uint8 ).
25.3.4.13 DataView.prototype.getUint16 ( byteOffset [ , littleEndian ] )
When the getUint16 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Uint16 ).
25.3.4.14 DataView.prototype.getUint32 ( byteOffset [ , littleEndian ] )
When the getUint32 method is called with argument byteOffset and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
GetViewValue (v, byteOffset, littleEndian,Uint32 ).
25.3.4.15 DataView.prototype.setBigInt64 ( byteOffset, value [ , littleEndian ] )
When the setBigInt64 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - Return ?
SetViewValue (v, byteOffset, littleEndian,BigInt64 , value).
25.3.4.16 DataView.prototype.setBigUint64 ( byteOffset, value [ , littleEndian ] )
When the setBigUint64 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - Return ?
SetViewValue (v, byteOffset, littleEndian,BigUint64 , value).
25.3.4.17 DataView.prototype.setFloat32 ( byteOffset, value [ , littleEndian ] )
When the setFloat32 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Float32 , value).
25.3.4.18 DataView.prototype.setFloat64 ( byteOffset, value [ , littleEndian ] )
When the setFloat64 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Float64 , value).
25.3.4.19 DataView.prototype.setInt8 ( byteOffset, value )
When the setInt8 method is called with arguments byteOffset and value, the following steps are taken:
- Let v be the
this value. - Return ?
SetViewValue (v, byteOffset,true ,Int8 , value).
25.3.4.20 DataView.prototype.setInt16 ( byteOffset, value [ , littleEndian ] )
When the setInt16 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Int16 , value).
25.3.4.21 DataView.prototype.setInt32 ( byteOffset, value [ , littleEndian ] )
When the setInt32 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Int32 , value).
25.3.4.22 DataView.prototype.setUint8 ( byteOffset, value )
When the setUint8 method is called with arguments byteOffset and value, the following steps are taken:
- Let v be the
this value. - Return ?
SetViewValue (v, byteOffset,true ,Uint8 , value).
25.3.4.23 DataView.prototype.setUint16 ( byteOffset, value [ , littleEndian ] )
When the setUint16 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Uint16 , value).
25.3.4.24 DataView.prototype.setUint32 ( byteOffset, value [ , littleEndian ] )
When the setUint32 method is called with arguments byteOffset and value and optional argument littleEndian, the following steps are taken:
- Let v be the
this value. - If littleEndian is not present, set littleEndian to
false . - Return ?
SetViewValue (v, byteOffset, littleEndian,Uint32 , value).
25.3.4.25 DataView.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
25.3.5 Properties of DataView Instances
DataView instances are
The value of the [[DataView]] internal slot is not used within this specification. The simple presence of that internal slot is used within the specification to identify objects created using the DataView
25.4 The Atomics Object
The Atomics object:
- is
%Atomics% . - is the initial value of the
"Atomics" property of theglobal object . - is an
ordinary object . - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - does not have a [[Construct]] internal method; it cannot be used as a
constructor with thenewoperator. - does not have a [[Call]] internal method; it cannot be invoked as a function.
The Atomics object provides functions that operate indivisibly (atomically) on shared memory array cells as well as functions that let
For informative guidelines for programming and implementing shared memory in ECMAScript, please see the notes at the end of the
25.4.1 WaiterList Objects
A WaiterList is a semantic object that contains an ordered list of
Initially a WaiterList object has an empty list and no
The
Each WaiterList has a critical section that controls exclusive access to that WaiterList during evaluation. Only a single
25.4.2 Abstract Operations for Atomics
25.4.2.1 ValidateIntegerTypedArray ( typedArray [ , waitable ] )
The abstract operation ValidateIntegerTypedArray takes argument typedArray and optional argument waitable (a Boolean) and returns either a
- If waitable is not present, set waitable to
false . - Perform ?
ValidateTypedArray (typedArray). - Let buffer be typedArray.[[ViewedArrayBuffer]].
- If waitable is
true , then- If typedArray.[[TypedArrayName]] is not
"Int32Array" or"BigInt64Array" , throw aTypeError exception.
- If typedArray.[[TypedArrayName]] is not
- Else,
- Let type be
TypedArrayElementType (typedArray). - If
IsUnclampedIntegerElementType (type) isfalse andIsBigIntElementType (type) isfalse , throw aTypeError exception.
- Let type be
- Return buffer.
25.4.2.2 ValidateAtomicAccess ( typedArray, requestIndex )
The abstract operation ValidateAtomicAccess takes arguments typedArray (a TypedArray) and requestIndex and returns either a
- Let length be typedArray.[[ArrayLength]].
- Let accessIndex be ?
ToIndex (requestIndex). Assert : accessIndex ≥ 0.- If accessIndex ≥ length, throw a
RangeError exception. - Let elementSize be
TypedArrayElementSize (typedArray). - Let offset be typedArray.[[ByteOffset]].
- Return (accessIndex × elementSize) + offset.
25.4.2.3 GetWaiterList ( block, i )
The abstract operation GetWaiterList takes arguments block (a
Assert : i and i + 3 are valid byte offsets within the memory of block.- Return the
WaiterList that is referenced by the pair (block, i).
25.4.2.4 EnterCriticalSection ( WL )
The abstract operation EnterCriticalSection takes argument WL (a
Assert : The callingagent is not in thecritical section for anyWaiterList .- Wait until no
agent is in thecritical section for WL, then enter thecritical section for WL (without allowing any otheragent to enter). - If WL has a
Synchronize event , then- NOTE: A WL whose
critical section has been entered at least once has aSynchronize event set byLeaveCriticalSection . - Let execution be the [[CandidateExecution]] field of the
surrounding agent 'sAgent Record . - Let eventsRecord be the
Agent Events Record in execution.[[EventsRecords]] whose [[AgentSignifier]] isAgentSignifier (). - Let entererEventList be eventsRecord.[[EventList]].
- Let enterEvent be a new
Synchronize event . - Append enterEvent to entererEventList.
- Let leaveEvent be the
Synchronize event in WL. - Append (leaveEvent, enterEvent) to eventsRecord.[[AgentSynchronizesWith]].
- NOTE: A WL whose
- Return
unused .
EnterCriticalSection has contention when an
25.4.2.5 LeaveCriticalSection ( WL )
The abstract operation LeaveCriticalSection takes argument WL (a
Assert : The callingagent is in thecritical section for WL.- Let execution be the [[CandidateExecution]] field of the calling surrounding's
Agent Record . - Let eventsRecord be the
Agent Events Record in execution.[[EventsRecords]] whose [[AgentSignifier]] isAgentSignifier (). - Let leaverEventList be eventsRecord.[[EventList]].
- Let leaveEvent be a new
Synchronize event . - Append leaveEvent to leaverEventList.
- Set the
Synchronize event in WL to leaveEvent. - Leave the
critical section for WL. - Return
unused .
25.4.2.6 AddWaiter ( WL, W )
The abstract operation AddWaiter takes arguments WL (a
Assert : The callingagent is in thecritical section for WL.Assert : W is not on the list of waiters in anyWaiterList .- Add W to the end of the list of waiters in WL.
- Return
unused .
25.4.2.7 RemoveWaiter ( WL, W )
The abstract operation RemoveWaiter takes arguments WL (a
Assert : The callingagent is in thecritical section for WL.Assert : W is on the list of waiters in WL.- Remove W from the list of waiters in WL.
- Return
unused .
25.4.2.8 RemoveWaiters ( WL, c )
The abstract operation RemoveWaiters takes arguments WL (a
Assert : The callingagent is in thecritical section for WL.- Let L be a new empty
List . - Let S be a reference to the list of waiters in WL.
- Repeat, while c > 0 and S is not an empty
List ,- Let W be the first waiter in S.
- Add W to the end of L.
- Remove W from S.
- If c is finite, set c to c - 1.
- Return L.
25.4.2.9 SuspendAgent ( WL, W, timeout )
The abstract operation SuspendAgent takes arguments WL (a
Assert : The callingagent is in thecritical section for WL.Assert : W is equivalent toAgentSignifier ().Assert : W is on the list of waiters in WL.Assert :AgentCanSuspend () istrue .- Perform
LeaveCriticalSection (WL) and suspend W for up to timeout milliseconds, performing the combined operation in such a way that a notification that arrives after thecritical section is exited but before the suspension takes effect is not lost. W can notify either because the timeout expired or because it was notified explicitly by anotheragent callingNotifyWaiter with arguments WL and W, and not for any other reasons at all. - Perform
EnterCriticalSection (WL). - If W was notified explicitly by another
agent callingNotifyWaiter with arguments WL and W, returntrue . - Return
false .
25.4.2.10 NotifyWaiter ( WL, W )
The abstract operation NotifyWaiter takes arguments WL (a
Assert : The callingagent is in thecritical section for WL.- Notify the
agent W. - Return
unused .
The embedding may delay notifying W, e.g. for resource management reasons, but W must eventually be notified in order to guarantee forward progress.
25.4.2.11 AtomicReadModifyWrite ( typedArray, index, value, op )
The abstract operation AtomicReadModifyWrite takes arguments typedArray, index, value, and op (a
- Let buffer be ?
ValidateIntegerTypedArray (typedArray). - Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If typedArray.[[ContentType]] is
BigInt , let v be ?ToBigInt (value). - Otherwise, let v be 𝔽(?
ToIntegerOrInfinity (value)). - If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - NOTE: The above check is not redundant with the check in
ValidateIntegerTypedArray because the call toToBigInt orToIntegerOrInfinity on the preceding lines can have arbitrary side effects, which could cause the buffer to become detached. - Let elementType be
TypedArrayElementType (typedArray). - Return
GetModifySetValueInBuffer (buffer, indexedPosition, elementType, v, op).
25.4.2.12 ByteListBitwiseOp ( op, xBytes, yBytes )
The abstract operation ByteListBitwiseOp takes arguments op (&, ^, or |), xBytes (a
Assert : xBytes and yBytes have the same number of elements.- Let result be a new empty
List . - Let i be 0.
- For each element xByte of xBytes, do
- Let yByte be yBytes[i].
- If op is
&, let resultByte be the result of applying the bitwise AND operation to xByte and yByte. - Else if op is
^, let resultByte be the result of applying the bitwise exclusive OR (XOR) operation to xByte and yByte. - Else, op is
|. Let resultByte be the result of applying the bitwise inclusive OR operation to xByte and yByte. - Set i to i + 1.
- Append resultByte to the end of result.
- Return result.
25.4.2.13 ByteListEqual ( xBytes, yBytes )
The abstract operation ByteListEqual takes arguments xBytes (a
- If xBytes and yBytes do not have the same number of elements, return
false . - Let i be 0.
- For each element xByte of xBytes, do
- Let yByte be yBytes[i].
- If xByte ≠ yByte, return
false . - Set i to i + 1.
- Return
true .
25.4.3 Atomics.add ( typedArray, index, value )
The following steps are taken:
- Let type be
TypedArrayElementType (typedArray). - Let isLittleEndian be the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Let add be a new
read-modify-write modification function with parameters (xBytes, yBytes) that captures type and isLittleEndian and performs the following steps atomically when called:- Let x be
RawBytesToNumeric (type, xBytes, isLittleEndian). - Let y be
RawBytesToNumeric (type, yBytes, isLittleEndian). - If
Type (x) is Number, then- Let sum be
Number::add (x, y).
- Let sum be
- Else,
Assert :Type (x) is BigInt.- Let sum be
BigInt::add (x, y).
- Let sumBytes be
NumericToRawBytes (type, sum, isLittleEndian). Assert : sumBytes, xBytes, and yBytes have the same number of elements.- Return sumBytes.
- Let x be
- Return ?
AtomicReadModifyWrite (typedArray, index, value, add).
25.4.4 Atomics.and ( typedArray, index, value )
The following steps are taken:
- Let and be a new
read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:- Return
ByteListBitwiseOp (&, xBytes, yBytes).
- Return
- Return ?
AtomicReadModifyWrite (typedArray, index, value, and).
25.4.5 Atomics.compareExchange ( typedArray, index, expectedValue, replacementValue )
The following steps are taken:
- Let buffer be ?
ValidateIntegerTypedArray (typedArray). - Let block be buffer.[[ArrayBufferData]].
- Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If typedArray.[[ContentType]] is
BigInt , then - Else,
- Let expected be 𝔽(?
ToIntegerOrInfinity (expectedValue)). - Let replacement be 𝔽(?
ToIntegerOrInfinity (replacementValue)).
- Let expected be 𝔽(?
- If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - NOTE: The above check is not redundant with the check in
ValidateIntegerTypedArray because the call toToBigInt orToIntegerOrInfinity on the preceding lines can have arbitrary side effects, which could cause the buffer to become detached. - Let elementType be
TypedArrayElementType (typedArray). - Let elementSize be
TypedArrayElementSize (typedArray). - Let isLittleEndian be the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Let expectedBytes be
NumericToRawBytes (elementType, expected, isLittleEndian). - Let replacementBytes be
NumericToRawBytes (elementType, replacement, isLittleEndian). - If
IsSharedArrayBuffer (buffer) istrue , then- Let execution be the [[CandidateExecution]] field of the
surrounding agent 'sAgent Record . - Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is
AgentSignifier (). - Let rawBytesRead be a
List of length elementSize whose elements are nondeterministically chosenbyte values . - NOTE: In implementations, rawBytesRead is the result of a load-link, of a load-exclusive, or of an operand of a read-modify-write instruction on the underlying hardware. The nondeterminism is a semantic prescription of the
memory model to describe observable behaviour of hardware with weak consistency. - NOTE: The comparison of the expected value and the read value is performed outside of the
read-modify-write modification function to avoid needlessly strong synchronization when the expected value is not equal to the read value. - If
ByteListEqual (rawBytesRead, expectedBytes) istrue , then- Let second be a new
read-modify-write modification function with parameters (oldBytes, newBytes) that captures nothing and performs the following steps atomically when called:- Return newBytes.
- Let event be
ReadModifyWriteSharedMemory { [[Order]]:SeqCst , [[NoTear]]:true , [[Block]]: block, [[ByteIndex]]: indexedPosition, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }.
- Let second be a new
- Else,
- Let event be
ReadSharedMemory { [[Order]]:SeqCst , [[NoTear]]:true , [[Block]]: block, [[ByteIndex]]: indexedPosition, [[ElementSize]]: elementSize }.
- Let event be
- Append event to eventList.
- Append
Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead } to execution.[[ChosenValues]].
- Let execution be the [[CandidateExecution]] field of the
- Else,
- Let rawBytesRead be a
List of length elementSize whose elements are the sequence of elementSize bytes starting with block[indexedPosition]. - If
ByteListEqual (rawBytesRead, expectedBytes) istrue , then- Store the individual bytes of replacementBytes into block, starting at block[indexedPosition].
- Let rawBytesRead be a
- Return
RawBytesToNumeric (elementType, rawBytesRead, isLittleEndian).
25.4.6 Atomics.exchange ( typedArray, index, value )
The following steps are taken:
- Let second be a new
read-modify-write modification function with parameters (oldBytes, newBytes) that captures nothing and performs the following steps atomically when called:- Return newBytes.
- Return ?
AtomicReadModifyWrite (typedArray, index, value, second).
25.4.7 Atomics.isLockFree ( size )
The following steps are taken:
- Let n be ?
ToIntegerOrInfinity (size). - Let AR be the
Agent Record of thesurrounding agent . - If n = 1, return AR.[[IsLockFree1]].
- If n = 2, return AR.[[IsLockFree2]].
- If n = 4, return
true . - If n = 8, return AR.[[IsLockFree8]].
- Return
false .
Atomics.isLockFree() is an optimization primitive. The intuition is that if the atomic step of an atomic primitive (compareExchange, load, store, add, sub, and, or, xor, or exchange) on a datum of size n bytes will be performed without the calling Atomics.isLockFree(n) will return Atomics.isLockFree to determine whether to use locks or atomic operations in
Atomics.isLockFree(4) always returns
Regardless of the value of Atomics.isLockFree, all atomic operations are guaranteed to be atomic. For example, they will never have a visible operation take place in the middle of the operation (e.g., "tearing").
25.4.8 Atomics.load ( typedArray, index )
The following steps are taken:
- Let buffer be ?
ValidateIntegerTypedArray (typedArray). - Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - NOTE: The above check is not redundant with the check in
ValidateIntegerTypedArray because the call toValidateAtomicAccess on the preceding line can have arbitrary side effects, which could cause the buffer to become detached. - Let elementType be
TypedArrayElementType (typedArray). - Return
GetValueFromBuffer (buffer, indexedPosition, elementType,true ,SeqCst ).
25.4.9 Atomics.or ( typedArray, index, value )
The following steps are taken:
- Let or be a new
read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:- Return
ByteListBitwiseOp (|, xBytes, yBytes).
- Return
- Return ?
AtomicReadModifyWrite (typedArray, index, value, or).
25.4.10 Atomics.store ( typedArray, index, value )
The following steps are taken:
- Let buffer be ?
ValidateIntegerTypedArray (typedArray). - Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If typedArray.[[ContentType]] is
BigInt , let v be ?ToBigInt (value). - Otherwise, let v be 𝔽(?
ToIntegerOrInfinity (value)). - If
IsDetachedBuffer (buffer) istrue , throw aTypeError exception. - NOTE: The above check is not redundant with the check in
ValidateIntegerTypedArray because the call toToBigInt orToIntegerOrInfinity on the preceding lines can have arbitrary side effects, which could cause the buffer to become detached. - Let elementType be
TypedArrayElementType (typedArray). - Perform
SetValueInBuffer (buffer, indexedPosition, elementType, v,true ,SeqCst ). - Return v.
25.4.11 Atomics.sub ( typedArray, index, value )
The following steps are taken:
- Let type be
TypedArrayElementType (typedArray). - Let isLittleEndian be the value of the [[LittleEndian]] field of the
surrounding agent 'sAgent Record . - Let subtract be a new
read-modify-write modification function with parameters (xBytes, yBytes) that captures type and isLittleEndian and performs the following steps atomically when called:- Let x be
RawBytesToNumeric (type, xBytes, isLittleEndian). - Let y be
RawBytesToNumeric (type, yBytes, isLittleEndian). - If
Type (x) is Number, then- Let difference be
Number::subtract (x, y).
- Let difference be
- Else,
Assert :Type (x) is BigInt.- Let difference be
BigInt::subtract (x, y).
- Let differenceBytes be
NumericToRawBytes (type, difference, isLittleEndian). Assert : differenceBytes, xBytes, and yBytes have the same number of elements.- Return differenceBytes.
- Let x be
- Return ?
AtomicReadModifyWrite (typedArray, index, value, subtract).
25.4.12 Atomics.wait ( typedArray, index, value, timeout )
Atomics.wait puts the calling
- Let buffer be ?
ValidateIntegerTypedArray (typedArray,true ). - If
IsSharedArrayBuffer (buffer) isfalse , throw aTypeError exception. - Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If typedArray.[[TypedArrayName]] is
"BigInt64Array" , let v be ?ToBigInt64 (value). - Otherwise, let v be ?
ToInt32 (value). - Let q be ?
ToNumber (timeout). - If q is
NaN or+∞ 𝔽, let t be +∞; else if q is-∞ 𝔽, let t be 0; else let t bemax (ℝ(q), 0). - Let B be
AgentCanSuspend (). - If B is
false , throw aTypeError exception. - Let block be buffer.[[ArrayBufferData]].
- Let WL be
GetWaiterList (block, indexedPosition). - Perform
EnterCriticalSection (WL). - Let elementType be
TypedArrayElementType (typedArray). - Let w be
GetValueFromBuffer (buffer, indexedPosition, elementType,true ,SeqCst ). - If v ≠ w, then
- Perform
LeaveCriticalSection (WL). - Return the String
"not-equal" .
- Perform
- Let W be
AgentSignifier (). - Perform
AddWaiter (WL, W). - Let notified be
SuspendAgent (WL, W, t). - If notified is
true , thenAssert : W is not on the list of waiters in WL.
- Else,
- Perform
RemoveWaiter (WL, W).
- Perform
- Perform
LeaveCriticalSection (WL). - If notified is
true , return the String"ok" . - Return the String
"timed-out" .
25.4.13 Atomics.notify ( typedArray, index, count )
Atomics.notify notifies some
- Let buffer be ?
ValidateIntegerTypedArray (typedArray,true ). - Let indexedPosition be ?
ValidateAtomicAccess (typedArray, index). - If count is
undefined , let c be +∞. - Else,
- Let intCount be ?
ToIntegerOrInfinity (count). - Let c be
max (intCount, 0).
- Let intCount be ?
- Let block be buffer.[[ArrayBufferData]].
- If
IsSharedArrayBuffer (buffer) isfalse , return+0 𝔽. - Let WL be
GetWaiterList (block, indexedPosition). - Let n be 0.
- Perform
EnterCriticalSection (WL). - Let S be
RemoveWaiters (WL, c). - Repeat, while S is not an empty
List ,- Let W be the first
agent in S. - Remove W from the front of S.
- Perform
NotifyWaiter (WL, W). - Set n to n + 1.
- Let W be the first
- Perform
LeaveCriticalSection (WL). - Return 𝔽(n).
25.4.14 Atomics.xor ( typedArray, index, value )
The following steps are taken:
- Let xor be a new
read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:- Return
ByteListBitwiseOp (^, xBytes, yBytes).
- Return
- Return ?
AtomicReadModifyWrite (typedArray, index, value, xor).
25.4.15 Atomics [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
25.5 The JSON Object
The JSON object:
- is
%JSON% . - is the initial value of the
"JSON" property of theglobal object . - is an
ordinary object . - contains two functions,
parseandstringify, that are used to parse and construct JSON texts. - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - does not have a [[Construct]] internal method; it cannot be used as a
constructor with thenewoperator. - does not have a [[Call]] internal method; it cannot be invoked as a function.
The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used in this specification is exactly that described by ECMA-404. Conforming implementations of JSON.parse and JSON.stringify must support the exact interchange format described in the ECMA-404 specification without any deletions or extensions to the format.
25.5.1 JSON.parse ( text [ , reviver ] )
The parse function parses a JSON text (a JSON-formatted String) and produces an
The optional reviver parameter is a function that takes two parameters, key and value. It can filter and transform the results. It is called with each of the key/value pairs produced by the parse, and its return value is used instead of the original value. If it returns what it received, the structure is not modified. If it returns
- Let jsonString be ?
ToString (text). - Parse
StringToCodePoints (jsonString) as a JSON text as specified in ECMA-404. Throw aSyntaxError exception if it is not a valid JSON text as defined in that specification. - Let scriptString be the
string-concatenation of"(" , jsonString, and");" . - Let script be
ParseText (StringToCodePoints (scriptString),Script ). - NOTE: The
early error rules defined in13.2.5.1 have special handling for the above invocation ofParseText . Assert : script is aParse Node .- Let completion be the result of
evaluating script . - NOTE: The
PropertyDefinitionEvaluation semantics defined in13.2.5.5 have special handling for the above evaluation. - Let unfiltered be completion.[[Value]].
Assert : unfiltered is either a String, Number, Boolean, Null, or an Object that is defined by either anArrayLiteral or anObjectLiteral .- If
IsCallable (reviver) istrue , then- Let root be
OrdinaryObjectCreate (%Object.prototype% ). - Let rootName be the empty String.
- Perform !
CreateDataPropertyOrThrow (root, rootName, unfiltered). - Return ?
InternalizeJSONProperty (root, rootName, reviver).
- Let root be
- Else,
- Return unfiltered.
The parse function is
Valid JSON text is a subset of the ECMAScript
However, because JSON.parse, the same source text can produce different results when evaluated as a JSON.parse, means that not all texts accepted by JSON.parse are valid as a
25.5.1.1 InternalizeJSONProperty ( holder, name, reviver )
The abstract operation InternalizeJSONProperty takes arguments holder (an Object), name (a String), and reviver (a
This algorithm intentionally does not throw an exception if either [[Delete]] or
It performs the following steps when called:
- Let val be ?
Get (holder, name). - If
Type (val) is Object, then- Let isArray be ?
IsArray (val). - If isArray is
true , then- Let I be 0.
- Let len be ?
LengthOfArrayLike (val). - Repeat, while I < len,
- Let prop be !
ToString (𝔽(I)). - Let newElement be ? InternalizeJSONProperty(val, prop, reviver).
- If newElement is
undefined , then- Perform ?
val.[[Delete]] (prop).
- Perform ?
- Else,
- Perform ?
CreateDataProperty (val, prop, newElement).
- Perform ?
- Set I to I + 1.
- Let prop be !
- Else,
- Let keys be ?
EnumerableOwnPropertyNames (val,key ). - For each String P of keys, do
- Let newElement be ? InternalizeJSONProperty(val, P, reviver).
- If newElement is
undefined , then- Perform ?
val.[[Delete]] (P).
- Perform ?
- Else,
- Perform ?
CreateDataProperty (val, P, newElement).
- Perform ?
- Let keys be ?
- Let isArray be ?
- Return ?
Call (reviver, holder, « name, val »).
It is not permitted for a conforming implementation of JSON.parse to extend the JSON grammars. If an implementation wishes to support a modified or extended JSON interchange format it must do so by defining a different parse function.
In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.
25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] )
The stringify function returns a String in UTF-16 encoded JSON format representing an
These are the steps in stringifying an object:
- Let stack be a new empty
List . - Let indent be the empty String.
- Let PropertyList and ReplacerFunction be
undefined . - If
Type (replacer) is Object, then- If
IsCallable (replacer) istrue , then- Set ReplacerFunction to replacer.
- Else,
- Let isArray be ?
IsArray (replacer). - If isArray is
true , then- Set PropertyList to a new empty
List . - Let len be ?
LengthOfArrayLike (replacer). - Let k be 0.
- Repeat, while k < len,
- Let prop be !
ToString (𝔽(k)). - Let v be ?
Get (replacer, prop). - Let item be
undefined . - If
Type (v) is String, set item to v. - Else if
Type (v) is Number, set item to !ToString (v). - Else if
Type (v) is Object, then- If v has a [[StringData]] or [[NumberData]] internal slot, set item to ?
ToString (v).
- If v has a [[StringData]] or [[NumberData]] internal slot, set item to ?
- If item is not
undefined and item is not currently an element of PropertyList, then- Append item to the end of PropertyList.
- Set k to k + 1.
- Let prop be !
- Set PropertyList to a new empty
- Let isArray be ?
- If
- If
Type (space) is Object, then - If
Type (space) is Number, then- Let spaceMV be !
ToIntegerOrInfinity (space). - Set spaceMV to
min (10, spaceMV). - If spaceMV < 1, let gap be the empty String; otherwise let gap be the String value containing spaceMV occurrences of the code unit 0x0020 (SPACE).
- Let spaceMV be !
- Else if
Type (space) is String, then- If the length of space is 10 or less, let gap be space; otherwise let gap be the
substring of space from 0 to 10.
- If the length of space is 10 or less, let gap be space; otherwise let gap be the
- Else,
- Let gap be the empty String.
- Let wrapper be
OrdinaryObjectCreate (%Object.prototype% ). - Perform !
CreateDataPropertyOrThrow (wrapper, the empty String, value). - Let state be the
Record { [[ReplacerFunction]]: ReplacerFunction, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: PropertyList }. - Return ?
SerializeJSONProperty (state, the empty String, wrapper).
The stringify function is
JSON structures are allowed to be nested to any depth, but they must be acyclic. If value is or contains a cyclic structure, then the stringify function must throw a
a = [];
a[0] = a;
my_text = JSON.stringify(a); // This must throw a TypeError.
Symbolic primitive values are rendered as follows:
-
The
null value is rendered in JSON text as the String"null" . -
The
undefined value is not rendered. -
The
true value is rendered in JSON text as the String"true" . -
The
false value is rendered in JSON text as the String"false" .
String values are wrapped in QUOTATION MARK (") code units. The code units " and \ are escaped with \ prefixes. Control characters code units are replaced with escape sequences \uHHHH, or with the shorter forms, \b (BACKSPACE), \f (FORM FEED), \n (LINE FEED), \r (CARRIAGE RETURN), \t (CHARACTER TABULATION).
Finite numbers are stringified as if by calling
Values that do not have a JSON representation (such as
An object is rendered as U+007B (LEFT CURLY BRACKET) followed by zero or more properties, separated with a U+002C (COMMA), closed with a U+007D (RIGHT CURLY BRACKET). A property is a quoted String representing the key or
25.5.2.1 SerializeJSONProperty ( state, key, holder )
The abstract operation SerializeJSONProperty takes arguments state, key, and holder and returns either a
- Let value be ?
Get (holder, key). - If
Type (value) is Object or BigInt, then- Let toJSON be ?
GetV (value,"toJSON" ). - If
IsCallable (toJSON) istrue , then- Set value to ?
Call (toJSON, value, « key »).
- Set value to ?
- Let toJSON be ?
- If state.[[ReplacerFunction]] is not
undefined , then- Set value to ?
Call (state.[[ReplacerFunction]], holder, « key, value »).
- Set value to ?
- If
Type (value) is Object, then- If value has a [[NumberData]] internal slot, then
- Set value to ?
ToNumber (value).
- Set value to ?
- Else if value has a [[StringData]] internal slot, then
- Set value to ?
ToString (value).
- Set value to ?
- Else if value has a [[BooleanData]] internal slot, then
- Set value to value.[[BooleanData]].
- Else if value has a [[BigIntData]] internal slot, then
- Set value to value.[[BigIntData]].
- If value has a [[NumberData]] internal slot, then
- If value is
null , return"null" . - If value is
true , return"true" . - If value is
false , return"false" . - If
Type (value) is String, returnQuoteJSONString (value). - If
Type (value) is Number, then- If value is finite, return !
ToString (value). - Return
"null" .
- If value is finite, return !
- If
Type (value) is BigInt, throw aTypeError exception. - If
Type (value) is Object andIsCallable (value) isfalse , then- Let isArray be ?
IsArray (value). - If isArray is
true , return ?SerializeJSONArray (state, value). - Return ?
SerializeJSONObject (state, value).
- Let isArray be ?
- Return
undefined .
25.5.2.2 QuoteJSONString ( value )
The abstract operation QuoteJSONString takes argument value (a String) and returns a String. It wraps value in 0x0022 (QUOTATION MARK) code units and escapes certain other code units within it. This operation interprets value as a sequence of UTF-16 encoded code points, as described in
- Let product be the String value consisting solely of the code unit 0x0022 (QUOTATION MARK).
- For each code point C of
StringToCodePoints (value), do- If C is listed in the “Code Point” column of
Table 72 , then- Set product to the
string-concatenation of product and the escape sequence for C as specified in the “Escape Sequence” column of the corresponding row.
- Set product to the
- Else if C has a numeric value less than 0x0020 (SPACE), or if C has the same numeric value as a
leading surrogate ortrailing surrogate , then- Let unit be the code unit whose numeric value is that of C.
- Set product to the
string-concatenation of product andUnicodeEscape (unit).
- Else,
- Set product to the
string-concatenation of product andUTF16EncodeCodePoint (C).
- Set product to the
- If C is listed in the “Code Point” column of
- Set product to the
string-concatenation of product and the code unit 0x0022 (QUOTATION MARK). - Return product.
| Code Point | Unicode Character Name | Escape Sequence |
|---|---|---|
| U+0008 | BACKSPACE |
\b
|
| U+0009 | CHARACTER TABULATION |
\t
|
| U+000A | LINE FEED (LF) |
\n
|
| U+000C | FORM FEED (FF) |
\f
|
| U+000D | CARRIAGE RETURN (CR) |
\r
|
| U+0022 | QUOTATION MARK |
\"
|
| U+005C | REVERSE SOLIDUS |
\\
|
25.5.2.3 UnicodeEscape ( C )
The abstract operation UnicodeEscape takes argument C (a code unit) and returns a String. It represents C as a Unicode escape sequence. It performs the following steps when called:
- Let n be the numeric value of C.
Assert : n ≤ 0xFFFF.- Return the
string-concatenation of:- the code unit 0x005C (REVERSE SOLIDUS)
"u" - the String representation of n, formatted as a four-digit lowercase hexadecimal number, padded to the left with zeroes if necessary
25.5.2.4 SerializeJSONObject ( state, value )
The abstract operation SerializeJSONObject takes arguments state and value (an Object) and returns either a
- If state.[[Stack]] contains value, throw a
TypeError exception because the structure is cyclical. - Append value to state.[[Stack]].
- Let stepback be state.[[Indent]].
- Set state.[[Indent]] to the
string-concatenation of state.[[Indent]] and state.[[Gap]]. - If state.[[PropertyList]] is not
undefined , then- Let K be state.[[PropertyList]].
- Else,
- Let K be ?
EnumerableOwnPropertyNames (value,key ).
- Let K be ?
- Let partial be a new empty
List . - For each element P of K, do
- Let strP be ?
SerializeJSONProperty (state, P, value). - If strP is not
undefined , then- Let member be
QuoteJSONString (P). - Set member to the
string-concatenation of member and":" . - If state.[[Gap]] is not the empty String, then
- Set member to the
string-concatenation of member and the code unit 0x0020 (SPACE).
- Set member to the
- Set member to the
string-concatenation of member and strP. - Append member to partial.
- Let member be
- Let strP be ?
- If partial is empty, then
- Let final be
"{}" .
- Let final be
- Else,
- If state.[[Gap]] is the empty String, then
- Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the code unit 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"{" , properties, and"}" .
- Else,
- Let separator be the
string-concatenation of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED), and state.[[Indent]]. - Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"{" , the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and"}" .
- Let separator be the
- If state.[[Gap]] is the empty String, then
- Remove the last element of state.[[Stack]].
- Set state.[[Indent]] to stepback.
- Return final.
25.5.2.5 SerializeJSONArray ( state, value )
The abstract operation SerializeJSONArray takes arguments state and value (an
- If state.[[Stack]] contains value, throw a
TypeError exception because the structure is cyclical. - Append value to state.[[Stack]].
- Let stepback be state.[[Indent]].
- Set state.[[Indent]] to the
string-concatenation of state.[[Indent]] and state.[[Gap]]. - Let partial be a new empty
List . - Let len be ?
LengthOfArrayLike (value). - Let index be 0.
- Repeat, while index < len,
- Let strP be ?
SerializeJSONProperty (state, !ToString (𝔽(index)), value). - If strP is
undefined , then- Append
"null" to partial.
- Append
- Else,
- Append strP to partial.
- Set index to index + 1.
- Let strP be ?
- If partial is empty, then
- Let final be
"[]" .
- Let final be
- Else,
- If state.[[Gap]] is the empty String, then
- Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the code unit 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"[" , properties, and"]" .
- Else,
- Let separator be the
string-concatenation of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED), and state.[[Indent]]. - Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"[" , the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and"]" .
- Let separator be the
- If state.[[Gap]] is the empty String, then
- Remove the last element of state.[[Stack]].
- Set state.[[Indent]] to stepback.
- Return final.
The representation of arrays includes only the elements between zero and array.length - 1
25.5.3 JSON [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]: