File: BitArray%2BBitwiseOperations.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (194 lines) | stat: -rw-r--r-- 6,589 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

#if false
// FIXME: Bitwise operators disabled for now. I have two concerns:
// 1. We need to support bitwise operations over slices of bit arrays, not just
//    whole arrays.
// 2. We need to put in-place mutations as the primary operation, and they
//    need to avoid copy-on-write copies unless absolutely necessary.
//
// It seems unlikely that the operator syntax will survive these points.
// We have five (5!) separate cases:
//
//     foo |= bar
//     foo[i ..< j] |= bar
//     foo |= bar[u ..< v]
//     foo[i ..< j] |= bar[u ..< v]
//     foo[i ..< j] |= foo[k ..< l]
//
// The last one where the array is ORed with itself is particularly problematic
// -- like memcpy, these operations can easily support overlapping inputs, but
// it doesn't seem likely we can implement that with this nice slicing syntax,
// unless we are okay with forcing a CoW copy. (Which we aren't.)
//
// Even ignoring that, I would not like to end up with four overloads for each
// operator, especially not for such niche operations. So we'll entirely disable
// these for now, to prevent any shipping API from interfering with an eventual
// redesign. (This is an active area of experimentation, as it will potentially
// also affect our non-copyable container design.)

extension BitArray {
  /// Stores the result of performing a bitwise OR operation on two
  /// equal-sized bit arrays in the left-hand-side variable.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Complexity: O(left.count)
  public static func |=(left: inout Self, right: Self) {
    precondition(left.count == right.count)
    left._update { target in
      right._read { source in
        for i in 0 ..< target._words.count {
          target._mutableWords[i].formUnion(source._words[i])
        }
      }
    }
    left._checkInvariants()
  }

  /// Returns the result of performing a bitwise OR operation on two
  /// equal-sized bit arrays.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Returns: The bitwise OR of `left` and `right`.
  /// - Complexity: O(left.count)
  public static func |(left: Self, right: Self) -> Self {
    precondition(left.count == right.count)
    var result = left
    result |= right
    return result
  }

  /// Stores the result of performing a bitwise AND operation on two given
  /// equal-sized bit arrays in the left-hand-side variable.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Complexity: O(left.count)
  public static func &=(left: inout Self, right: Self) {
    precondition(left.count == right.count)
    left._update { target in
      right._read { source in
        for i in 0 ..< target._words.count {
          target._mutableWords[i].formIntersection(source._words[i])
        }
      }
    }
    left._checkInvariants()
  }

  /// Returns the result of performing a bitwise AND operation on two
  /// equal-sized bit arrays.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Returns: The bitwise AND of `left` and `right`.
  /// - Complexity: O(left.count)
  public static func &(left: Self, right: Self) -> Self {
    precondition(left.count == right.count)
    var result = left
    result &= right
    return result
  }

  /// Stores the result of performing a bitwise XOR operation on two given
  /// equal-sized bit arrays in the left-hand-side variable.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Complexity: O(left.count)
  public static func ^=(left: inout Self, right: Self) {
    precondition(left.count == right.count)
    left._update { target in
      right._read { source in
        for i in 0 ..< target._words.count {
          target._mutableWords[i].formSymmetricDifference(source._words[i])
        }
      }
    }
    left._checkInvariants()
  }

  /// Returns the result of performing a bitwise XOR operation on two
  /// equal-sized bit arrays.
  ///
  /// - Parameter left: A bit array.
  /// - Parameter right: Another bit array of the same size.
  /// - Returns: The bitwise XOR of `left` and `right`.
  /// - Complexity: O(left.count)
  public static func ^(left: Self, right: Self) -> Self {
    precondition(left.count == right.count)
    var result = left
    result ^= right
    return result
  }
}

extension BitArray {
  /// Returns the complement of the given bit array.
  ///
  /// - Parameter value: A bit array.
  /// - Returns: A bit array constructed by flipping each bit in `value`.
  ///     flipped.
  /// - Complexity: O(value.count)
  public static prefix func ~(value: Self) -> Self {
    var result = value
    result.toggleAll()
    return result
  }
}
#endif

extension BitArray {
  public mutating func toggleAll() {
    _update { handle in
      let w = handle._mutableWords
      for i in 0 ..< handle._words.count {
        w[i].formComplement()
      }
      let p = handle.end
      if p.bit > 0 {
        w[p.word].subtract(_Word(upTo: p.bit).complement())
      }
    }
    _checkInvariants()
  }

  public mutating func toggleAll(in range: Range<Int>) {
    precondition(range.upperBound <= count, "Range out of bounds")
    guard !range.isEmpty else { return }
    _update { handle in
      let words = handle._mutableWords
      let start = _BitPosition(range.lowerBound)
      let end = _BitPosition(range.upperBound)
      if start.word == end.word {
        let bits = _Word(from: start.bit, to: end.bit)
        words[start.word].formSymmetricDifference(bits)
        return
      }
      words[start.word].formSymmetricDifference(
        _Word(upTo: start.bit).complement())
      for i in stride(from: start.word + 1, to: end.word, by: 1) {
        words[i].formComplement()
      }
      if end.bit > 0 {
        words[end.word].formSymmetricDifference(_Word(upTo: end.bit))
      }
    }
  }

  @inlinable
  public mutating func toggleAll(in range: some RangeExpression<Int>) {
    toggleAll(in: range.relative(to: self))
  }
}