FastBinaryWriter.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace InABox.Core
  6. {
  7. public class FastBinaryWriter : IDisposable
  8. {
  9. private List<byte[]> _data = new List<byte[]>();
  10. public void Dispose()
  11. {
  12. _data.Clear();
  13. }
  14. public byte[] GetBuffer()
  15. {
  16. var result = new byte[_data.Sum(a => a.Length)];
  17. var offset = 0;
  18. foreach (var array in _data)
  19. {
  20. Buffer.BlockCopy(array, 0, result, offset, array.Length);
  21. offset += array.Length;
  22. }
  23. return result;
  24. }
  25. public void Write(bool value)
  26. {
  27. _data.Add(BitConverter.GetBytes(value));
  28. }
  29. public void Write(byte value)
  30. {
  31. _data.Add(BitConverter.GetBytes(value));
  32. }
  33. public void Write(short value)
  34. {
  35. _data.Add(BitConverter.GetBytes(value));
  36. }
  37. public void Write(int value)
  38. {
  39. _data.Add(BitConverter.GetBytes(value));
  40. }
  41. public void Write(long value)
  42. {
  43. _data.Add(BitConverter.GetBytes(value));
  44. }
  45. public void Write(float value)
  46. {
  47. _data.Add(BitConverter.GetBytes(value));
  48. }
  49. public void Write(double value)
  50. {
  51. _data.Add(BitConverter.GetBytes(value));
  52. }
  53. protected void Write7BitEncodedInt(int value)
  54. {
  55. // Write out an int 7 bits at a time. The high bit of the byte,
  56. // when on, tells reader to continue reading more bytes.
  57. var v = (uint)value; // support negative numbers
  58. while (v >= 0x80)
  59. {
  60. Write((byte)(v | 0x80));
  61. v >>= 7;
  62. }
  63. Write((byte)v);
  64. }
  65. public void Write(string value)
  66. {
  67. Write7BitEncodedInt(value.Length);
  68. _data.Add(Encoding.UTF8.GetBytes(value));
  69. }
  70. public void Write(DateTime value)
  71. {
  72. Write(value.ToBinary());
  73. }
  74. public void Write(TimeSpan value)
  75. {
  76. Write(value.Ticks);
  77. }
  78. public void Write(Guid value)
  79. {
  80. _data.Add(value.ToByteArray());
  81. }
  82. public void Write(byte[] value)
  83. {
  84. _data.Add(value);
  85. }
  86. }
  87. }