JsArrayBuffer.cs 12 KB

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