FastBinaryWriter.cs 2.4 KB

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