BitVector.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace SharpCompress.Compressors.LZMA
  5. {
  6. internal class BitVector
  7. {
  8. private readonly uint[] _mBits;
  9. public BitVector(int length)
  10. {
  11. Length = length;
  12. _mBits = new uint[(length + 31) >> 5];
  13. }
  14. public BitVector(int length, bool initValue)
  15. {
  16. Length = length;
  17. _mBits = new uint[(length + 31) >> 5];
  18. if (initValue)
  19. {
  20. for (int i = 0; i < _mBits.Length; i++)
  21. {
  22. _mBits[i] = ~0u;
  23. }
  24. }
  25. }
  26. public BitVector(List<bool> bits)
  27. : this(bits.Count)
  28. {
  29. for (int i = 0; i < bits.Count; i++)
  30. {
  31. if (bits[i])
  32. {
  33. SetBit(i);
  34. }
  35. }
  36. }
  37. public bool[] ToArray()
  38. {
  39. bool[] bits = new bool[Length];
  40. for (int i = 0; i < bits.Length; i++)
  41. {
  42. bits[i] = this[i];
  43. }
  44. return bits;
  45. }
  46. public int Length { get; }
  47. public bool this[int index]
  48. {
  49. get
  50. {
  51. if (index < 0 || index >= Length)
  52. {
  53. throw new ArgumentOutOfRangeException(nameof(index));
  54. }
  55. return (_mBits[index >> 5] & (1u << (index & 31))) != 0;
  56. }
  57. }
  58. public void SetBit(int index)
  59. {
  60. if (index < 0 || index >= Length)
  61. {
  62. throw new ArgumentOutOfRangeException(nameof(index));
  63. }
  64. _mBits[index >> 5] |= 1u << (index & 31);
  65. }
  66. internal bool GetAndSet(int index)
  67. {
  68. if (index < 0 || index >= Length)
  69. {
  70. throw new ArgumentOutOfRangeException(nameof(index));
  71. }
  72. uint bits = _mBits[index >> 5];
  73. uint mask = 1u << (index & 31);
  74. _mBits[index >> 5] |= mask;
  75. return (bits & mask) != 0;
  76. }
  77. public override string ToString()
  78. {
  79. StringBuilder sb = new StringBuilder(Length);
  80. for (int i = 0; i < Length; i++)
  81. {
  82. sb.Append(this[i] ? 'x' : '.');
  83. }
  84. return sb.ToString();
  85. }
  86. }
  87. }