JsArrayBuffer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using Jint.Native.Object;
  2. using Jint.Native.TypedArray;
  3. using Jint.Runtime;
  4. namespace Jint.Native.ArrayBuffer;
  5. /// <summary>
  6. /// https://tc39.es/ecma262/#sec-arraybuffer-objects
  7. /// </summary>
  8. public class JsArrayBuffer : ObjectInstance
  9. {
  10. // so that we don't need to allocate while or reading setting values
  11. private readonly byte[] _workBuffer = new byte[8];
  12. internal byte[]? _arrayBufferData;
  13. internal readonly int? _arrayBufferMaxByteLength;
  14. internal readonly JsValue _arrayBufferDetachKey = Undefined;
  15. internal JsArrayBuffer(
  16. Engine engine,
  17. uint? arrayBufferMaxByteLength = null) : base(engine)
  18. {
  19. if (arrayBufferMaxByteLength is > int.MaxValue)
  20. {
  21. ExceptionHelper.ThrowRangeError(engine.Realm, "arrayBufferMaxByteLength cannot be larger than int32.MaxValue");
  22. }
  23. _arrayBufferMaxByteLength = (int?) arrayBufferMaxByteLength;
  24. }
  25. internal static byte[] CreateByteDataBlock(Realm realm, ulong byteLength)
  26. {
  27. if (byteLength > int.MaxValue)
  28. {
  29. ExceptionHelper.ThrowRangeError(realm, "Array buffer allocation failed");
  30. }
  31. return new byte[byteLength];
  32. }
  33. internal virtual int ArrayBufferByteLength => _arrayBufferData?.Length ?? 0;
  34. internal byte[]? ArrayBufferData => _arrayBufferData;
  35. internal bool IsDetachedBuffer => _arrayBufferData is null;
  36. internal bool IsFixedLengthArrayBuffer => _arrayBufferMaxByteLength is null;
  37. internal virtual bool IsSharedArrayBuffer => false;
  38. /// <summary>
  39. /// https://tc39.es/ecma262/#sec-detacharraybuffer
  40. /// </summary>
  41. internal void DetachArrayBuffer(JsValue? key = null)
  42. {
  43. key ??= Undefined;
  44. if (!SameValue(_arrayBufferDetachKey, key))
  45. {
  46. ExceptionHelper.ThrowTypeError(_engine.Realm);
  47. }
  48. _arrayBufferData = null;
  49. }
  50. /// <summary>
  51. /// https://tc39.es/ecma262/#sec-clonearraybuffer
  52. /// </summary>
  53. internal JsArrayBuffer CloneArrayBuffer(
  54. ArrayBufferConstructor constructor,
  55. int srcByteOffset,
  56. uint srcLength)
  57. {
  58. var targetBuffer = constructor.AllocateArrayBuffer(_engine.Realm.Intrinsics.ArrayBuffer, srcLength);
  59. AssertNotDetached();
  60. var srcBlock = _arrayBufferData!;
  61. var targetBlock = targetBuffer.ArrayBufferData!;
  62. // TODO SharedArrayBuffer would use this
  63. //CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  64. System.Array.Copy(srcBlock, srcByteOffset, targetBlock, 0, srcLength);
  65. return targetBuffer;
  66. }
  67. /// <summary>
  68. /// https://tc39.es/ecma262/#sec-getvaluefrombuffer
  69. /// </summary>
  70. internal TypedArrayValue GetValueFromBuffer(
  71. int byteIndex,
  72. TypedArrayElementType type,
  73. bool isTypedArray,
  74. ArrayBufferOrder order,
  75. bool? isLittleEndian = null)
  76. {
  77. return RawBytesToNumeric(type, byteIndex, isLittleEndian ?? BitConverter.IsLittleEndian);
  78. }
  79. /// <summary>
  80. /// https://tc39.es/ecma262/#sec-rawbytestonumeric
  81. /// </summary>
  82. internal TypedArrayValue RawBytesToNumeric(TypedArrayElementType type, int byteIndex, bool isLittleEndian)
  83. {
  84. var elementSize = type.GetElementSize();
  85. var rawBytes = _arrayBufferData!;
  86. // 8 byte values require a little more at the moment
  87. var needsReverse = !isLittleEndian
  88. && elementSize > 1
  89. && type is TypedArrayElementType.Float32 or TypedArrayElementType.Float64 or TypedArrayElementType.BigInt64 or TypedArrayElementType.BigUint64;
  90. if (needsReverse)
  91. {
  92. System.Array.Copy(rawBytes, byteIndex, _workBuffer, 0, elementSize);
  93. byteIndex = 0;
  94. System.Array.Reverse(_workBuffer, 0, elementSize);
  95. rawBytes = _workBuffer;
  96. }
  97. if (type == TypedArrayElementType.Float32)
  98. {
  99. // rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary32 value.
  100. var value = BitConverter.ToSingle(rawBytes, byteIndex);
  101. // If value is an IEEE 754-2019 binary32 NaN value, return the NaN Number value.
  102. if (float.IsNaN(value))
  103. {
  104. return double.NaN;
  105. }
  106. return value;
  107. }
  108. if (type == TypedArrayElementType.Float64)
  109. {
  110. // rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary64 value.
  111. var value = BitConverter.ToDouble(rawBytes, byteIndex);
  112. return value;
  113. }
  114. if (type == TypedArrayElementType.BigUint64)
  115. {
  116. var value = BitConverter.ToUInt64(rawBytes, byteIndex);
  117. return value;
  118. }
  119. if (type == TypedArrayElementType.BigInt64)
  120. {
  121. var value = BitConverter.ToInt64(rawBytes, byteIndex);
  122. return value;
  123. }
  124. TypedArrayValue? arrayValue = type switch
  125. {
  126. TypedArrayElementType.Int8 => ((sbyte) rawBytes[byteIndex]),
  127. TypedArrayElementType.Uint8 => (rawBytes[byteIndex]),
  128. TypedArrayElementType.Uint8C =>(rawBytes[byteIndex]),
  129. TypedArrayElementType.Int16 => (isLittleEndian
  130. ? (short) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  131. : (short) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  132. ),
  133. TypedArrayElementType.Uint16 => (isLittleEndian
  134. ? (ushort) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
  135. : (ushort) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
  136. ),
  137. TypedArrayElementType.Int32 => (isLittleEndian
  138. ? rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24)
  139. : rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex + 0] << 24)
  140. ),
  141. TypedArrayElementType.Uint32 => (isLittleEndian
  142. ? (uint) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24))
  143. : (uint) (rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex] << 24))
  144. ),
  145. _ => null
  146. };
  147. if (arrayValue is null)
  148. {
  149. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(type), type.ToString());
  150. }
  151. return arrayValue.Value;
  152. }
  153. /// <summary>
  154. /// https://tc39.es/ecma262/#sec-setvalueinbuffer
  155. /// </summary>
  156. internal void SetValueInBuffer(
  157. int byteIndex,
  158. TypedArrayElementType type,
  159. TypedArrayValue value,
  160. bool isTypedArray,
  161. ArrayBufferOrder order,
  162. bool? isLittleEndian = null)
  163. {
  164. var block = _arrayBufferData!;
  165. // If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  166. var rawBytes = NumericToRawBytes(type, value, isLittleEndian ?? BitConverter.IsLittleEndian);
  167. System.Array.Copy(rawBytes, 0, block, byteIndex, type.GetElementSize());
  168. }
  169. private byte[] NumericToRawBytes(TypedArrayElementType type, TypedArrayValue value, bool isLittleEndian)
  170. {
  171. byte[] rawBytes;
  172. if (type == TypedArrayElementType.Float32)
  173. {
  174. // Let rawBytes be a List whose elements are the 4 bytes that are the result of converting value to IEEE 754-2019 binary32 format using roundTiesToEven mode. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary32 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
  175. rawBytes = BitConverter.GetBytes((float) value.DoubleValue);
  176. }
  177. else if (type == TypedArrayElementType.Float64)
  178. {
  179. // Let rawBytes be a List whose elements are the 8 bytes that are the IEEE 754-2019 binary64 format encoding of value. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
  180. rawBytes = BitConverter.GetBytes(value.DoubleValue);
  181. }
  182. else if (type == TypedArrayElementType.BigInt64)
  183. {
  184. rawBytes = BitConverter.GetBytes(TypeConverter.ToBigInt64(value.BigInteger));
  185. }
  186. else if (type == TypedArrayElementType.BigUint64)
  187. {
  188. rawBytes = BitConverter.GetBytes(TypeConverter.ToBigUint64(value.BigInteger));
  189. }
  190. else
  191. {
  192. // inlined conversion for faster speed instead of getting the method in spec
  193. var doubleValue = value.DoubleValue;
  194. var intValue = double.IsNaN(doubleValue) || doubleValue == 0 || double.IsInfinity(doubleValue)
  195. ? 0
  196. : (long) doubleValue;
  197. rawBytes = _workBuffer;
  198. switch (type)
  199. {
  200. case TypedArrayElementType.Int8:
  201. rawBytes[0] = (byte) (sbyte) intValue;
  202. break;
  203. case TypedArrayElementType.Uint8:
  204. rawBytes[0] = (byte) intValue;
  205. break;
  206. case TypedArrayElementType.Uint8C:
  207. rawBytes[0] = (byte) TypeConverter.ToUint8Clamp(value.DoubleValue);
  208. break;
  209. case TypedArrayElementType.Int16:
  210. #if !NETSTANDARD2_1
  211. rawBytes = BitConverter.GetBytes((short) intValue);
  212. #else
  213. BitConverter.TryWriteBytes(rawBytes, (short) intValue);
  214. #endif
  215. break;
  216. case TypedArrayElementType.Uint16:
  217. #if !NETSTANDARD2_1
  218. rawBytes = BitConverter.GetBytes((ushort) intValue);
  219. #else
  220. BitConverter.TryWriteBytes(rawBytes, (ushort) intValue);
  221. #endif
  222. break;
  223. case TypedArrayElementType.Int32:
  224. #if !NETSTANDARD2_1
  225. rawBytes = BitConverter.GetBytes((uint) intValue);
  226. #else
  227. BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
  228. #endif
  229. break;
  230. case TypedArrayElementType.Uint32:
  231. #if !NETSTANDARD2_1
  232. rawBytes = BitConverter.GetBytes((uint) intValue);
  233. #else
  234. BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
  235. #endif
  236. break;
  237. default:
  238. ExceptionHelper.ThrowArgumentOutOfRangeException();
  239. return null;
  240. }
  241. }
  242. var elementSize = type.GetElementSize();
  243. if (!isLittleEndian && elementSize > 1)
  244. {
  245. System.Array.Reverse(rawBytes, 0, elementSize);
  246. }
  247. return rawBytes;
  248. }
  249. internal void Resize(uint newByteLength)
  250. {
  251. if (_arrayBufferMaxByteLength is null)
  252. {
  253. ExceptionHelper.ThrowTypeError(_engine.Realm);
  254. }
  255. if (newByteLength > _arrayBufferMaxByteLength)
  256. {
  257. ExceptionHelper.ThrowRangeError(_engine.Realm);
  258. }
  259. var oldBlock = _arrayBufferData ?? System.Array.Empty<byte>();
  260. var newBlock = CreateByteDataBlock(_engine.Realm, newByteLength);
  261. var copyLength = System.Math.Min(newByteLength, ArrayBufferByteLength);
  262. System.Array.Copy(oldBlock, newBlock, copyLength);
  263. _arrayBufferData = newBlock;
  264. }
  265. internal void AssertNotDetached()
  266. {
  267. if (IsDetachedBuffer)
  268. {
  269. ExceptionHelper.ThrowTypeError(_engine.Realm, "ArrayBuffer has been detached");
  270. }
  271. }
  272. }