1
0

FilePathComponentView.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /*
  2. This source file is part of the Swift System open source project
  3. Copyright (c) 2020 Apple Inc. and the Swift System project authors
  4. Licensed under Apache License v2.0 with Runtime Library Exception
  5. See https://swift.org/LICENSE.txt for license information
  6. */
  7. // MARK: - API
  8. @available(System 0.0.2, *)
  9. extension FilePath {
  10. /// A bidirectional, range replaceable collection of the non-root components
  11. /// that make up a file path.
  12. ///
  13. /// ComponentView provides access to standard `BidirectionalCollection`
  14. /// algorithms for accessing components from the front or back, as well as
  15. /// standard `RangeReplaceableCollection` algorithms for modifying the
  16. /// file path using component or range of components granularity.
  17. ///
  18. /// Example:
  19. ///
  20. /// var path: FilePath = "/./home/./username/scripts/./tree"
  21. /// let scriptIdx = path.components.lastIndex(of: "scripts")!
  22. /// path.components.insert("bin", at: scriptIdx)
  23. /// // path is "/./home/./username/bin/scripts/./tree"
  24. ///
  25. /// path.components.removeAll { $0.kind == .currentDirectory }
  26. /// // path is "/home/username/bin/scripts/tree"
  27. @available(System 0.0.2, *)
  28. public struct ComponentView: Sendable {
  29. internal var _path: FilePath
  30. internal var _start: SystemString.Index
  31. internal init(_ path: FilePath) {
  32. self._path = path
  33. self._start = path._relativeStart
  34. _invariantCheck()
  35. }
  36. }
  37. /// View the non-root components that make up this path.
  38. public var components: ComponentView {
  39. __consuming get { ComponentView(self) }
  40. _modify {
  41. // RRC's empty init means that we can't guarantee that the yielded
  42. // view will restore our root. So copy it out first.
  43. //
  44. // TODO(perf): Small-form root (especially on Unix). Have Root
  45. // always copy out (not worth ref counting). Make sure that we're
  46. // not needlessly sliding values around or triggering a COW
  47. let rootStr = self.root?._systemString ?? SystemString()
  48. var comp = ComponentView(self)
  49. self = FilePath()
  50. defer {
  51. self = comp._path
  52. if root?._slice.elementsEqual(rootStr) != true {
  53. self.root = Root(rootStr)
  54. }
  55. }
  56. yield &comp
  57. }
  58. }
  59. }
  60. @available(System 0.0.2, *)
  61. extension FilePath.ComponentView: BidirectionalCollection {
  62. public typealias Element = FilePath.Component
  63. @available(System 0.0.2, *)
  64. public struct Index: Sendable, Comparable, Hashable {
  65. internal typealias Storage = SystemString.Index
  66. internal var _storage: Storage
  67. public static func < (lhs: Self, rhs: Self) -> Bool {
  68. lhs._storage < rhs._storage
  69. }
  70. fileprivate init(_ idx: Storage) {
  71. self._storage = idx
  72. }
  73. }
  74. public var startIndex: Index { Index(_start) }
  75. public var endIndex: Index { Index(_path._storage.endIndex) }
  76. public func index(after i: Index) -> Index {
  77. return Index(_path._parseComponent(startingAt: i._storage).nextStart)
  78. }
  79. public func index(before i: Index) -> Index {
  80. Index(_path._parseComponent(priorTo: i._storage).lowerBound)
  81. }
  82. public subscript(position: Index) -> FilePath.Component {
  83. let end = _path._parseComponent(startingAt: position._storage).componentEnd
  84. return FilePath.Component(_path, position._storage ..< end)
  85. }
  86. }
  87. @available(System 0.0.2, *)
  88. extension FilePath.ComponentView: RangeReplaceableCollection {
  89. public init() {
  90. self.init(FilePath())
  91. }
  92. // TODO(perf): We probably want to have concrete overrides or generic
  93. // specializations taking FP.ComponentView and
  94. // FP.ComponentView.SubSequence because we
  95. // can just memcpy in those cases. We
  96. // probably want to do that for all RRC operations.
  97. public mutating func replaceSubrange<C>(
  98. _ subrange: Range<Index>, with newElements: C
  99. ) where C : Collection, Self.Element == C.Element {
  100. defer {
  101. _path._invariantCheck()
  102. _invariantCheck()
  103. }
  104. if isEmpty {
  105. _path = FilePath(root: _path.root, newElements)
  106. return
  107. }
  108. let range = subrange.lowerBound._storage ..< subrange.upperBound._storage
  109. if newElements.isEmpty {
  110. let fromEnd = subrange.upperBound == endIndex
  111. _path._storage.removeSubrange(range)
  112. if fromEnd {
  113. _path._removeTrailingSeparator()
  114. }
  115. return
  116. }
  117. // TODO(perf): Avoid extra allocation by sliding elements down and
  118. // filling in the bytes ourselves.
  119. // If we're inserting at the end, we need a leading separator.
  120. var str = SystemString()
  121. let atEnd = subrange.lowerBound == endIndex
  122. if atEnd {
  123. str.append(platformSeparator)
  124. }
  125. str.appendComponents(components: newElements)
  126. if !atEnd {
  127. str.append(platformSeparator)
  128. }
  129. _path._storage.replaceSubrange(range, with: str)
  130. }
  131. }
  132. @available(System 0.0.2, *)
  133. extension FilePath {
  134. /// Create a file path from a root and a collection of components.
  135. public init<C: Collection>(
  136. root: Root?, _ components: C
  137. ) where C.Element == Component {
  138. var str = root?._systemString ?? SystemString()
  139. str.appendComponents(components: components)
  140. self.init(str)
  141. }
  142. /// Create a file path from a root and any number of components.
  143. public init(root: Root?, components: Component...) {
  144. self.init(root: root, components)
  145. }
  146. /// Create a file path from an optional root and a slice of another path's
  147. /// components.
  148. public init(root: Root?, _ components: ComponentView.SubSequence) {
  149. var str = root?._systemString ?? SystemString()
  150. let (start, end) =
  151. (components.startIndex._storage, components.endIndex._storage)
  152. str.append(contentsOf: components.base._slice[start..<end])
  153. self.init(str)
  154. }
  155. }
  156. // MARK: - Internals
  157. @available(System 0.0.2, *)
  158. extension FilePath.ComponentView: _PathSlice {
  159. internal var _range: Range<SystemString.Index> {
  160. _start ..< _path._storage.endIndex
  161. }
  162. internal init(_ str: SystemString) {
  163. fatalError("TODO: consider dropping proto req")
  164. }
  165. }
  166. // MARK: - Invariants
  167. @available(System 0.0.2, *)
  168. extension FilePath.ComponentView {
  169. internal func _invariantCheck() {
  170. #if DEBUG
  171. if isEmpty {
  172. precondition(_path.isEmpty == (_path.root == nil))
  173. return
  174. }
  175. // If path has a root,
  176. if _path.root != nil {
  177. precondition(first!._slice.startIndex > _path._storage.startIndex)
  178. precondition(first!._slice.startIndex == _path._relativeStart)
  179. }
  180. self.forEach { $0._invariantCheck() }
  181. if let base = last {
  182. precondition(base._slice.endIndex == _path._storage.endIndex)
  183. }
  184. precondition(FilePath(root: _path.root, self) == _path)
  185. #endif // DEBUG
  186. }
  187. }