JsArrayBuffer.cs 13 KB

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