You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
9.4 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package common
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "regexp"
  6. "strings"
  7. "sync"
  8. )
  9. // BitArray is a thread-safe implementation of a bit array.
  10. type BitArray struct {
  11. mtx sync.Mutex
  12. Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported
  13. Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported
  14. }
  15. // NewBitArray returns a new bit array.
  16. // It returns nil if the number of bits is zero.
  17. func NewBitArray(bits int) *BitArray {
  18. if bits <= 0 {
  19. return nil
  20. }
  21. return &BitArray{
  22. Bits: bits,
  23. Elems: make([]uint64, (bits+63)/64),
  24. }
  25. }
  26. // Size returns the number of bits in the bitarray
  27. func (bA *BitArray) Size() int {
  28. if bA == nil {
  29. return 0
  30. }
  31. return bA.Bits
  32. }
  33. // GetIndex returns the bit at index i within the bit array.
  34. // The behavior is undefined if i >= bA.Bits
  35. func (bA *BitArray) GetIndex(i int) bool {
  36. if bA == nil {
  37. return false
  38. }
  39. bA.mtx.Lock()
  40. defer bA.mtx.Unlock()
  41. return bA.getIndex(i)
  42. }
  43. func (bA *BitArray) getIndex(i int) bool {
  44. if i >= bA.Bits {
  45. return false
  46. }
  47. return bA.Elems[i/64]&(uint64(1)<<uint(i%64)) > 0
  48. }
  49. // SetIndex sets the bit at index i within the bit array.
  50. // The behavior is undefined if i >= bA.Bits
  51. func (bA *BitArray) SetIndex(i int, v bool) bool {
  52. if bA == nil {
  53. return false
  54. }
  55. bA.mtx.Lock()
  56. defer bA.mtx.Unlock()
  57. return bA.setIndex(i, v)
  58. }
  59. func (bA *BitArray) setIndex(i int, v bool) bool {
  60. if i >= bA.Bits {
  61. return false
  62. }
  63. if v {
  64. bA.Elems[i/64] |= (uint64(1) << uint(i%64))
  65. } else {
  66. bA.Elems[i/64] &= ^(uint64(1) << uint(i%64))
  67. }
  68. return true
  69. }
  70. // Copy returns a copy of the provided bit array.
  71. func (bA *BitArray) Copy() *BitArray {
  72. if bA == nil {
  73. return nil
  74. }
  75. bA.mtx.Lock()
  76. defer bA.mtx.Unlock()
  77. return bA.copy()
  78. }
  79. func (bA *BitArray) copy() *BitArray {
  80. c := make([]uint64, len(bA.Elems))
  81. copy(c, bA.Elems)
  82. return &BitArray{
  83. Bits: bA.Bits,
  84. Elems: c,
  85. }
  86. }
  87. func (bA *BitArray) copyBits(bits int) *BitArray {
  88. c := make([]uint64, (bits+63)/64)
  89. copy(c, bA.Elems)
  90. return &BitArray{
  91. Bits: bits,
  92. Elems: c,
  93. }
  94. }
  95. // Or returns a bit array resulting from a bitwise OR of the two bit arrays.
  96. // If the two bit-arrys have different lengths, Or right-pads the smaller of the two bit-arrays with zeroes.
  97. // Thus the size of the return value is the maximum of the two provided bit arrays.
  98. func (bA *BitArray) Or(o *BitArray) *BitArray {
  99. if bA == nil && o == nil {
  100. return nil
  101. }
  102. if bA == nil && o != nil {
  103. return o.Copy()
  104. }
  105. if o == nil {
  106. return bA.Copy()
  107. }
  108. bA.mtx.Lock()
  109. o.mtx.Lock()
  110. defer func() {
  111. bA.mtx.Unlock()
  112. o.mtx.Unlock()
  113. }()
  114. c := bA.copyBits(MaxInt(bA.Bits, o.Bits))
  115. for i := 0; i < len(c.Elems); i++ {
  116. c.Elems[i] |= o.Elems[i]
  117. }
  118. return c
  119. }
  120. // And returns a bit array resulting from a bitwise AND of the two bit arrays.
  121. // If the two bit-arrys have different lengths, this truncates the larger of the two bit-arrays from the right.
  122. // Thus the size of the return value is the minimum of the two provided bit arrays.
  123. func (bA *BitArray) And(o *BitArray) *BitArray {
  124. if bA == nil || o == nil {
  125. return nil
  126. }
  127. bA.mtx.Lock()
  128. o.mtx.Lock()
  129. defer func() {
  130. bA.mtx.Unlock()
  131. o.mtx.Unlock()
  132. }()
  133. return bA.and(o)
  134. }
  135. func (bA *BitArray) and(o *BitArray) *BitArray {
  136. c := bA.copyBits(MinInt(bA.Bits, o.Bits))
  137. for i := 0; i < len(c.Elems); i++ {
  138. c.Elems[i] &= o.Elems[i]
  139. }
  140. return c
  141. }
  142. // Not returns a bit array resulting from a bitwise Not of the provided bit array.
  143. func (bA *BitArray) Not() *BitArray {
  144. if bA == nil {
  145. return nil // Degenerate
  146. }
  147. bA.mtx.Lock()
  148. defer bA.mtx.Unlock()
  149. return bA.not()
  150. }
  151. func (bA *BitArray) not() *BitArray {
  152. c := bA.copy()
  153. for i := 0; i < len(c.Elems); i++ {
  154. c.Elems[i] = ^c.Elems[i]
  155. }
  156. return c
  157. }
  158. // Sub subtracts the two bit-arrays bitwise, without carrying the bits.
  159. // This is essentially bA.And(o.Not()).
  160. // If bA is longer than o, o is right padded with zeroes.
  161. func (bA *BitArray) Sub(o *BitArray) *BitArray {
  162. if bA == nil || o == nil {
  163. // TODO: Decide if we should do 1's complement here?
  164. return nil
  165. }
  166. bA.mtx.Lock()
  167. o.mtx.Lock()
  168. defer func() {
  169. bA.mtx.Unlock()
  170. o.mtx.Unlock()
  171. }()
  172. if bA.Bits > o.Bits {
  173. c := bA.copy()
  174. for i := 0; i < len(o.Elems)-1; i++ {
  175. c.Elems[i] &= ^c.Elems[i]
  176. }
  177. i := len(o.Elems) - 1
  178. if i >= 0 {
  179. for idx := i * 64; idx < o.Bits; idx++ {
  180. c.setIndex(idx, c.getIndex(idx) && !o.getIndex(idx))
  181. }
  182. }
  183. return c
  184. }
  185. return bA.and(o.not()) // Note degenerate case where o == nil
  186. }
  187. // IsEmpty returns true iff all bits in the bit array are 0
  188. func (bA *BitArray) IsEmpty() bool {
  189. if bA == nil {
  190. return true // should this be opposite?
  191. }
  192. bA.mtx.Lock()
  193. defer bA.mtx.Unlock()
  194. for _, e := range bA.Elems {
  195. if e > 0 {
  196. return false
  197. }
  198. }
  199. return true
  200. }
  201. // IsFull returns true iff all bits in the bit array are 1.
  202. func (bA *BitArray) IsFull() bool {
  203. if bA == nil {
  204. return true
  205. }
  206. bA.mtx.Lock()
  207. defer bA.mtx.Unlock()
  208. // Check all elements except the last
  209. for _, elem := range bA.Elems[:len(bA.Elems)-1] {
  210. if (^elem) != 0 {
  211. return false
  212. }
  213. }
  214. // Check that the last element has (lastElemBits) 1's
  215. lastElemBits := (bA.Bits+63)%64 + 1
  216. lastElem := bA.Elems[len(bA.Elems)-1]
  217. return (lastElem+1)&((uint64(1)<<uint(lastElemBits))-1) == 0
  218. }
  219. // PickRandom returns a random index in the bit array, and its value.
  220. // It uses the global randomness in `random.go` to get this index.
  221. func (bA *BitArray) PickRandom() (int, bool) {
  222. if bA == nil {
  223. return 0, false
  224. }
  225. bA.mtx.Lock()
  226. defer bA.mtx.Unlock()
  227. length := len(bA.Elems)
  228. if length == 0 {
  229. return 0, false
  230. }
  231. randElemStart := RandIntn(length)
  232. for i := 0; i < length; i++ {
  233. elemIdx := ((i + randElemStart) % length)
  234. if elemIdx < length-1 {
  235. if bA.Elems[elemIdx] > 0 {
  236. randBitStart := RandIntn(64)
  237. for j := 0; j < 64; j++ {
  238. bitIdx := ((j + randBitStart) % 64)
  239. if (bA.Elems[elemIdx] & (uint64(1) << uint(bitIdx))) > 0 {
  240. return 64*elemIdx + bitIdx, true
  241. }
  242. }
  243. PanicSanity("should not happen")
  244. }
  245. } else {
  246. // Special case for last elem, to ignore straggler bits
  247. elemBits := bA.Bits % 64
  248. if elemBits == 0 {
  249. elemBits = 64
  250. }
  251. randBitStart := RandIntn(elemBits)
  252. for j := 0; j < elemBits; j++ {
  253. bitIdx := ((j + randBitStart) % elemBits)
  254. if (bA.Elems[elemIdx] & (uint64(1) << uint(bitIdx))) > 0 {
  255. return 64*elemIdx + bitIdx, true
  256. }
  257. }
  258. }
  259. }
  260. return 0, false
  261. }
  262. // String returns a string representation of BitArray: BA{<bit-string>},
  263. // where <bit-string> is a sequence of 'x' (1) and '_' (0).
  264. // The <bit-string> includes spaces and newlines to help people.
  265. // For a simple sequence of 'x' and '_' characters with no spaces or newlines,
  266. // see the MarshalJSON() method.
  267. // Example: "BA{_x_}" or "nil-BitArray" for nil.
  268. func (bA *BitArray) String() string {
  269. return bA.StringIndented("")
  270. }
  271. // StringIndented returns the same thing as String(), but applies the indent
  272. // at every 10th bit, and twice at every 50th bit.
  273. func (bA *BitArray) StringIndented(indent string) string {
  274. if bA == nil {
  275. return "nil-BitArray"
  276. }
  277. bA.mtx.Lock()
  278. defer bA.mtx.Unlock()
  279. return bA.stringIndented(indent)
  280. }
  281. func (bA *BitArray) stringIndented(indent string) string {
  282. lines := []string{}
  283. bits := ""
  284. for i := 0; i < bA.Bits; i++ {
  285. if bA.getIndex(i) {
  286. bits += "x"
  287. } else {
  288. bits += "_"
  289. }
  290. if i%100 == 99 {
  291. lines = append(lines, bits)
  292. bits = ""
  293. }
  294. if i%10 == 9 {
  295. bits += indent
  296. }
  297. if i%50 == 49 {
  298. bits += indent
  299. }
  300. }
  301. if len(bits) > 0 {
  302. lines = append(lines, bits)
  303. }
  304. return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent))
  305. }
  306. // Bytes returns the byte representation of the bits within the bitarray.
  307. func (bA *BitArray) Bytes() []byte {
  308. bA.mtx.Lock()
  309. defer bA.mtx.Unlock()
  310. numBytes := (bA.Bits + 7) / 8
  311. bytes := make([]byte, numBytes)
  312. for i := 0; i < len(bA.Elems); i++ {
  313. elemBytes := [8]byte{}
  314. binary.LittleEndian.PutUint64(elemBytes[:], bA.Elems[i])
  315. copy(bytes[i*8:], elemBytes[:])
  316. }
  317. return bytes
  318. }
  319. // Update sets the bA's bits to be that of the other bit array.
  320. // The copying begins from the begin of both bit arrays.
  321. func (bA *BitArray) Update(o *BitArray) {
  322. if bA == nil || o == nil {
  323. return
  324. }
  325. bA.mtx.Lock()
  326. o.mtx.Lock()
  327. defer func() {
  328. bA.mtx.Unlock()
  329. o.mtx.Unlock()
  330. }()
  331. copy(bA.Elems, o.Elems)
  332. }
  333. // MarshalJSON implements json.Marshaler interface by marshaling bit array
  334. // using a custom format: a string of '-' or 'x' where 'x' denotes the 1 bit.
  335. func (bA *BitArray) MarshalJSON() ([]byte, error) {
  336. if bA == nil {
  337. return []byte("null"), nil
  338. }
  339. bA.mtx.Lock()
  340. defer bA.mtx.Unlock()
  341. bits := `"`
  342. for i := 0; i < bA.Bits; i++ {
  343. if bA.getIndex(i) {
  344. bits += `x`
  345. } else {
  346. bits += `_`
  347. }
  348. }
  349. bits += `"`
  350. return []byte(bits), nil
  351. }
  352. var bitArrayJSONRegexp = regexp.MustCompile(`\A"([_x]*)"\z`)
  353. // UnmarshalJSON implements json.Unmarshaler interface by unmarshaling a custom
  354. // JSON description.
  355. func (bA *BitArray) UnmarshalJSON(bz []byte) error {
  356. b := string(bz)
  357. if b == "null" {
  358. // This is required e.g. for encoding/json when decoding
  359. // into a pointer with pre-allocated BitArray.
  360. bA.Bits = 0
  361. bA.Elems = nil
  362. return nil
  363. }
  364. // Validate 'b'.
  365. match := bitArrayJSONRegexp.FindStringSubmatch(b)
  366. if match == nil {
  367. return fmt.Errorf("BitArray in JSON should be a string of format %q but got %s", bitArrayJSONRegexp.String(), b)
  368. }
  369. bits := match[1]
  370. // Construct new BitArray and copy over.
  371. numBits := len(bits)
  372. bA2 := NewBitArray(numBits)
  373. for i := 0; i < numBits; i++ {
  374. if bits[i] == 'x' {
  375. bA2.SetIndex(i, true)
  376. }
  377. }
  378. *bA = *bA2
  379. return nil
  380. }