DtoaBuilder.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. namespace Jint.Native.Number.Dtoa;
  7. [StructLayout(LayoutKind.Auto)]
  8. internal ref struct DtoaBuilder
  9. {
  10. // allocate buffer for generated digits + extra notation + padding zeroes
  11. internal readonly Span<char> _chars;
  12. internal int Length;
  13. public DtoaBuilder(Span<char> initialBuffer)
  14. {
  15. _chars = initialBuffer;
  16. }
  17. internal void Append(char c)
  18. {
  19. _chars[Length++] = c;
  20. }
  21. internal void DecreaseLast()
  22. {
  23. _chars[Length - 1]--;
  24. }
  25. public void Reset()
  26. {
  27. Length = 0;
  28. _chars.Clear();
  29. }
  30. public char this[int i]
  31. {
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. get => _chars[i];
  34. set
  35. {
  36. _chars[i] = value;
  37. Length = System.Math.Max(Length, i + 1);
  38. }
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public ReadOnlySpan<char> Slice(int start, int length) => _chars.Slice(start, length);
  42. public override string ToString() => "[chars:" + _chars.Slice(0, Length).ToString() + "]";
  43. }