<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Inga X</title>
	<atom:link href="https://ingax.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://ingax.com</link>
	<description>An education platform for people passionate about software engineering to learn problem solving techniques and useful algorithms and data structures</description>
	<lastBuildDate>Fri, 25 Nov 2022 16:26:14 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.5.18</generator>
	<item>
		<title>A Tale of Two Features</title>
		<link>https://ingax.com/a-tale-of-two-features/</link>
					<comments>https://ingax.com/a-tale-of-two-features/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Fri, 25 Nov 2022 16:26:13 +0000</pubDate>
				<category><![CDATA[Stories]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=7038</guid>

					<description><![CDATA[By George Pirocanac I have often been asked, “What is the most memorable bug that you have encountered in your testing career?” For me, it...]]></description>
										<content:encoded><![CDATA[
<p>By George Pirocanac</p>



<p class="has-drop-cap">I have often been asked, “What is the most memorable bug that you have encountered in your testing career?” For me, it is hands down a bug that happened quite a few years ago. I was leading an Engineering Productivity team that supported Google App Engine. At that time App Engine was still in its early stages, and there were many challenges associated with testing rapidly evolving features. Our testing frameworks and processes were also evolving, so it was an exciting time to be on the team. <br>What makes this bug so memorable is that I spent so much time developing a comprehensive suite of test scenarios, yet a failure occurred during such an obvious use case that it left me shaking my head and wondering how I had missed it. Even with many years of testing experience it can be very humbling to construct scenarios that adequately mirror what will happen in the field.<br>I’ll try to provide enough background for the reader to play along and see if they can determine the anomalous scenario. As a further hint, the problem resulted from the interaction of two App Engine features, so I like calling this story <em>A Tale of Two Features.</em></p>



<h2>Feature 1 &#8211; Datastore Admin (backup, restore, delete)</h2>



<p>Google App Engine was released 13 years ago as Google’s first Cloud product. It allowed users to build and deploy highly scalable web applications in the Cloud. To support this, it had its own scalable database called the Datastore. An administration console allowed users to manage the application and its Datastore through a web interface. Users wrote applications that consisted of request handlers that App Engine invoked according to the URL that was specified. The handlers could call App Engine services like Datastore through a remote procedure call (RPC) mechanism. Figure 1 illustrates this flow.</p>



<figure class="wp-block-image"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEh0cVtb0BQOCfEOdYOLTEzlkK6wlHKjVPjCdIUxMjMR8xH7dG2zAClwF1rdSiYZKoH9ZODmhh46bvRoZNh1m6GnBRcdO5-bJEOOBJXrH5GObECmzIKNS6w0aladuki_mY3bM1WaDl7sdTrvvbYTsJ1cY5xhWO1idwxPAnN-UrTSYyALq8JnxQ=s736" target="_blank" rel="noreferrer noopener"><img src="https://blogger.googleusercontent.com/img/a/AVvXsEh0cVtb0BQOCfEOdYOLTEzlkK6wlHKjVPjCdIUxMjMR8xH7dG2zAClwF1rdSiYZKoH9ZODmhh46bvRoZNh1m6GnBRcdO5-bJEOOBJXrH5GObECmzIKNS6w0aladuki_mY3bM1WaDl7sdTrvvbYTsJ1cY5xhWO1idwxPAnN-UrTSYyALq8JnxQ=w640-h194" alt=""/></a></figure>



<p>The first feature in this&nbsp;<em>Tale of Two Features</em>&nbsp;resided in the administration console, providing the ability to back up, restore, and delete selected or all of an application’s entities in the Datastore. It was implemented in a clever way that incorporated it directly into the application, rather than as an independent utility. As part of the application it could freely operate on the Datastore and incur the same billing charges as other datastore operations within the application. When the feature was invoked, traffic would be sent to its handler and the application would process it. Figure 2 illustrates this request flow.</p>



<figure class="wp-block-image"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjqOeIzD2oUVRnK14nCw8j5vxEcBvN98tBirvh3sj_P3a2E29GoZTKeSvgl2ePALbtxdVRSZ2R3tIWwPL93U3ckniR0hkDQBmKyTXqfvTzOjpLcNCVlEfLSBGUfzMD2PX6a5q4zrI8hUbJbbmPWnz5HDlWSJXQ_1LK7Hy92zVGIkx7KRZuFQQ=s736" target="_blank" rel="noreferrer noopener"><img src="https://blogger.googleusercontent.com/img/a/AVvXsEjqOeIzD2oUVRnK14nCw8j5vxEcBvN98tBirvh3sj_P3a2E29GoZTKeSvgl2ePALbtxdVRSZ2R3tIWwPL93U3ckniR0hkDQBmKyTXqfvTzOjpLcNCVlEfLSBGUfzMD2PX6a5q4zrI8hUbJbbmPWnz5HDlWSJXQ_1LK7Hy92zVGIkx7KRZuFQQ=w640-h410" alt=""/></a></figure>



<p>By the time this memorable bug occurred, this Datastore administration feature was mature, well tested, and stable. No changes were being made to it.</p>



<h2>Feature 2 &#8211; Utilities for Migrating to the HR &#8211; Datastore</h2>



<p>The second feature (or more accurately, set of features) came at least a year after the first feature was released and stable. It helped users migrate their applications to a new High Replication (HR) Datastore. The HR Datastore was more reliable than its predecessor, but using it meant creating a new application and copying over all the data from the old Datastore. To support such migrations, App Engine developers added two new features to the administration console. The first copied all the data from the Datastore of one application to another, and the second redirected all traffic from one application to another. The latter was particularly useful because it meant the new application would seamlessly receive the traffic after a migration. This set of features was written by another team, and we in Engineering Productivity supported them by creating processes for testing various Datastore migrations. The migration-support features were thoroughly tested and released to developers. Figure 3 illustrates the request flow of the redirection feature.</p>



<figure class="wp-block-image"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhR9Tw44yOC48vvAARE70a2JNLAB5EcYPimIFeuGBNnm4Qbjf5d7W4NzZ-s-j5BU-b0-u2cFX1q9AL0e-QNkVabq3CpiTLZzVSA7fjrYTjHXofw0WErosSUgI_XHygJbMRIyuoPno0b4JNzgrXPXSPz2xLhZqKPUy8gkISvOZS_mjrhAKsprQ=s735" target="_blank" rel="noreferrer noopener"><img src="https://blogger.googleusercontent.com/img/a/AVvXsEhR9Tw44yOC48vvAARE70a2JNLAB5EcYPimIFeuGBNnm4Qbjf5d7W4NzZ-s-j5BU-b0-u2cFX1q9AL0e-QNkVabq3CpiTLZzVSA7fjrYTjHXofw0WErosSUgI_XHygJbMRIyuoPno0b4JNzgrXPXSPz2xLhZqKPUy8gkISvOZS_mjrhAKsprQ=w640-h364" alt=""/></a></figure>



<h2>What Could Possibly Go Wrong?</h2>



<p>So this was the situation when we released these utilities for migrating to the new Datastore. We were very confident that they worked, as we had tested migrations of many different types and sizes of Datastore entities. We had also tested that a migration could be interrupted without data loss. All checked out fine. I was confident that this new feature would work, yet soon after we released it, we started getting problem reports.<br>If you have been playing along, now is the time to ask yourself,&nbsp; “What could possibly go wrong?” As an added hint, the problem reports claimed that all the data in the newly migrated application was disappearing.</p>



<h2>What Did Go Wrong</h2>



<p>As mentioned above, developers began to report that data was disappearing from their newly migrated applications. It wasn’t at all common, yet of course it is most disconcerting when data “just disappears.” We had to investigate how this could occur. Our standard processes ensured that we had internal backups of the data, which were promptly restored. In parallel we tried to reproduce the problem, but we couldn’t—at least until we figured out what was happening. As I mentioned earlier, once we understood it, it was quite obvious, but that only made it all the more painful that we missed it.<br>What was happening was that, after migrating and automatically redirecting traffic to the new application, a number of customers thought they still needed to delete the data from their old application, so they used the first Datastore admin feature to do that. As expected, the feature sent traffic to that application to delete the entities from the Datastore. But that traffic was now being automatically redirected to the new application, and voila—all the data that had been copied earlier was now deleted there. Since only a handful of developers tried to delete the data from their old applications, this explained why the problem occurred only rarely. Figure 4 illustrates this request flow.</p>



<figure class="wp-block-image"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjRpHqaAL8XEJd2_MiESEmXnj8sqqctGvogjgRsw9Ty40zwQbmhfA9CLeECNR3dSh5PxIkN1HC3AnydKx-ef6LzkcC3E6QrKi23Y5IqZPPB9t38DIQylqsW3o-VIVhFpi0OkeX5YxkMmWk0Etiy4Php_XQWMDDeG0ZPirNEFM6Sr1Mg9Y85xg=s735" target="_blank" rel="noreferrer noopener"><img src="https://blogger.googleusercontent.com/img/a/AVvXsEjRpHqaAL8XEJd2_MiESEmXnj8sqqctGvogjgRsw9Ty40zwQbmhfA9CLeECNR3dSh5PxIkN1HC3AnydKx-ef6LzkcC3E6QrKi23Y5IqZPPB9t38DIQylqsW3o-VIVhFpi0OkeX5YxkMmWk0Etiy4Php_XQWMDDeG0ZPirNEFM6Sr1Mg9Y85xg=w640-h510" alt=""/></a></figure>



<p>Obvious, isn’t it, once you know what is happening.</p>



<h2>Lessons Learned</h2>



<p>This all occurred years ago, and App Engine is based on a far different and more robust framework today. Datastore migrations are but a memory from the past, yet this experience made a great impression on me.<br>The most important thing I learned from this experience is that, while it is important to test features for their functionality, it’s also important to think of them as part of workflows. In performing our testing we exercised a very limited number of steps in the migration process workflow and omitted a very reasonable step at the end: trying to delete the data from the old application. Our focus was in testing the variability of contents in the Datastore rather than different steps in the migration process. It was this focus that kept our eyes away from the relatively obvious failure case.<br>Another thing I learned was that this bug might have been caught if the developer of the first feature had been in the design review for the second set of migration features (particularly the feature that automatically redirects traffic). Unfortunately, that person had already joined a new team. A key step in reducing bugs can occur at the design stage if “what-if” questions are being asked.<br>Finally, I was enormously impressed that we were able to recover so quickly. Protecting against data loss is one of the most important aspects of Cloud management, and being able to recover from mistakes is at least as important as trying to prevent them. I have the utmost respect for my coworkers in Site Reliability Engineering (SRE).</p>



<h2>References</h2>



<p><a href="https://cloud.google.com/appengine/docs/standard/python/an-overview-of-app-engine">An Overview of Google App Engine</a></p>



<p><a href="https://testing.googleblog.com/2022/02/a-tale-of-two-features.html">A Tale of Two Features</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/a-tale-of-two-features/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Tower of Hanoi Puzzle</title>
		<link>https://ingax.com/tower-of-hanoi-puzzle/</link>
					<comments>https://ingax.com/tower-of-hanoi-puzzle/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 17 Nov 2022 18:19:25 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=7031</guid>

					<description><![CDATA[The&#160;Tower of Hanoi&#160;(also called&#160;The problem of Benares Temple[1]&#160;or&#160;Tower of Brahma&#160;or&#160;Lucas&#8217; Tower[2]&#160;and sometimes pluralized as&#160;Towers, or simply&#160;pyramid puzzle[3]) is a&#160;mathematical game&#160;or&#160;puzzle&#160;consisting of three rods and a...]]></description>
										<content:encoded><![CDATA[
<p>The&nbsp;<strong>Tower of Hanoi</strong>&nbsp;(also called&nbsp;<strong>The problem of Benares Temple</strong><sup><a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi#cite_note-oeis-1">[1]</a></sup>&nbsp;or&nbsp;<strong>Tower of Brahma</strong>&nbsp;or&nbsp;<strong>Lucas&#8217; Tower</strong><sup><a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi#cite_note-2">[2]</a></sup>&nbsp;and sometimes pluralized as&nbsp;<strong>Towers</strong>, or simply&nbsp;<strong>pyramid puzzle</strong><sup><a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi#cite_note-3">[3]</a></sup>) is a&nbsp;<a href="https://en.wikipedia.org/wiki/Mathematical_game">mathematical game</a>&nbsp;or&nbsp;<a href="https://en.wikipedia.org/wiki/Puzzle">puzzle</a>&nbsp;consisting of three rods and a number of disks of various&nbsp;<a href="https://en.wikipedia.org/wiki/Diameter">diameters</a>, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a&nbsp;<a href="https://en.wikipedia.org/wiki/Cone">conical</a>&nbsp;shape. The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:</p>



<ol><li>Only one disk may be moved at a time.</li><li>Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.</li><li>No disk may be placed on top of a disk that is smaller than it.</li></ol>



<p>Prints n moves in the Tower of Hanoi puzzle.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func tower_of_hanoi(_ n: Int) -> [[Int]] {
    var result: [[Int]] = []
    
    func helper(_ n: Int, _ src: Int, _ aux: Int, _ dst: Int) {
        if n == 1  {
            result.append([src, dst])
            return
        }
        
        helper(n - 1, src, dst, aux)
        result.append([src, dst])
        helper(n - 1, aux, src, dst)
    }
    
    helper(n, 1, 2, 3)
    
    return result
}

print(tower_of_hanoi(3))</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/tower-of-hanoi-puzzle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Deque Template in Swift</title>
		<link>https://ingax.com/deque-template-in-swift/</link>
					<comments>https://ingax.com/deque-template-in-swift/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Tue, 25 Oct 2022 18:16:12 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[Templates]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=7010</guid>

					<description><![CDATA[https://github.com/apple/swift-collections/blob/main/Sources/DequeModule/Deque.swift]]></description>
										<content:encoded><![CDATA[
<pre class="wp-block-prismatic-blocks"><code class="language-swift">@frozen
public struct Deque<Element> {
  @usableFromInline
  internal typealias _Slot = _DequeSlot

  @usableFromInline
  internal var _storage: _Storage

  @inlinable
  internal init(_storage: _Storage) {
    self._storage = _storage
  }
  
  @inlinable
  public init(minimumCapacity: Int) {
    self._storage = _Storage(minimumCapacity: minimumCapacity)
  }
}

@usableFromInline
@frozen
internal struct _DequeSlot {
  @usableFromInline
  internal var position: Int

  @inlinable
  @inline(__always)
  init(at position: Int) {
    assert(position >= 0)
    self.position = position
  }
}

extension _DequeSlot {
  @inlinable
  @inline(__always)
  internal static var zero: Self { Self(at: 0) }

  @inlinable
  @inline(__always)
  internal func advanced(by delta: Int) -> Self {
    Self(at: position &+ delta)
  }

  @inlinable
  @inline(__always)
  internal func orIfZero(_ value: Int) -> Self {
    guard position > 0 else { return Self(at: value) }
    return self
  }
}

extension _DequeSlot: CustomStringConvertible {
  @usableFromInline
  internal var description: String {
    "@\(position)"
  }
}

extension _DequeSlot: Equatable {
  @inlinable
  @inline(__always)
  static func ==(left: Self, right: Self) -> Bool {
    left.position == right.position
  }
}

extension _DequeSlot: Comparable {
  @inlinable
  @inline(__always)
  static func <(left: Self, right: Self) -> Bool {
    left.position < right.position
  }
}

extension Range where Bound == _DequeSlot {
  @inlinable
  @inline(__always)
  internal var _count: Int { upperBound.position - lowerBound.position }
}

extension Deque {
  @frozen
  @usableFromInline
  struct _Storage {
    @usableFromInline
    internal typealias _Buffer = ManagedBufferPointer<_DequeBufferHeader, Element>

    @usableFromInline
    internal var _buffer: _Buffer

    @inlinable
    @inline(__always)
    internal init(_buffer: _Buffer) {
      self._buffer = _buffer
    }
  }
}

extension Deque._Storage: CustomStringConvertible {
  @usableFromInline
  internal var description: String {
    "Deque<\(Element.self)>._Storage\(_buffer.header)"
  }
}

extension Deque._Storage {
  @inlinable
  internal init() {
    self.init(_buffer: _Buffer(unsafeBufferObject: _emptyDequeStorage))
  }

  @inlinable
  internal init(_ object: _DequeBuffer<Element>) {
    self.init(_buffer: _Buffer(unsafeBufferObject: object))
  }

  @inlinable
  internal init(minimumCapacity: Int) {
    let object = _DequeBuffer<Element>.create(
      minimumCapacity: minimumCapacity,
      makingHeaderWith: {
        #if os(OpenBSD)
        let capacity = minimumCapacity
        #else
        let capacity = $0.capacity
        #endif
        return _DequeBufferHeader(capacity: capacity, count: 0, startSlot: .zero)
      })
    self.init(_buffer: _Buffer(unsafeBufferObject: object))
  }
}

extension Deque._Storage {
  #if COLLECTIONS_INTERNAL_CHECKS
  @usableFromInline @inline(never) @_effects(releasenone)
  internal func _checkInvariants() {
    _buffer.withUnsafeMutablePointerToHeader { $0.pointee._checkInvariants() }
  }
  #else
  @inlinable @inline(__always)
  internal func _checkInvariants() {}
  #endif // COLLECTIONS_INTERNAL_CHECKS
}

extension Deque._Storage {
  @inlinable
  @inline(__always)
  internal var identity: AnyObject { _buffer.buffer }


  @inlinable
  @inline(__always)
  internal var capacity: Int {
    _buffer.withUnsafeMutablePointerToHeader { $0.pointee.capacity }
  }

  @inlinable
  @inline(__always)
  internal var count: Int {
    _buffer.withUnsafeMutablePointerToHeader { $0.pointee.count }
  }

  @inlinable
  @inline(__always)
  internal var startSlot: _DequeSlot {
    _buffer.withUnsafeMutablePointerToHeader { $0.pointee.startSlot
    }
  }
}

extension Deque._Storage {
  @usableFromInline
  internal typealias Index = Int

  @usableFromInline
  internal typealias _UnsafeHandle = Deque._UnsafeHandle

  @inlinable
  @inline(__always)
  internal func read<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
    try _buffer.withUnsafeMutablePointers { header, elements in
      let handle = _UnsafeHandle(header: header,
                                 elements: elements,
                                 isMutable: false)
      return try body(handle)
    }
  }

  @inlinable
  @inline(__always)
  internal func update<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
    try _buffer.withUnsafeMutablePointers { header, elements in
      let handle = _UnsafeHandle(header: header,
                                 elements: elements,
                                 isMutable: true)
      return try body(handle)
    }
  }
}

extension Deque._Storage {
  @inlinable
  @inline(__always)
  internal mutating func isUnique() -> Bool {
    _buffer.isUniqueReference()
  }

  @inlinable
  @inline(__always)
  internal mutating func ensureUnique() {
    if isUnique() { return }
    self._makeUniqueCopy()
  }

  @inlinable
  @inline(never)
  internal mutating func _makeUniqueCopy() {
    self = self.read { $0.copyElements() }
  }

  @inlinable
  @inline(__always)
  internal static var growthFactor: Double { 1.5 }

  @usableFromInline
  internal func _growCapacity(
    to minimumCapacity: Int,
    linearly: Bool
  ) -> Int {
    if linearly { return Swift.max(capacity, minimumCapacity) }
    return Swift.max(Int((Self.growthFactor * Double(capacity)).rounded(.up)),
                     minimumCapacity)
  }

  @inlinable
  @inline(__always)
  internal mutating func ensureUnique(
    minimumCapacity: Int,
    linearGrowth: Bool = false
  ) {
    let unique = isUnique()
    if _slowPath(capacity < minimumCapacity || !unique) {
      _ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: linearGrowth)
    }
  }

  @inlinable
  internal mutating func _ensureUnique(
    minimumCapacity: Int,
    linearGrowth: Bool
  ) {
    if capacity >= minimumCapacity {
      assert(!self.isUnique())
      self = self.read { $0.copyElements() }
    } else if isUnique() {
      let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
      self = self.update { source in
        source.moveElements(minimumCapacity: minimumCapacity)
      }
    } else {
      let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
      self = self.read { source in
        source.copyElements(minimumCapacity: minimumCapacity)
      }
    }
  }
}

@usableFromInline
internal struct _DequeBufferHeader {
  @usableFromInline
  var capacity: Int

  @usableFromInline
  var count: Int

  @usableFromInline
  var startSlot: _DequeSlot

  @usableFromInline
  init(capacity: Int, count: Int, startSlot: _DequeSlot) {
    self.capacity = capacity
    self.count = count
    self.startSlot = startSlot
    _checkInvariants()
  }

  #if COLLECTIONS_INTERNAL_CHECKS
  @usableFromInline @inline(never) @_effects(releasenone)
  internal func _checkInvariants() {
    precondition(capacity >= 0)
    precondition(count >= 0 && count <= capacity)
    precondition(startSlot.position >= 0 && startSlot.position <= capacity)
  }
  #else
  @inlinable @inline(__always)
  internal func _checkInvariants() {}
  #endif
}

extension _DequeBufferHeader: CustomStringConvertible {
  @usableFromInline
  internal var description: String {
    "(capacity: \(capacity), count: \(count), startSlot: \(startSlot))"
  }
}

@_fixed_layout
@usableFromInline
internal class _DequeBuffer<Element>: ManagedBuffer<_DequeBufferHeader, Element> {
  @inlinable
  deinit {
    self.withUnsafeMutablePointers { header, elements in
      header.pointee._checkInvariants()

      let capacity = header.pointee.capacity
      let count = header.pointee.count
      let startSlot = header.pointee.startSlot

      if startSlot.position + count <= capacity {
        (elements + startSlot.position).deinitialize(count: count)
      } else {
        let firstRegion = capacity - startSlot.position
        (elements + startSlot.position).deinitialize(count: firstRegion)
        elements.deinitialize(count: count - firstRegion)
      }
    }
  }
}

extension _DequeBuffer: CustomStringConvertible {
  @usableFromInline
  internal var description: String {
    withUnsafeMutablePointerToHeader { "_DequeStorage<\(Element.self)>\($0.pointee)" }
  }
}

@usableFromInline
internal let _emptyDequeStorage = _DequeBuffer<Void>.create(
  minimumCapacity: 0,
  makingHeaderWith: { _ in
    _DequeBufferHeader(capacity: 0, count: 0, startSlot: .init(at: 0))
  })

extension Deque {
  @frozen
  @usableFromInline
  internal struct _UnsafeHandle {
    @usableFromInline
    let _header: UnsafeMutablePointer<_DequeBufferHeader>
    @usableFromInline
    let _elements: UnsafeMutablePointer<Element>
    #if DEBUG
    @usableFromInline
    let _isMutable: Bool
    #endif

    @inlinable
    @inline(__always)
    init(
      header: UnsafeMutablePointer<_DequeBufferHeader>,
      elements: UnsafeMutablePointer<Element>,
      isMutable: Bool
    ) {
      self._header = header
      self._elements = elements
      #if DEBUG
      self._isMutable = isMutable
      #endif
    }
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  @inline(__always)
  func assertMutable() {
    #if DEBUG
    assert(_isMutable)
    #endif
  }
}

extension Deque._UnsafeHandle {
  @usableFromInline
  internal typealias Slot = _DequeSlot

  @inlinable
  @inline(__always)
  var header: _DequeBufferHeader {
    _header.pointee
  }

  @inlinable
  @inline(__always)
  var capacity: Int {
    _header.pointee.capacity
  }

  @inlinable
  @inline(__always)
  var count: Int {
    get { _header.pointee.count }
    nonmutating set { _header.pointee.count = newValue }
  }

  @inlinable
  @inline(__always)
  var startSlot: Slot {
    get { _header.pointee.startSlot }
    nonmutating set { _header.pointee.startSlot = newValue }
  }

  @inlinable
  @inline(__always)
  func ptr(at slot: Slot) -> UnsafeMutablePointer<Element> {
    assert(slot.position >= 0 && slot.position <= capacity)
    return _elements + slot.position
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  @inline(__always)
  var mutableBuffer: UnsafeMutableBufferPointer<Element> {
    assertMutable()
    return .init(start: _elements, count: _header.pointee.capacity)
  }

  @inlinable
  internal func buffer(for range: Range<Slot>) -> UnsafeBufferPointer<Element> {
    assert(range.upperBound.position <= capacity)
    return .init(start: _elements + range.lowerBound.position, count: range._count)
  }

  @inlinable
  @inline(__always)
  internal func mutableBuffer(for range: Range<Slot>) -> UnsafeMutableBufferPointer<Element> {
    assertMutable()
    return .init(mutating: buffer(for: range))
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  @inline(__always)
  internal var limSlot: Slot {
    Slot(at: capacity)
  }

  @inlinable
  internal func slot(after slot: Slot) -> Slot {
    assert(slot.position < capacity)
    let position = slot.position + 1
    if position >= capacity {
      return Slot(at: 0)
    }
    return Slot(at: position)
  }

  @inlinable
  internal func slot(before slot: Slot) -> Slot {
    assert(slot.position < capacity)
    if slot.position == 0 { return Slot(at: capacity - 1) }
    return Slot(at: slot.position - 1)
  }

  @inlinable
  internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot {
    assert(slot.position <= capacity)
    let position = slot.position + delta
    if delta >= 0 {
      if position >= capacity { return Slot(at: position - capacity) }
    } else {
      if position < 0 { return Slot(at: position + capacity) }
    }
    return Slot(at: position)
  }

  @inlinable
  @inline(__always)
  internal var endSlot: Slot {
    slot(startSlot, offsetBy: count)
  }

  /// Return the storage slot corresponding to the specified offset, which may
  /// or may not address an existing element.
  @inlinable
  internal func slot(forOffset offset: Int) -> Slot {
    assert(offset >= 0)
    assert(offset <= capacity) // Not `count`!
    // Note: The use of wrapping addition/subscription is justified here by the
    // fact that `offset` is guaranteed to fall in the range `0 ..< capacity`.
    // Eliminating the overflow checks leads to a measurable speedup for
    // random-access subscript operations. (Up to 2x on some microbenchmarks.)
    let position = startSlot.position &#038;+ offset
    guard position < capacity else { return Slot(at: position &#038;- capacity) }
    return Slot(at: position)
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func segments() -> _UnsafeWrappedBuffer<Element> {
    let wrap = capacity - startSlot.position
    if count <= wrap {
      return .init(start: ptr(at: startSlot), count: count)
    }
    return .init(first: ptr(at: startSlot), count: wrap,
                 second: ptr(at: .zero), count: count - wrap)
  }

  @inlinable
  internal func segments(
    forOffsets offsets: Range<Int>
  ) -> _UnsafeWrappedBuffer<Element> {
    assert(offsets.lowerBound >= 0 && offsets.upperBound <= count)
    let lower = slot(forOffset: offsets.lowerBound)
    let upper = slot(forOffset: offsets.upperBound)
    if offsets.count == 0 || lower < upper {
      return .init(start: ptr(at: lower), count: offsets.count)
    }
    return .init(first: ptr(at: lower), count: capacity - lower.position,
                 second: ptr(at: .zero), count: upper.position)
  }

  @inlinable
  @inline(__always)
  internal func mutableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
    assertMutable()
    return .init(mutating: segments())
  }

  @inlinable
  @inline(__always)
  internal func mutableSegments(
    forOffsets range: Range<Int>
  ) -> _UnsafeMutableWrappedBuffer<Element> {
    assertMutable()
    return .init(mutating: segments(forOffsets: range))
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func availableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
    assertMutable()
    let endSlot = self.endSlot
    guard count < capacity else { return .init(start: ptr(at: endSlot), count: 0) }
    if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) }
    return .init(mutableBuffer(for: endSlot ..< limSlot),
                 mutableBuffer(for: .zero ..< startSlot))
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  @discardableResult
  func initialize(
    at start: Slot,
    from source: UnsafeBufferPointer<Element>
  ) -> Slot {
    assert(start.position + source.count <= capacity)
    guard source.count > 0 else { return start }
    ptr(at: start).initialize(from: source.baseAddress!, count: source.count)
    return Slot(at: start.position + source.count)
  }

  @inlinable
  @inline(__always)
  @discardableResult
  func moveInitialize(
    at start: Slot,
    from source: UnsafeMutableBufferPointer<Element>
  ) -> Slot {
    assert(start.position + source.count <= capacity)
    guard source.count > 0 else { return start }
    ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count)
    return Slot(at: start.position + source.count)
  }

  @inlinable
  @inline(__always)
  @discardableResult
  public func move(
    from source: Slot,
    to target: Slot,
    count: Int
  ) -> (source: Slot, target: Slot) {
    assert(count >= 0)
    assert(source.position + count <= self.capacity)
    assert(target.position + count <= self.capacity)
    guard count > 0 else { return (source, target) }
    ptr(at: target).moveInitialize(from: ptr(at: source), count: count)
    return (slot(source, offsetBy: count), slot(target, offsetBy: count))
  }
}



extension Deque._UnsafeHandle {
  @inlinable
  internal func copyElements() -> Deque._Storage {
    let object = _DequeBuffer<Element>.create(
      minimumCapacity: capacity,
      makingHeaderWith: { _ in header })
    let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
    guard self.count > 0 else { return result }
    result.update { target in
      let source = self.segments()
      target.initialize(at: startSlot, from: source.first)
      if let second = source.second {
        target.initialize(at: .zero, from: second)
      }
    }
    return result
  }

  @inlinable
  internal func copyElements(minimumCapacity: Int) -> Deque._Storage {
    assert(minimumCapacity >= count)
    let object = _DequeBuffer<Element>.create(
      minimumCapacity: minimumCapacity,
      makingHeaderWith: {
        #if os(OpenBSD)
        let capacity = minimumCapacity
        #else
        let capacity = $0.capacity
        #endif
        return _DequeBufferHeader(
          capacity: capacity,
          count: count,
          startSlot: .zero)
      })
    let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
    guard count > 0 else { return result }
    result.update { target in
      assert(target.count == count && target.startSlot.position == 0)
      let source = self.segments()
      let next = target.initialize(at: .zero, from: source.first)
      if let second = source.second {
        target.initialize(at: next, from: second)
      }
    }
    return result
  }

  @inlinable
  internal func moveElements(minimumCapacity: Int) -> Deque._Storage {
    assertMutable()
    let count = self.count
    assert(minimumCapacity >= count)
    let object = _DequeBuffer<Element>.create(
      minimumCapacity: minimumCapacity,
      makingHeaderWith: {
        #if os(OpenBSD)
        let capacity = minimumCapacity
        #else
        let capacity = $0.capacity
        #endif
        return _DequeBufferHeader(
          capacity: capacity,
          count: count,
          startSlot: .zero)
      })
    let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
    guard count > 0 else { return result }
    result.update { target in
      let source = self.mutableSegments()
      let next = target.moveInitialize(at: .zero, from: source.first)
      if let second = source.second {
        target.moveInitialize(at: next, from: second)
      }
    }
    self.count = 0
    return result
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func withUnsafeSegment<R>(
    startingAt start: Int,
    maximumCount: Int?,
    _ body: (UnsafeBufferPointer<Element>) throws -> R
  ) rethrows -> (end: Int, result: R) {
    assert(start <= count)
    guard start < count else {
      return try (count, body(UnsafeBufferPointer(start: nil, count: 0)))
    }
    let endSlot = self.endSlot

    let segmentStart = self.slot(forOffset: start)
    let segmentEnd = segmentStart < endSlot ? endSlot : limSlot
    let count = Swift.min(maximumCount ?? Int.max, segmentEnd.position - segmentStart.position)
    let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count))
    return (start + count, result)
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func uncheckedReplaceInPlace<C: Collection>(
    inOffsets range: Range<Int>,
    with newElements: C
  ) where C.Element == Element {
    assertMutable()
    assert(range.upperBound <= count)
    assert(newElements.count == range.count)
    guard !range.isEmpty else { return }
    let target = mutableSegments(forOffsets: range)
    target.assign(from: newElements)
  }
}

// MARK: Appending
extension Deque._UnsafeHandle {
  @inlinable
  internal func uncheckedAppend(_ element: Element) {
    assertMutable()
    assert(count < capacity)
    ptr(at: endSlot).initialize(to: element)
    count += 1
  }

  @inlinable
  internal func uncheckedAppend(contentsOf source: UnsafeBufferPointer<Element>) {
    assertMutable()
    assert(count + source.count <= capacity)
    guard source.count > 0 else { return }
    let c = self.count
    count += source.count
    let gap = mutableSegments(forOffsets: c ..< count)
    gap.initialize(from: source)
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func uncheckedPrepend(_ element: Element) {
    assertMutable()
    assert(count < capacity)
    let slot = self.slot(before: startSlot)
    ptr(at: slot).initialize(to: element)
    startSlot = slot
    count += 1
  }

  @inlinable
  internal func uncheckedPrepend(contentsOf source: UnsafeBufferPointer<Element>) {
    assertMutable()
    assert(count + source.count <= capacity)
    guard source.count > 0 else { return }
    let oldStart = startSlot
    let newStart = self.slot(startSlot, offsetBy: -source.count)
    startSlot = newStart
    count += source.count

    let gap = mutableWrappedBuffer(between: newStart, and: oldStart)
    gap.initialize(from: source)
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func uncheckedInsert<C: Collection>(
    contentsOf newElements: __owned C,
    count newCount: Int,
    atOffset offset: Int
  ) where C.Element == Element {
    assertMutable()
    assert(offset <= count)
    assert(newElements.count == newCount)
    guard newCount > 0 else { return }
    let gap = openGap(ofSize: newCount, atOffset: offset)
    gap.initialize(from: newElements)
  }

  @inlinable
  internal func mutableWrappedBuffer(
    between start: Slot,
    and end: Slot
  ) -> _UnsafeMutableWrappedBuffer<Element> {
    assert(start.position <= capacity)
    assert(end.position <= capacity)
    if start < end {
      return .init(start: ptr(at: start), count: end.position - start.position)
    }
    return .init(
      first: ptr(at: start), count: capacity - start.position,
      second: ptr(at: .zero), count: end.position)
  }

  @inlinable
  internal func openGap(
    ofSize gapSize: Int,
    atOffset offset: Int
  ) -> _UnsafeMutableWrappedBuffer<Element> {
    assertMutable()
    assert(offset >= 0 && offset <= self.count)
    assert(self.count + gapSize <= capacity)
    assert(gapSize > 0)

    let headCount = offset
    let tailCount = count - offset
    if tailCount <= headCount {

      let originalEnd = self.slot(startSlot, offsetBy: count)
      let newEnd = self.slot(startSlot, offsetBy: count + gapSize)
      let gapStart = self.slot(forOffset: offset)
      let gapEnd = self.slot(gapStart, offsetBy: gapSize)

      let sourceIsContiguous = gapStart <= originalEnd.orIfZero(capacity)
      let targetIsContiguous = gapEnd <= newEnd.orIfZero(capacity)

      if sourceIsContiguous &#038;&#038; targetIsContiguous {
        move(from: gapStart, to: gapEnd, count: tailCount)
      } else if targetIsContiguous {
        assert(startSlot > originalEnd.orIfZero(capacity))
        move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
        move(from: gapStart, to: gapEnd, count: capacity - gapStart.position)
      } else if sourceIsContiguous {
        move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position)
        move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position)
      } else {
        move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
        move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
        move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position)
      }
      count += gapSize
      return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
    }

    let originalStart = self.startSlot
    let newStart = self.slot(originalStart, offsetBy: -gapSize)
    let gapEnd = self.slot(forOffset: offset)
    let gapStart = self.slot(gapEnd, offsetBy: -gapSize)

    let sourceIsContiguous = originalStart <= gapEnd.orIfZero(capacity)
    let targetIsContiguous = newStart <= gapStart.orIfZero(capacity)

    if sourceIsContiguous &#038;&#038; targetIsContiguous {
      move(from: originalStart, to: newStart, count: headCount)
    } else if targetIsContiguous {
      assert(originalStart >= newStart)
      move(from: originalStart, to: newStart, count: capacity - originalStart.position)
      move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position)
    } else if sourceIsContiguous {
      move(from: originalStart, to: newStart, count: capacity - newStart.position)
      move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
    } else {
      move(from: originalStart, to: newStart, count: capacity - originalStart.position)
      move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize)
      move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
    }
    startSlot = newStart
    count += gapSize
    return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
  }
}

extension Deque._UnsafeHandle {
  @inlinable
  internal func uncheckedRemoveFirst() -> Element {
    assertMutable()
    assert(count > 0)
    let result = ptr(at: startSlot).move()
    startSlot = slot(after: startSlot)
    count -= 1
    return result
  }

  @inlinable
  internal func uncheckedRemoveLast() -> Element {
    assertMutable()
    assert(count > 0)
    let slot = self.slot(forOffset: count - 1)
    let result = ptr(at: slot).move()
    count -= 1
    return result
  }

  @inlinable
  internal func uncheckedRemoveFirst(_ n: Int) {
    assertMutable()
    assert(count >= n)
    guard n > 0 else { return }
    let target = mutableSegments(forOffsets: 0 ..< n)
    target.deinitialize()
    startSlot = slot(startSlot, offsetBy: n)
    count -= n
  }

  @inlinable
  internal func uncheckedRemoveLast(_ n: Int) {
    assertMutable()
    assert(count >= n)
    guard n > 0 else { return }
    let target = mutableSegments(forOffsets: count - n ..< count)
    target.deinitialize()
    count -= n
  }

  @inlinable
  internal func uncheckedRemoveAll() {
    assertMutable()
    guard count > 0 else { return }
    let target = mutableSegments()
    target.deinitialize()
    count = 0
    startSlot = .zero
  }

  @inlinable
  internal func uncheckedRemove(offsets bounds: Range<Int>) {
    assertMutable()
    assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)

    mutableSegments(forOffsets: bounds).deinitialize()
    closeGap(offsets: bounds)
  }

  @inlinable
  internal func closeGap(offsets bounds: Range<Int>) {
    assertMutable()
    assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)
    let gapSize = bounds.count
    guard gapSize > 0 else { return }

    let gapStart = self.slot(forOffset: bounds.lowerBound)
    let gapEnd = self.slot(forOffset: bounds.upperBound)

    let headCount = bounds.lowerBound
    let tailCount = count - bounds.upperBound

    if headCount >= tailCount {
      let originalEnd = endSlot
      let newEnd = self.slot(forOffset: count - gapSize)

      let sourceIsContiguous = gapEnd < originalEnd.orIfZero(capacity)
      let targetIsContiguous = gapStart <= newEnd.orIfZero(capacity)
      if tailCount == 0 {
      } else if sourceIsContiguous &#038;&#038; targetIsContiguous {
        move(from: gapEnd, to: gapStart, count: tailCount)
      } else if sourceIsContiguous {
        let c = capacity - gapStart.position
        assert(tailCount > c)
        let next = move(from: gapEnd, to: gapStart, count: c)
        move(from: next.source, to: .zero, count: tailCount - c)
      } else if targetIsContiguous {
        let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
        move(from: .zero, to: next.target, count: originalEnd.position)
      } else {
        var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
        next = move(from: .zero, to: next.target, count: gapSize)
        move(from: next.source, to: .zero, count: newEnd.position)
      }
      count -= gapSize
    } else {
      let originalStart = startSlot
      let newStart = slot(startSlot, offsetBy: gapSize)

      let sourceIsContiguous = originalStart < gapStart.orIfZero(capacity)
      let targetIsContiguous = newStart <= gapEnd.orIfZero(capacity)

      if headCount == 0 {
      } else if sourceIsContiguous &#038;&#038; targetIsContiguous {
        move(from: originalStart, to: newStart, count: headCount)
      } else if sourceIsContiguous {
        move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position)
        move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
      } else if targetIsContiguous {
        move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position)
        move(from: startSlot, to: newStart, count: headCount - gapStart.position)
      } else {
        move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position)
        move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
        move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
      }
      startSlot = newStart
      count -= gapSize
    }
  }
}

@frozen
@usableFromInline
internal struct _UnsafeWrappedBuffer<Element> {
  @usableFromInline
  internal let first: UnsafeBufferPointer<Element>

  @usableFromInline
  internal let second: UnsafeBufferPointer<Element>?

  @inlinable
  @inline(__always)
  internal init(
    _ first: UnsafeBufferPointer<Element>,
    _ second: UnsafeBufferPointer<Element>? = nil
  ) {
    self.first = first
    self.second = second
    assert(first.count > 0 || second == nil)
  }

  @inlinable
  internal init(
    start: UnsafePointer<Element>,
    count: Int
  ) {
    self.init(UnsafeBufferPointer(start: start, count: count))
  }

  @inlinable
  internal init(
    first start1: UnsafePointer<Element>,
    count count1: Int,
    second start2: UnsafePointer<Element>,
    count count2: Int
  ) {
    self.init(UnsafeBufferPointer(start: start1, count: count1),
              UnsafeBufferPointer(start: start2, count: count2))
  }

  @inlinable
  internal var count: Int { first.count + (second?.count ?? 0) }
}

@frozen
@usableFromInline
internal struct _UnsafeMutableWrappedBuffer<Element> {
  @usableFromInline
  internal let first: UnsafeMutableBufferPointer<Element>

  @usableFromInline
  internal let second: UnsafeMutableBufferPointer<Element>?

  @inlinable
  @inline(__always)
  internal init(
    _ first: UnsafeMutableBufferPointer<Element>,
    _ second: UnsafeMutableBufferPointer<Element>? = nil
  ) {
    self.first = first
    self.second = second?.count == 0 ? nil : second
    assert(first.count > 0 || second == nil)
  }

  @inlinable
  @inline(__always)
  internal init(
    _ first: UnsafeMutableBufferPointer<Element>.SubSequence,
    _ second: UnsafeMutableBufferPointer<Element>? = nil
  ) {
    self.init(UnsafeMutableBufferPointer(rebasing: first), second)
  }

  @inlinable
  @inline(__always)
  internal init(
    _ first: UnsafeMutableBufferPointer<Element>,
    _ second: UnsafeMutableBufferPointer<Element>.SubSequence
  ) {
    self.init(first, UnsafeMutableBufferPointer(rebasing: second))
  }

  @inlinable
  @inline(__always)
  internal init(
    start: UnsafeMutablePointer<Element>,
    count: Int
  ) {
    self.init(UnsafeMutableBufferPointer(start: start, count: count))
  }

  @inlinable
  @inline(__always)
  internal init(
    first start1: UnsafeMutablePointer<Element>,
    count count1: Int,
    second start2: UnsafeMutablePointer<Element>,
    count count2: Int
  ) {
    self.init(UnsafeMutableBufferPointer(start: start1, count: count1),
              UnsafeMutableBufferPointer(start: start2, count: count2))
  }

  @inlinable
  @inline(__always)
  internal init(mutating buffer: _UnsafeWrappedBuffer<Element>) {
    self.init(.init(mutating: buffer.first),
              buffer.second.map { .init(mutating: $0) })
  }
}

extension _UnsafeMutableWrappedBuffer {
  @inlinable
  @inline(__always)
  internal var count: Int { first.count + (second?.count ?? 0) }

  @inlinable
  internal func prefix(_ n: Int) -> Self {
    assert(n >= 0)
    if n >= self.count {
      return self
    }
    if n <= first.count {
      return Self(first.prefix(n))
    }
    return Self(first, second!.prefix(n - first.count))
  }

  @inlinable
  internal func suffix(_ n: Int) -> Self {
    assert(n >= 0)
    if n >= self.count {
      return self
    }
    guard let second = second else {
      return Self(first.suffix(n))
    }
    if n <= second.count {
      return Self(second.suffix(n))
    }
    return Self(first.suffix(n - second.count), second)
  }
}

extension _UnsafeMutableWrappedBuffer {
  @inlinable
  internal func deinitialize() {
    first.deinitialize()
    second?.deinitialize()
  }

  @inlinable
  @discardableResult
  internal func initialize<I: IteratorProtocol>(
    fromPrefixOf iterator: inout I
  ) -> Int
  where I.Element == Element {
    var copied = 0
    var gap = first
    var wrapped = false
    while true {
      if copied == gap.count {
        guard !wrapped, let second = second, second.count > 0 else { break }
        gap = second
        copied = 0
        wrapped = true
      }
      guard let next = iterator.next() else { break }
      (gap.baseAddress! + copied).initialize(to: next)
      copied += 1
    }
    return wrapped ? first.count + copied : copied
  }

  @inlinable
  internal func initialize<S: Sequence>(
    fromSequencePrefix elements: __owned S
  ) -> (iterator: S.Iterator, count: Int)
  where S.Element == Element {
    guard second == nil || first.count >= elements.underestimatedCount else {
      var it = elements.makeIterator()
      let copied = initialize(fromPrefixOf: &it)
      return (it, copied)
    }
    var (it, copied) = elements._copyContents(initializing: first)
    if copied == first.count, let second = second {
      var i = 0
      while i < second.count {
        guard let next = it.next() else { break }
        (second.baseAddress! + i).initialize(to: next)
        i += 1
      }
      copied += i
    }
    return (it, copied)
  }

  @inlinable
  internal func initialize<C: Collection>(
    from elements: __owned C
  ) where C.Element == Element {
    assert(self.count == elements.count)
    if let second = second {
      let wrap = elements.index(elements.startIndex, offsetBy: first.count)
      first.initializeAll(fromContentsOf: elements[..<wrap])
      second.initializeAll(fromContentsOf: elements[wrap...])
    } else {
      first.initializeAll(fromContentsOf: elements)
    }
  }

  @inlinable
  internal func assign<C: Collection>(
    from elements: C
  ) where C.Element == Element {
    assert(elements.count == self.count)
    deinitialize()
    initialize(from: elements)
  }
}

extension UnsafeMutableBufferPointer {
  @discardableResult
  @inlinable
  public func deinitialize() -> UnsafeMutableRawBufferPointer {
    guard let start = baseAddress else { return .init(start: nil, count: 0) }
    start.deinitialize(count: count)
    return .init(start: UnsafeMutableRawPointer(start),
                 count: count * MemoryLayout<Element>.stride)
  }
}

extension UnsafeMutableBufferPointer {
  @inlinable
  public func initialize<C: Collection>(
    fromContentsOf source: C
  ) -> Index
  where C.Element == Element {
    let count: Int? = source._withContiguousStorageIfAvailable_SR14663 {
      guard let sourceAddress = $0.baseAddress, !$0.isEmpty else {
        return 0
      }
      precondition(
        $0.count <= self.count,
        "buffer cannot contain every element from source."
      )
      baseAddress?.initialize(from: sourceAddress, count: $0.count)
      return $0.count
    }
    if let count = count {
      return startIndex.advanced(by: count)
    }

    var (iterator, copied) = source._copyContents(initializing: self)
    precondition(
      iterator.next() == nil,
      "buffer cannot contain every element from source."
    )
    return startIndex.advanced(by: copied)
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func moveInitialize(fromContentsOf source: Self) -> Index {
    guard let sourceAddress = source.baseAddress, !source.isEmpty else {
      return startIndex
    }
    precondition(
      source.count <= self.count,
      "buffer cannot contain every element from source."
    )
    baseAddress?.moveInitialize(from: sourceAddress, count: source.count)
    return startIndex.advanced(by: source.count)
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func moveInitialize(fromContentsOf source: Slice<Self>) -> Index {
    return moveInitialize(fromContentsOf: Self(rebasing: source))
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func initializeElement(at index: Index, to value: Element) {
    assert(startIndex <= index &#038;&#038; index < endIndex)
    let p = baseAddress.unsafelyUnwrapped.advanced(by: index)
    p.initialize(to: value)
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func moveElement(from index: Index) -> Element {
    assert(startIndex <= index &#038;&#038; index < endIndex)
    return baseAddress.unsafelyUnwrapped.advanced(by: index).move()
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func deinitializeElement(at index: Index) {
    assert(startIndex <= index &#038;&#038; index < endIndex)
    let p = baseAddress.unsafelyUnwrapped.advanced(by: index)
    p.deinitialize(count: 1)
  }
}

extension Slice {
  @inlinable
  @_alwaysEmitIntoClient
  public func initialize<C: Collection>(
    fromContentsOf source: C
  ) -> Index where Base == UnsafeMutableBufferPointer<C.Element> {
    let buffer = Base(rebasing: self)
    let index = buffer.initialize(fromContentsOf: source)
    let distance = buffer.distance(from: buffer.startIndex, to: index)
    return startIndex.advanced(by: distance)
  }
  
  @inlinable
  @_alwaysEmitIntoClient
  public func moveInitialize<Element>(
    fromContentsOf source: UnsafeMutableBufferPointer<Element>
  ) -> Index where Base == UnsafeMutableBufferPointer<Element> {
    let buffer = Base(rebasing: self)
    let index = buffer.moveInitialize(fromContentsOf: source)
    let distance = buffer.distance(from: buffer.startIndex, to: index)
    return startIndex.advanced(by: distance)
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func moveInitialize<Element>(
    fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
  ) -> Index where Base == UnsafeMutableBufferPointer<Element> {
    let buffer = Base(rebasing: self)
    let index = buffer.moveInitialize(fromContentsOf: source)
    let distance = buffer.distance(from: buffer.startIndex, to: index)
    return startIndex.advanced(by: distance)
  }

  @discardableResult
  @inlinable
  @_alwaysEmitIntoClient
  public func deinitialize<Element>() -> UnsafeMutableRawBufferPointer
  where Base == UnsafeMutableBufferPointer<Element> {
    Base(rebasing: self).deinitialize()
  }

  @inlinable
  @_alwaysEmitIntoClient
  public func initializeElement<Element>(at index: Int, to value: Element)
  where Base == UnsafeMutableBufferPointer<Element> {
    assert(startIndex <= index &#038;&#038; index < endIndex)
    base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value)
  }
}

#if swift(<5.8)
extension UnsafeMutableBufferPointer {
  @_alwaysEmitIntoClient
  public func update(repeating repeatedValue: Element) {
    guard let dstBase = baseAddress else { return }
    dstBase.update(repeating: repeatedValue, count: count)
  }
}
#endif

#if swift(<5.8)
extension Slice {
  @_alwaysEmitIntoClient
  public func update<Element>(repeating repeatedValue: Element)
  where Base == UnsafeMutableBufferPointer<Element> {
    Base(rebasing: self).update(repeating: repeatedValue)
  }
}
#endif

extension UnsafeMutableBufferPointer {
  @inlinable
  public func initialize(fromContentsOf source: Self) -> Index {
    guard source.count > 0 else { return 0 }
    precondition(
      source.count <= self.count,
      "buffer cannot contain every element from source.")
    baseAddress.unsafelyUnwrapped.initialize(
      from: source.baseAddress.unsafelyUnwrapped,
      count: source.count)
    return source.count
  }

  @inlinable
  public func initialize(fromContentsOf source: Slice<Self>) -> Index {
    let sourceCount = source.count
    guard sourceCount > 0 else { return 0 }
    precondition(
      sourceCount <= self.count,
      "buffer cannot contain every element from source.")
    baseAddress.unsafelyUnwrapped.initialize(
      from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex,
      count: sourceCount)
    return sourceCount
  }
}

extension Slice {
  @inlinable @inline(__always)
  public func initialize<Element>(
    fromContentsOf source: UnsafeMutableBufferPointer<Element>
  ) -> Index
  where Base == UnsafeMutableBufferPointer<Element>
  {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    let i = target.initialize(fromContentsOf: source)
    return self.startIndex + i
  }

  @inlinable @inline(__always)
  public func initialize<Element>(
    fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
  ) -> Index
  where Base == UnsafeMutableBufferPointer<Element>
  {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    let i = target.initialize(fromContentsOf: source)
    return self.startIndex + i
  }
}

extension UnsafeMutableBufferPointer {
  @inlinable @inline(__always)
  public func initializeAll<C: Collection>(
    fromContentsOf source: C
  ) where C.Element == Element {
    let i = self.initialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }

  @inlinable @inline(__always)
  public func initializeAll(fromContentsOf source: Self) {
    let i = self.initialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }

  @inlinable @inline(__always)
  public func initializeAll(fromContentsOf source: Slice<Self>) {
    let i = self.initialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }

  @inlinable @inline(__always)
  public func moveInitializeAll(fromContentsOf source: Self) {
    let i = self.moveInitialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }

  @inlinable @inline(__always)
  public func moveInitializeAll(fromContentsOf source: Slice<Self>) {
    let i = self.moveInitialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }
}

extension Slice {
  @inlinable @inline(__always)
  public func initializeAll<C: Collection>(
    fromContentsOf source: C
  ) where Base == UnsafeMutableBufferPointer<C.Element> {
    let i = self.initialize(fromContentsOf: source)
    assert(i == self.endIndex)
  }

  @inlinable @inline(__always)
  public func initializeAll<Element>(
    fromContentsOf source: UnsafeMutableBufferPointer<Element>
  ) where Base == UnsafeMutableBufferPointer<Element> {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    target.initializeAll(fromContentsOf: source)
  }

  @inlinable @inline(__always)
  public func initializeAll<Element>(
    fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
  ) where Base == UnsafeMutableBufferPointer<Element> {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    target.initializeAll(fromContentsOf: source)
  }

  @inlinable @inline(__always)
  public func moveInitializeAll<Element>(
    fromContentsOf source: UnsafeMutableBufferPointer<Element>
  ) where Base == UnsafeMutableBufferPointer<Element> {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    target.moveInitializeAll(fromContentsOf: source)
  }

  @inlinable @inline(__always)
  public func moveInitializeAll<Element>(
    fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
  ) where Base == UnsafeMutableBufferPointer<Element> {
    let target = UnsafeMutableBufferPointer(rebasing: self)
    target.moveInitializeAll(fromContentsOf: source)
  }
}

#if swift(<5.8)
extension UnsafeMutablePointer {
  @_alwaysEmitIntoClient
  public func update(repeating repeatedValue: Pointee, count: Int) {
    assert(count >= 0, "UnsafeMutablePointer.update(repeating:count:) with negative count")
    for i in 0 ..< count {
      self[i] = repeatedValue
    }
  }
}
#endif

extension Array {
  @inlinable
  internal static func _isWCSIABroken() -> Bool {
    #if _runtime(_ObjC)
    guard _isBridgedVerbatimToObjectiveC(Element.self) else {
      return false
    }
    #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
    if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) {
      return false
    }
    return true
    #else
    return false
    #endif

    #else
    return false
    #endif
  }
}

extension Sequence {
  @inlinable @inline(__always)
  public func _withContiguousStorageIfAvailable_SR14663<R>(
    _ body: (UnsafeBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    if Self.self == Array<Element>.self && Array<Element>._isWCSIABroken() {
      return nil
    }

    return try self.withContiguousStorageIfAvailable(body)
  }
}

extension Deque: Hashable where Element: Hashable {
  @inlinable
  public func hash(into hasher: inout Hasher) {
    hasher.combine(count) // discriminator
    for element in self {
      hasher.combine(element)
    }
  }
}

extension Deque: Sequence {
  @frozen
  public struct Iterator: IteratorProtocol {
    @usableFromInline
    internal var _storage: Deque._Storage

    @usableFromInline
    internal var _nextSlot: _Slot

    @usableFromInline
    internal var _endSlot: _Slot

    @inlinable
    internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
      self._storage = _storage
      self._nextSlot = start
      self._endSlot = end
    }

    @inlinable
    internal init(_base: Deque) {
      self = _base._storage.read { handle in
        let start = handle.startSlot
        let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
        return Self(_storage: _base._storage, start: start, end: end)
      }
    }

    @inlinable
    internal init(_base: Deque, from index: Int) {
      self = _base._storage.read { handle in
        assert(index >= 0 && index <= handle.count)
        let start = handle.slot(forOffset: index)
        if index == handle.count {
          return Self(_storage: _base._storage, start: start, end: start)
        }
        var end = handle.endSlot
        if start >= end { end = handle.limSlot }
        return Self(_storage: _base._storage, start: start, end: end)
      }
    }

    @inlinable
    @inline(never)
    internal mutating func _swapSegment() -> Bool {
      assert(_nextSlot == _endSlot)
      return _storage.read { handle in
        let end = handle.endSlot
        if end == .zero || end == _nextSlot {
          return false
        }
        _endSlot = end
        _nextSlot = .zero
        return true
      }
    }

    @inlinable
    public mutating func next() -> Element? {
      if _nextSlot == _endSlot {
        guard _swapSegment() else { return nil }
      }
      assert(_nextSlot < _endSlot)
      let slot = _nextSlot
      _nextSlot = _nextSlot.advanced(by: 1)
      return _storage.read { handle in
        return handle.ptr(at: slot).pointee
      }
    }
  }

  @inlinable
  public func makeIterator() -> Iterator {
    Iterator(_base: self)
  }

  @inlinable
  public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
    ContiguousArray(unsafeUninitializedCapacity: _storage.count) { target, count in
      _storage.read { source in
        let segments = source.segments()
        let c = segments.first.count
        target[..<c].initializeAll(fromContentsOf: segments.first)
        count += segments.first.count
        if let second = segments.second {
          target[c ..< c + second.count].initializeAll(fromContentsOf: second)
          count += second.count
        }
        assert(count == source.count)
      }
    }
  }

  @inlinable
  public __consuming func _copyContents(
    initializing target: UnsafeMutableBufferPointer<Element>
  ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
    _storage.read { source in
      let segments = source.segments()
      let c1 = Swift.min(segments.first.count, target.count)
      target[..<c1].initializeAll(fromContentsOf: segments.first.prefix(c1))
      guard target.count > c1, let second = segments.second else {
        return (Iterator(_base: self, from: c1), c1)
      }
      let c2 = Swift.min(second.count, target.count - c1)
      target[c1 ..< c1 + c2].initializeAll(fromContentsOf: second.prefix(c2))
      return (Iterator(_base: self, from: c1 + c2), c1 + c2)
    }
  }

  @inlinable
  public func withContiguousStorageIfAvailable<R>(
    _ body: (UnsafeBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    return try _storage.read { handle in
      let endSlot = handle.startSlot.advanced(by: handle.count)
      guard endSlot.position <= handle.capacity else { return nil }
      return try body(handle.buffer(for: handle.startSlot ..< endSlot))
    }
  }
}

#if swift(>=5.5)
extension Deque.Iterator: Sendable where Element: Sendable {}
#endif

extension Deque: RandomAccessCollection {
  public typealias Index = Int
  public typealias SubSequence = Slice<Self>
  public typealias Indices = Range<Int>

  @inlinable
  @inline(__always)
  public var count: Int { _storage.count }

  @inlinable
  @inline(__always)
  public var startIndex: Int { 0 }

  @inlinable
  @inline(__always)
  public var endIndex: Int { count }

  @inlinable
  @inline(__always)
  public var indices: Range<Int> { 0 ..< count }

  @inlinable
  @inline(__always)
  public func index(after i: Int) -> Int {
    return i + 1
  }

  @inlinable
  @inline(__always)
  public func formIndex(after i: inout Int) {
    i += 1
  }

  @inlinable
  @inline(__always)
  public func index(before i: Int) -> Int {
    return i - 1
  }

  @inlinable
  @inline(__always)
  public func formIndex(before i: inout Int) {
    i -= 1
  }

  @inlinable
  @inline(__always)
  public func index(_ i: Int, offsetBy distance: Int) -> Int {
    return i + distance
  }

  @inlinable
  public func index(
    _ i: Int,
    offsetBy distance: Int,
    limitedBy limit: Int
  ) -> Int? {
    let l = limit - i
    if distance > 0 ? l >= 0 && l < distance : l <= 0 &#038;&#038; distance < l {
      return nil
    }
    return i + distance
  }

  @inlinable
  @inline(__always)
  public func distance(from start: Int, to end: Int) -> Int {
    return end - start
  }

  @inlinable
  public subscript(index: Int) -> Element {
    get {
      precondition(index >= 0 && index < count, "Index out of bounds")
      return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
    }
    set {
      precondition(index >= 0 && index < count, "Index out of bounds")
      _storage.ensureUnique()
      _storage.update { handle in
        let slot = handle.slot(forOffset: index)
        handle.ptr(at: slot).pointee = newValue
      }
    }
    @inline(__always)
    _modify {
      precondition(index >= 0 && index < count, "Index out of bounds")
      var (slot, value) = _prepareForModify(at: index)
      defer {
        _finalizeModify(slot, value)
      }
      yield &#038;value
    }
  }

  @inlinable
  internal mutating func _prepareForModify(at index: Int) -> (_Slot, Element) {
    _storage.ensureUnique()
    return _storage.update { handle in
      let slot = handle.slot(forOffset: index)
      return (slot, handle.ptr(at: slot).move())
    }
  }

  @inlinable
  internal mutating func _finalizeModify(_ slot: _Slot, _ value: Element) {
    _storage.update { handle in
      handle.ptr(at: slot).initialize(to: value)
    }
  }

  @inlinable
  public subscript(bounds: Range<Int>) -> Slice<Self> {
    get {
      precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
                   "Invalid bounds")
      return Slice(base: self, bounds: bounds)
    }
    set(source) {
      precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
                   "Invalid bounds")
      self.replaceSubrange(bounds, with: source)
    }
  }
}

extension Deque: MutableCollection {
  @inlinable
  public mutating func swapAt(_ i: Int, _ j: Int) {
    precondition(i >= 0 && i < count, "Index out of bounds")
    precondition(j >= 0 && j < count, "Index out of bounds")
    _storage.ensureUnique()
    _storage.update { handle in
      let slot1 = handle.slot(forOffset: i)
      let slot2 = handle.slot(forOffset: j)
      handle.mutableBuffer.swapAt(slot1.position, slot2.position)
    }
  }

  @inlinable
  public mutating func withContiguousMutableStorageIfAvailable<R>(
    _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    _storage.ensureUnique()
    return try _storage.update { handle in
      let endSlot = handle.startSlot.advanced(by: handle.count)
      guard endSlot.position <= handle.capacity else {
        return nil
      }
      let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
      var extract = original
      defer {
        precondition(extract.baseAddress == original.baseAddress &#038;&#038; extract.count == original.count,
                     "Closure must not replace the provided buffer")
      }
      return try body(&#038;extract)
    }
  }

  @inlinable
  public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
    _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    return try withContiguousMutableStorageIfAvailable(body)
  }
}

extension Deque: RangeReplaceableCollection {
  @inlinable
  public init() {
    _storage = _Storage()
  }

  @inlinable
  public mutating func reserveCapacity(_ minimumCapacity: Int) {
    _storage.ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: true)
  }

  @inlinable
  public mutating func replaceSubrange<C: Collection>(
    _ subrange: Range<Int>,
    with newElements: __owned C
  ) where C.Element == Element {
    precondition(subrange.lowerBound >= 0 && subrange.upperBound <= count, "Index range out of bounds")
    let removalCount = subrange.count
    let insertionCount = newElements.count
    let deltaCount = insertionCount - removalCount
    _storage.ensureUnique(minimumCapacity: count + deltaCount)

    let replacementCount = Swift.min(removalCount, insertionCount)
    let targetCut = subrange.lowerBound + replacementCount
    let sourceCut = newElements.index(newElements.startIndex, offsetBy: replacementCount)

    _storage.update { target in
      target.uncheckedReplaceInPlace(
        inOffsets: subrange.lowerBound ..< targetCut,
        with: newElements[..<sourceCut])
      if deltaCount < 0 {
        let r = targetCut ..< subrange.upperBound
        assert(replacementCount + r.count == removalCount)
        target.uncheckedRemove(offsets: r)
      } else if deltaCount > 0 {
        target.uncheckedInsert(
          contentsOf: newElements[sourceCut...],
          count: deltaCount,
          atOffset: targetCut)
      }
    }
  }

  @inlinable
  public init(repeating repeatedValue: Element, count: Int) {
    precondition(count >= 0)
    self.init(minimumCapacity: count)
    _storage.update { handle in
      assert(handle.startSlot == .zero)
      if count > 0 {
        handle.ptr(at: .zero).initialize(repeating: repeatedValue, count: count)
      }
      handle.count = count
    }
  }

  @inlinable
  public init<S: Sequence>(_ elements: S) where S.Element == Element {
    self.init()
    self.append(contentsOf: elements)
  }

  @inlinable
  public init<C: Collection>(_ elements: C) where C.Element == Element {
    let c = elements.count
    guard c > 0 else { _storage = _Storage(); return }
    self._storage = _Storage(minimumCapacity: c)
    _storage.update { handle in
      assert(handle.startSlot == .zero)
      let target = handle.mutableBuffer(for: .zero ..< _Slot(at: c))
      let done: Void? = elements._withContiguousStorageIfAvailable_SR14663 { source in
        target.initializeAll(fromContentsOf: source)
      }
      if done == nil {
        target.initializeAll(fromContentsOf: elements)
      }
      handle.count = c
    }
  }

  @inlinable
  public mutating func append(_ newElement: Element) {
    _storage.ensureUnique(minimumCapacity: count + 1)
    _storage.update {
      $0.uncheckedAppend(newElement)
    }
  }

  @inlinable
  public mutating func append<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
    let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
      _storage.ensureUnique(minimumCapacity: count + source.count)
      _storage.update { $0.uncheckedAppend(contentsOf: source) }
    }
    if done != nil {
      return
    }

    let underestimatedCount = newElements.underestimatedCount
    _storage.ensureUnique(minimumCapacity: count + underestimatedCount)
    var it: S.Iterator = _storage.update { target in
      let gaps = target.availableSegments()
      let (it, copied) = gaps.initialize(fromSequencePrefix: newElements)
      target.count += copied
      return it
    }
    while let next = it.next() {
      _storage.ensureUnique(minimumCapacity: count + 1)
      _storage.update { target in
        target.uncheckedAppend(next)
        let gaps = target.availableSegments()
        target.count += gaps.initialize(fromPrefixOf: &it)
      }
    }
  }

  @inlinable
  public mutating func append<C: Collection>(contentsOf newElements: C) where C.Element == Element {
    let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
      _storage.ensureUnique(minimumCapacity: count + source.count)
      _storage.update { $0.uncheckedAppend(contentsOf: source) }
    }
    guard done == nil else { return }

    let c = newElements.count
    guard c > 0 else { return }
    _storage.ensureUnique(minimumCapacity: count + c)
    _storage.update { target in
      let gaps = target.availableSegments().prefix(c)
      gaps.initialize(from: newElements)
      target.count += c
    }
  }

  @inlinable
  public mutating func insert(_ newElement: Element, at index: Int) {
    precondition(index >= 0 && index <= count,
                 "Can't insert element at invalid index")
    _storage.ensureUnique(minimumCapacity: count + 1)
    _storage.update { target in
      if index == 0 {
        target.uncheckedPrepend(newElement)
        return
      }
      if index == count {
        target.uncheckedAppend(newElement)
        return
      }
      let gap = target.openGap(ofSize: 1, atOffset: index)
      assert(gap.first.count == 1)
      gap.first.baseAddress!.initialize(to: newElement)
    }
  }

  @inlinable
  public mutating func insert<C: Collection>(
    contentsOf newElements: __owned C, at index: Int
  ) where C.Element == Element {
    precondition(index >= 0 && index <= count,
                 "Can't insert elements at an invalid index")
    let newCount = newElements.count
    _storage.ensureUnique(minimumCapacity: count + newCount)
    _storage.update { target in
      target.uncheckedInsert(contentsOf: newElements, count: newCount, atOffset: index)
    }
  }

  @inlinable
  @discardableResult
  public mutating func remove(at index: Int) -> Element {
    precondition(index >= 0 && index < self.count, "Index out of bounds")
    _storage.ensureUnique()
    return _storage.update { target in
      let result = self[index]
      target.uncheckedRemove(offsets: index ..< index + 1)
      return result
    }
  }

  @inlinable
  public mutating func removeSubrange(_ bounds: Range<Int>) {
    precondition(bounds.lowerBound >= 0 && bounds.upperBound <= self.count,
                 "Index range out of bounds")
    _storage.ensureUnique()
    _storage.update { $0.uncheckedRemove(offsets: bounds) }
  }

  @inlinable
  public mutating func _customRemoveLast() -> Element? {
    precondition(!isEmpty, "Cannot remove last element of an empty Deque")
    _storage.ensureUnique()
    return _storage.update { $0.uncheckedRemoveLast() }
  }

  @inlinable
  public mutating func _customRemoveLast(_ n: Int) -> Bool {
    precondition(n >= 0, "Can't remove a negative number of elements")
    precondition(n <= count, "Can't remove more elements than there are in the Collection")
    _storage.ensureUnique()
    _storage.update { $0.uncheckedRemoveLast(n) }
    return true
  }

  @inlinable
  @discardableResult
  public mutating func removeFirst() -> Element {
    precondition(!isEmpty, "Cannot remove first element of an empty Deque")
    _storage.ensureUnique()
    return _storage.update { $0.uncheckedRemoveFirst() }
  }

  @inlinable
  public mutating func removeFirst(_ n: Int) {
    precondition(n >= 0, "Can't remove a negative number of elements")
    precondition(n <= count, "Can't remove more elements than there are in the Collection")
    _storage.ensureUnique()
    return _storage.update { $0.uncheckedRemoveFirst(n) }
  }

  @inlinable
  public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
    if keepCapacity {
      _storage.ensureUnique()
      _storage.update { $0.uncheckedRemoveAll() }
    } else {
      self = Deque()
    }
  }
}

extension Deque: Equatable where Element: Equatable {
  @inlinable
  public static func ==(left: Self, right: Self) -> Bool {
    return left.elementsEqual(right)
  }
}

#if swift(>=5.5)
extension Deque: @unchecked Sendable where Element: Sendable {}
#endif

extension Deque: ExpressibleByArrayLiteral {
  @inlinable
  @inline(__always)
  public init(arrayLiteral elements: Element...) {
    self.init(elements)
  }
}

extension Deque: CustomStringConvertible {
  public var description: String {
    _arrayDescription(for: self)
  }
}

extension Deque: CustomDebugStringConvertible {
  public var debugDescription: String {
    _arrayDescription(
      for: self, debug: true, typeName: "Deque<\(Element.self)>")
  }
}

@inlinable
public func _arrayDescription<C: Collection>(
  for elements: C,
  debug: Bool = false,
  typeName: String? = nil
) -> String {
  var result = ""
  if let typeName = typeName {
    result += "\(typeName)("
  }
  result += "["
  var first = true
  for item in elements {
    if first {
      first = false
    } else {
      result += ", "
    }
    if debug {
      debugPrint(item, terminator: "", to: &result)
    } else {
      print(item, terminator: "", to: &result)
    }
  }
  result += "]"
  if typeName != nil { result += ")" }
  return result
}

extension Deque: CustomReflectable {
  public var customMirror: Mirror {
    Mirror(self, unlabeledChildren: self, displayStyle: .collection)
  }
}

extension Deque {
  @inlinable
  public init(
    unsafeUninitializedCapacity capacity: Int,
    initializingWith initializer:
      (inout UnsafeMutableBufferPointer<Element>, inout Int) throws -> Void
  ) rethrows {
    self._storage = .init(minimumCapacity: capacity)
    try _storage.update { handle in
      handle.startSlot = .zero
      var count = 0
      var buffer = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
      defer {
        precondition(count <= capacity,
          "Initialized count set to greater than specified capacity")
        let b = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
        precondition(buffer.baseAddress == b.baseAddress &#038;&#038; buffer.count == b.count,
          "Initializer relocated Deque storage")
        handle.count = count
      }
      try initializer(&#038;buffer, &#038;count)
    }
  }
}

extension Deque {
  @inlinable
  public mutating func popFirst() -> Element? {
    guard count > 0 else { return nil }
    _storage.ensureUnique()
    return _storage.update {
      $0.uncheckedRemoveFirst()
    }
  }

  @inlinable
  public mutating func prepend(_ newElement: Element) {
    _storage.ensureUnique(minimumCapacity: count + 1)
    return _storage.update {
      $0.uncheckedPrepend(newElement)
    }
  }

  @inlinable
  public mutating func prepend<C: Collection>(contentsOf newElements: C) where C.Element == Element {
    let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
      _storage.ensureUnique(minimumCapacity: count + source.count)
      _storage.update { $0.uncheckedPrepend(contentsOf: source) }
    }
    guard done == nil else { return }

    let c = newElements.count
    guard c > 0 else { return }
    _storage.ensureUnique(minimumCapacity: count + c)
    _storage.update { target in
      let gaps = target.availableSegments().suffix(c)
      gaps.initialize(from: newElements)
      target.count += c
      target.startSlot = target.slot(target.startSlot, offsetBy: -c)
    }
  }

  @inlinable
  public mutating func prepend<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
    let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
      _storage.ensureUnique(minimumCapacity: count + source.count)
      _storage.update { $0.uncheckedPrepend(contentsOf: source) }
    }
    guard done == nil else { return }

    let originalCount = self.count
    self.append(contentsOf: newElements)
    let newCount = self.count
    let c = newCount - originalCount
    _storage.update { target in
      target.startSlot = target.slot(forOffset: originalCount)
      target.count = target.capacity
      target.closeGap(offsets: c ..< c + (target.capacity - newCount))
      assert(target.count == newCount)
    }
  }
}</code></pre>



<p><a href="https://github.com/apple/swift-collections/blob/main/Sources/DequeModule/Deque.swift">https://github.com/apple/swift-collections/blob/main/Sources/DequeModule/Deque.swift</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/deque-template-in-swift/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Heap Template in Swift</title>
		<link>https://ingax.com/heap-template-in-swift/</link>
					<comments>https://ingax.com/heap-template-in-swift/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Tue, 25 Oct 2022 18:00:27 +0000</pubDate>
				<category><![CDATA[Swift]]></category>
		<category><![CDATA[Templates]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=7008</guid>

					<description><![CDATA[A partially-ordered tree of elements with performant insertion and removal operations. https://github.com/apple/swift-collections/blob/main/Documentation/Heap.md]]></description>
										<content:encoded><![CDATA[
<p>A partially-ordered tree of elements with performant insertion and removal operations.<a href="https://github.com/apple/swift-collections/blob/main/Documentation/Heap.md#declaration"></a></p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">@frozen
public struct Heap<Element: Comparable> {
  @usableFromInline
  internal var _storage: ContiguousArray<Element>

  @inlinable
  public init() {
    _storage = []
  }
}

#if swift(>=5.5)
extension Heap: Sendable where Element: Sendable {}
#endif

extension Heap {
  @inlinable @inline(__always)
  public var isEmpty: Bool {
    _storage.isEmpty
  }

  @inlinable @inline(__always)
  public var count: Int {
    _storage.count
  }

  @inlinable
  public var unordered: [Element] {
    Array(_storage)
  }

  @inlinable
  public mutating func insert(_ element: Element) {
    _storage.append(element)

    _update { handle in
      handle.bubbleUp(_Node(offset: handle.count - 1))
    }
    _checkInvariants()
  }

  @inlinable
  public func min() -> Element? {
    _storage.first
  }

  @inlinable
  public func max() -> Element? {
    _storage.withUnsafeBufferPointer { buffer in
      guard buffer.count > 2 else {
        return buffer.last
      }
      return Swift.max(buffer[1], buffer[2])
    }
  }

  @inlinable
  public mutating func popMin() -> Element? {
    guard _storage.count > 0 else { return nil }

    var removed = _storage.removeLast()

    if _storage.count > 0 {
      _update { handle in
        let minNode = _Node.root
        handle.swapAt(minNode, with: &removed)
        handle.trickleDownMin(minNode)
      }
    }

    _checkInvariants()
    return removed
  }

  @inlinable
  public mutating func popMax() -> Element? {
    guard _storage.count > 2 else { return _storage.popLast() }

    var removed = _storage.removeLast()

    _update { handle in
      if handle.count == 2 {
        if handle[.leftMax] > removed {
          handle.swapAt(.leftMax, with: &removed)
        }
      } else {
        let maxNode = handle.maxValue(.rightMax, .leftMax)
        handle.swapAt(maxNode, with: &removed)
        handle.trickleDownMax(maxNode)
      }
    }

    _checkInvariants()
    return removed
  }

  @inlinable
  public mutating func removeMin() -> Element {
    return popMin()!
  }

  @inlinable
  public mutating func removeMax() -> Element {
    return popMax()!
  }

  @inlinable
  @discardableResult
  public mutating func replaceMin(with replacement: Element) -> Element {
    precondition(!isEmpty, "No element to replace")

    var removed = replacement
    _update { handle in
      let minNode = _Node.root
      handle.swapAt(minNode, with: &removed)
      handle.trickleDownMin(minNode)
    }
    _checkInvariants()
    return removed
  }

  @inlinable
  @discardableResult
  public mutating func replaceMax(with replacement: Element) -> Element {
    precondition(!isEmpty, "No element to replace")

    var removed = replacement
    _update { handle in
      switch handle.count {
      case 1:
        handle.swapAt(.root, with: &removed)
      case 2:
        handle.swapAt(.leftMax, with: &removed)
        handle.bubbleUp(.leftMax)
      default:
        let maxNode = handle.maxValue(.leftMax, .rightMax)
        handle.swapAt(maxNode, with: &removed)
        handle.bubbleUp(maxNode)
        handle.trickleDownMax(maxNode)
      }
    }
    _checkInvariants()
    return removed
  }
}

extension Heap {
  
  @inlinable
  public init<S: Sequence>(_ elements: S) where S.Element == Element {
    _storage = ContiguousArray(elements)
    guard _storage.count > 1 else { return }

    _update { handle in
      handle.heapify()
    }
    _checkInvariants()
  }

  @inlinable
  public mutating func insert<S: Sequence>(
    contentsOf newElements: S
  ) where S.Element == Element {
    if count == 0 {
      self = Self(newElements)
      return
    }
    _storage.reserveCapacity(count + newElements.underestimatedCount)
    for element in newElements {
      insert(element)
    }
  }
}

@usableFromInline @frozen
internal struct _Node {
  @usableFromInline
  internal var offset: Int

  @usableFromInline
  internal var level: Int

  @inlinable
  internal init(offset: Int, level: Int) {
    assert(offset >= 0)
#if COLLECTIONS_INTERNAL_CHECKS
    assert(level == Self.level(forOffset: offset))
#endif
    self.offset = offset
    self.level = level
  }

  @inlinable
  internal init(offset: Int) {
    self.init(offset: offset, level: Self.level(forOffset: offset))
  }
}

extension _Node: Comparable {
  @inlinable @inline(__always)
  internal static func ==(left: Self, right: Self) -> Bool {
    left.offset == right.offset
  }

  @inlinable @inline(__always)
  internal static func <(left: Self, right: Self) -> Bool {
    left.offset < right.offset
  }
}

extension _Node: CustomStringConvertible {
  @usableFromInline
  internal var description: String {
    "(offset: \(offset), level: \(level))"
  }
}

extension _Node {
  @inlinable @inline(__always)
  internal static func level(forOffset offset: Int) -> Int {
    (offset &+ 1)._binaryLogarithm()
  }

  @inlinable @inline(__always)
  internal static func firstNode(onLevel level: Int) -> _Node {
    assert(level >= 0)
    return _Node(offset: (1 &<< level) &#038;- 1, level: level)
  }

  @inlinable @inline(__always)
  internal static func lastNode(onLevel level: Int) -> _Node {
    assert(level >= 0)
    return _Node(offset: (1 &<< (level &#038;+ 1)) &#038;- 2, level: level)
  }

  @inlinable @inline(__always)
  internal static func isMinLevel(_ level: Int) -> Bool {
    level & 0b1 == 0
  }
}

extension _Node {
  @inlinable @inline(__always)
  internal static var root: Self {
    Self.init(offset: 0, level: 0)
  }

  @inlinable @inline(__always)
  internal static var leftMax: Self {
    Self.init(offset: 1, level: 1)
  }

  @inlinable @inline(__always)
  internal static var rightMax: Self {
    Self.init(offset: 2, level: 1)
  }

  @inlinable @inline(__always)
  internal var isMinLevel: Bool {
    Self.isMinLevel(level)
  }

  @inlinable @inline(__always)
  internal var isRoot: Bool {
    offset == 0
  }
}

extension _Node {
  @inlinable @inline(__always)
  internal func parent() -> Self {
    assert(!isRoot)
    return Self(offset: (offset &- 1) / 2, level: level &- 1)
  }

  @inlinable @inline(__always)
  internal func grandParent() -> Self? {
    guard offset > 2 else { return nil }
    return Self(offset: (offset &- 3) / 4, level: level &- 2)
  }

  @inlinable @inline(__always)
  internal func leftChild() -> Self {
    Self(offset: offset &* 2 &+ 1, level: level &+ 1)
  }

  @inlinable @inline(__always)
  internal func rightChild() -> Self {
    Self(offset: offset &* 2 &+ 2, level: level &+ 1)
  }

  @inlinable @inline(__always)
  internal func firstGrandchild() -> Self {
    Self(offset: offset &* 4 &+ 3, level: level &+ 2)
  }

  @inlinable @inline(__always)
  internal func lastGrandchild() -> Self {
    Self(offset: offset &* 4 &+ 6, level: level &+ 2)
  }

  @inlinable
  internal static func allNodes(
    onLevel level: Int,
    limit: Int
  ) -> ClosedRange<Self>? {
    let first = Self.firstNode(onLevel: level)
    guard first.offset < limit else { return nil }
    var last = self.lastNode(onLevel: level)
    if last.offset >= limit {
      last.offset = limit &- 1
    }
    return ClosedRange(uncheckedBounds: (first, last))
  }
}

extension ClosedRange where Bound == _Node {
  @inlinable @inline(__always)
  internal func _forEach(_ body: (_Node) -> Void) {
    assert(
      isEmpty || _Node.level(forOffset: upperBound.offset) == lowerBound.level)
    var node = self.lowerBound
    while node.offset <= self.upperBound.offset {
      body(node)
      node.offset &#038;+= 1
    }
  }
}

extension Heap {
  #if COLLECTIONS_INTERNAL_CHECKS
  @inlinable
  @inline(never)
  internal func _checkInvariants() {
    guard count > 1 else { return }
    _checkInvariants(node: .root, min: nil, max: nil)
  }

  @inlinable
  internal func _checkInvariants(node: _Node, min: Element?, max: Element?) {
    let value = _storage[node.offset]
    if let min = min {
      precondition(value >= min,
                   "Element \(value) at \(node) is less than min \(min)")
    }
    if let max = max {
      precondition(value <= max,
                   "Element \(value) at \(node) is greater than max \(max)")
    }
    let left = node.leftChild()
    let right = node.rightChild()
    if node.isMinLevel {
      if left.offset < count {
        _checkInvariants(node: left, min: value, max: max)
      }
      if right.offset < count {
        _checkInvariants(node: right, min: value, max: max)
      }
    } else {
      if left.offset < count {
        _checkInvariants(node: left, min: min, max: value)
      }
      if right.offset < count {
        _checkInvariants(node: right, min: min, max: value)
      }
    }
  }
  #else
  @inlinable
  @inline(__always)
  public func _checkInvariants() {}
  #endif
}

extension Heap {
  @usableFromInline @frozen
  struct _UnsafeHandle {
    @usableFromInline
    var buffer: UnsafeMutableBufferPointer<Element>

    @inlinable @inline(__always)
    init(_ buffer: UnsafeMutableBufferPointer<Element>) {
      self.buffer = buffer
    }
  }

  @inlinable @inline(__always)
  mutating func _update<R>(_ body: (_UnsafeHandle) -> R) -> R {
    _storage.withUnsafeMutableBufferPointer { buffer in
      body(_UnsafeHandle(buffer))
    }
  }
}

extension Heap._UnsafeHandle {
  @inlinable @inline(__always)
  internal var count: Int {
    buffer.count
  }

  @inlinable
  subscript(node: _Node) -> Element {
    @inline(__always)
    get {
      buffer[node.offset]
    }
    @inline(__always)
    nonmutating _modify {
      yield &buffer[node.offset]
    }
  }

  @inlinable @inline(__always)
  internal func ptr(to node: _Node) -> UnsafeMutablePointer<Element> {
    assert(node.offset < count)
    return buffer.baseAddress! + node.offset
  }

  @inlinable @inline(__always)
  internal func extract(_ node: _Node) -> Element {
    ptr(to: node).move()
  }

  @inlinable @inline(__always)
  internal func initialize(_ node: _Node, to value: __owned Element) {
    ptr(to: node).initialize(to: value)
  }

  @inlinable @inline(__always)
  internal func swapAt(_ i: _Node, _ j: _Node) {
    buffer.swapAt(i.offset, j.offset)
  }

  @inlinable @inline(__always)
  internal func swapAt(_ i: _Node, with value: inout Element) {
    let p = buffer.baseAddress.unsafelyUnwrapped + i.offset
    swap(&p.pointee, &value)
  }


  @inlinable @inline(__always)
  internal func minValue(_ a: _Node, _ b: _Node) -> _Node {
    self[a] < self[b] ? a : b
  }

  @inlinable @inline(__always)
  internal func maxValue(_ a: _Node, _ b: _Node) -> _Node {
    self[a] < self[b] ? b : a
  }
}

extension Heap._UnsafeHandle {
  @inlinable
  internal func bubbleUp(_ node: _Node) {
    guard !node.isRoot else { return }

    let parent = node.parent()

    var node = node
    if (node.isMinLevel &#038;&#038; self[node] > self[parent])
        || (!node.isMinLevel && self[node] < self[parent]){
      swapAt(node, parent)
      node = parent
    }

    if node.isMinLevel {
      while let grandparent = node.grandParent(),
            self[node] < self[grandparent] {
        swapAt(node, grandparent)
        node = grandparent
      }
    } else {
      while let grandparent = node.grandParent(),
            self[node] > self[grandparent] {
        swapAt(node, grandparent)
        node = grandparent
      }
    }
  }
}

extension Heap._UnsafeHandle {
  @inlinable
  internal func trickleDownMin(_ node: _Node) {
    assert(node.isMinLevel)
    var node = node
    var value = extract(node)
    _trickleDownMin(node: &node, value: &value)
    initialize(node, to: value)
  }

  @inlinable @inline(__always)
  internal func _trickleDownMin(node: inout _Node, value: inout Element) {
    var gc0 = node.firstGrandchild()
    while gc0.offset &+ 3 < count {
      let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
      let minA = minValue(gc0, gc1)

      let gc2 = _Node(offset: gc0.offset &#038;+ 2, level: gc0.level)
      let gc3 = _Node(offset: gc0.offset &#038;+ 3, level: gc0.level)
      let minB = minValue(gc2, gc3)

      let min = minValue(minA, minB)
      guard self[min] < value else {
        return
      }

      initialize(node, to: extract(min))
      node = min
      gc0 = node.firstGrandchild()

      let parent = min.parent()
      if self[parent] < value {
        swapAt(parent, with: &#038;value)
      }
    }

    let c0 = node.leftChild()
    if c0.offset >= count {
      return
    }
    let min = _minDescendant(c0: c0, gc0: gc0)
    guard self[min] < value else {
      return
    }

    initialize(node, to: extract(min))
    node = min

    if min < gc0 { return }

    let parent = min.parent()
    if self[parent] < value {
      initialize(node, to: extract(parent))
      node = parent
    }
  }

  @inlinable
  internal func _minDescendant(c0: _Node, gc0: _Node) -> _Node {
    assert(c0.offset < count)
    assert(gc0.offset + 3 >= count)

    if gc0.offset < count {
      if gc0.offset &#038;+ 2 < count {
        let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
        let gc2 = _Node(offset: gc0.offset &#038;+ 2, level: gc0.level)
        return minValue(minValue(gc0, gc1), gc2)
      }

      let c1 = _Node(offset: c0.offset &#038;+ 1, level: c0.level)
      let m = minValue(c1, gc0)
      if gc0.offset &#038;+ 1 < count {
        let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
        return minValue(m, gc1)
      }

      return m
    }

    let c1 = _Node(offset: c0.offset &#038;+ 1, level: c0.level)
    if c1.offset < count {
      return minValue(c0, c1)
    }

    return c0
  }

  @inlinable
  internal func trickleDownMax(_ node: _Node) {
    assert(!node.isMinLevel)
    var node = node
    var value = extract(node)

    _trickleDownMax(node: &#038;node, value: &#038;value)
    initialize(node, to: value)
  }

  @inlinable @inline(__always)
  internal func _trickleDownMax(node: inout _Node, value: inout Element) {
    var gc0 = node.firstGrandchild()
    while gc0.offset &#038;+ 3 < count {
      let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
      let maxA = maxValue(gc0, gc1)

      let gc2 = _Node(offset: gc0.offset &#038;+ 2, level: gc0.level)
      let gc3 = _Node(offset: gc0.offset &#038;+ 3, level: gc0.level)
      let maxB = maxValue(gc2, gc3)

      let max = maxValue(maxA, maxB)
      guard value < self[max] else {
        return
      }

      initialize(node, to: extract(max))
      node = max
      gc0 = node.firstGrandchild()

      let parent = max.parent()
      if value < self[parent] {
        swapAt(parent, with: &#038;value)
      }
    }

    let c0 = node.leftChild()
    if c0.offset >= count {
      return
    }
    let max = _maxDescendant(c0: c0, gc0: gc0)
    guard value < self[max] else {
      return
    }

    initialize(node, to: extract(max))
    node = max

    if max < gc0 { return }

    let parent = max.parent()
    if value < self[parent] {
      initialize(node, to: extract(parent))
      node = parent
    }
  }

  @inlinable
  internal func _maxDescendant(c0: _Node, gc0: _Node) -> _Node {
    assert(c0.offset < count)
    assert(gc0.offset + 3 >= count)

    if gc0.offset < count {
      if gc0.offset &#038;+ 2 < count {
        let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
        let gc2 = _Node(offset: gc0.offset &#038;+ 2, level: gc0.level)
        return maxValue(maxValue(gc0, gc1), gc2)
      }

      let c1 = _Node(offset: c0.offset &#038;+ 1, level: c0.level)
      let m = maxValue(c1, gc0)
      if gc0.offset &#038;+ 1 < count {
        let gc1 = _Node(offset: gc0.offset &#038;+ 1, level: gc0.level)
        return maxValue(m, gc1)
      }

      return m
    }

    let c1 = _Node(offset: c0.offset &#038;+ 1, level: c0.level)
    if c1.offset < count {
      return maxValue(c0, c1)
    }

    return c0
  }
}

extension Heap._UnsafeHandle {
  @inlinable
  internal func heapify() {

    let limit = count / 2 // The first offset without a left child
    var level = _Node.level(forOffset: limit &#038;- 1)
    while level >= 0 {
      let nodes = _Node.allNodes(onLevel: level, limit: limit)
      _heapify(level, nodes)
      level &-= 1
    }
  }

  @inlinable
  internal func _heapify(_ level: Int, _ nodes: ClosedRange<_Node>?) {
    guard let nodes = nodes else { return }
    if _Node.isMinLevel(level) {
      nodes._forEach { node in
        trickleDownMin(node)
      }
    } else {
      nodes._forEach { node in
        trickleDownMax(node)
      }
    }
  }
}</code></pre>



<p><a href="https://github.com/apple/swift-collections/blob/main/Documentation/Heap.md">https://github.com/apple/swift-collections/blob/main/Documentation/Heap.md</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/heap-template-in-swift/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Important Equations for Software Engineering Interviews</title>
		<link>https://ingax.com/important-equations-for-software-engineering-interviews/</link>
					<comments>https://ingax.com/important-equations-for-software-engineering-interviews/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 20 Oct 2022 17:40:09 +0000</pubDate>
				<category><![CDATA[Interviews]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6995</guid>

					<description><![CDATA[Combinatorics Binomial Identify \(C(n, k) = C(n, n-k) \) Rule of Sums Choose one or another. Add Rule of Products Choose one and another. Multiply...]]></description>
										<content:encoded><![CDATA[
<h2>Combinatorics</h2>



<h3>Binomial Identify</h3>



\(C(n, k) = C(n, n-k) \)



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<p></p>



<h3>Rule of Sums</h3>



<p>Choose one or another. Add</p>



<h3>Rule of Products</h3>



<p>Choose one and another. Multiply</p>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<p></p>



<h2>General</h2>



<p>Finding the midpoint of an array. Avoiding overflow.</p>



\(midIndex = startIndex + (endIndex &#8211; startIndex) / 2 \)
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/important-equations-for-software-engineering-interviews/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Important iOS Topics</title>
		<link>https://ingax.com/important-ios-topics/</link>
					<comments>https://ingax.com/important-ios-topics/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Mon, 08 Aug 2022 16:41:38 +0000</pubDate>
				<category><![CDATA[iOS]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6989</guid>

					<description><![CDATA[ARC and Retain Cycles ARC or Automatic Reference Counting is system by which objects store a count of strong references that have been created in...]]></description>
										<content:encoded><![CDATA[
<h2>ARC and Retain Cycles</h2>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Swift - Retain Cycle, Automatic Reference Counting, Memory Leak - iOS Interview Questions" width="1080" height="608" src="https://www.youtube.com/embed/VcoZJ88d-vM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p></p>



<p>ARC or Automatic Reference Counting is system by which objects store a count of strong references that have been created in memory.</p>



<p>Once the number of references reaches 0, the object can be deinitialized.&nbsp;</p>



<p>A strong reference cycle or reference retain cycle is when two objects store strong references to each other. In this case, neither object can be removed from memory because the reference count will never reach 0.</p>



<p>Imagine a case where this type of object relationship was being created in a loop. The memory used by the app would grow indefinitely. This would be the cause of a memory leak.</p>



<p>It is important to be careful when creating object models that reference other objects. Closures can be particularly tricky because they store references to objects in a way that isn’t obvious to the developer.</p>



<p>A way to have an object relationship where two objects reference each other would be to make one of the references weak or unowned.&nbsp;</p>



<p>This can be accomplished by marking a property @unowned or @weak in a class, struct, or enum.</p>



<p>In a closure, a capture list is used to mark references as strong, weak, or unowned.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/important-ios-topics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Binary Tree Traversal</title>
		<link>https://ingax.com/binary-tree-traversal/</link>
					<comments>https://ingax.com/binary-tree-traversal/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Mon, 14 Feb 2022 22:45:05 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[BST Traversal]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[GIP]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6498</guid>

					<description><![CDATA[How to Recall Tree Traversal Orders Let L denote the left child. Let R denote the right child. Let P denote the parent and position....]]></description>
										<content:encoded><![CDATA[
<h3>How to Recall Tree Traversal Orders</h3>



<p>Let <strong>L</strong> denote the left child.</p>



<p>Let <strong>R</strong> denote the right child.</p>



<p>Let <strong>P</strong> denote the parent and position.</p>



<p>To easily remember tree traversal orders, pay attention to the position of <strong>P</strong> in the following strings.</p>



<p>When <strong>P</strong> is in the center, it is <strong>In Order</strong>. When it is first, it is <strong>Pre Order</strong>. And when it is last, it is <strong>Post Order</strong>.</p>



<p>L &#8211; <span style="text-decoration: underline;">P</span> &#8211; R |    <strong>In Order</strong></p>



<p><span style="text-decoration: underline;">P</span> &#8211; L &#8211; R |    <strong>Pre Order</strong></p>



<p>L &#8211; R &#8211; <span style="text-decoration: underline;">P</span> |    <strong>Post Order</strong></p>



<p>Note that L and R are always in the same order. The only element changing order is the parent.</p>



<h3>In Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">leftChild -> parent -> rightChild</code></pre>



<p>Integer values come out in order when traversing a Binary Search Tree.</p>



<h3>Pre Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">parent -> leftChild -> rightChild</code></pre>



<p>Traverse parent first (pre).</p>



<h3>Post Order</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">leftChild -> rightChild -> parent</code></pre>



<p>Traverse parent last (post).</p>



<h3>Code</h3>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">class BST {
    var value: Int?
    var left: BST?
    var right: BST?
    
    init(value: Int) {
        self.value = value
        left = nil
        right = nil
    }
}

// O(n) time | O(n) space, because we're storing all values in array
// Note: If were were just printing values, space will be O(h), where
// h is the height of the tree.

func inOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    inOrderTraversal(tree: node.left, array: &array)
    array.append(value)
    inOrderTraversal(tree: node.right, array: &array)
    
    return array
}

func preOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    array.append(value)
    preOrderTraversal(tree: node.left, array: &array)
    preOrderTraversal(tree: node.right, array: &array)
    
    return array
}

func postOrderTraversal(tree: BST?, array: inout [Int]) -> [Int] {
    guard let node = tree, let value = node.value else { return array }
    
    postOrderTraversal(tree: node.left, array: &array)
    postOrderTraversal(tree: node.right, array: &array)
    array.append(value)
    
    return array
}</code></pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/binary-tree-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Selection Sort</title>
		<link>https://ingax.com/selection-sort/</link>
					<comments>https://ingax.com/selection-sort/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 16:46:44 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Interviews]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6963</guid>

					<description><![CDATA[Two sections. One sorted. One unsorted. Select the smallest/largest value in the unsorted section and place it at the end of the sorted section. Continue...]]></description>
										<content:encoded><![CDATA[
<p>Two sections. One sorted. One unsorted. Select the smallest/largest value in the unsorted section and place it at the end of the sorted section. Continue until no values are left in the unsorted section.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func selectionSort(array: inout [Int]) -> [Int] {
    for i in 0 ..< array.count - 1 {
        var indexOfSmallestValue = i
        for j in i ..< array.count {
            indexOfSmallestValue = array[j] < array[indexOfSmallestValue] ? j : indexOfSmallestValue
        }
        array.swapAt(i, indexOfSmallestValue)
    }
    return array
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/selection-sort/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bubble Sort</title>
		<link>https://ingax.com/bubble-sort/</link>
					<comments>https://ingax.com/bubble-sort/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Thu, 25 Nov 2021 02:33:39 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Interviews]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6957</guid>

					<description><![CDATA[At each iteration, the largest element bubbles into correct order. The bubbling operation takes \(O(n)\) time and this operation is performed \(n\) times. Therefore, Bubble...]]></description>
										<content:encoded><![CDATA[
<p>At each iteration, the largest element bubbles into correct order.</p>



<p>The bubbling operation takes \(O(n)\) time and this operation is performed \(n\) times. Therefore, Bubble Sort runs in \(O(n^2)\) time.</p>



<p>The swaps are performed in place. If the given array is mutable, the algorithm can be performed in constant space.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func bubbleSort(_ array: inout [Int]) -> [Int] {
    for _ in 0..<array.count {
        for i in 0..<array.count - 1 {
            if array[i] > array[i+1] {
                array.swapAt(i, i+1)
            }
        }
    }
    return array
}</code></pre>



<p>Here&#8217;s a couple of real world optimizations. </p>



<p>Add a counter to avoid checking the part of the list that has already been sorted.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func bubbleSort(_ array: inout [Int]) -> [Int] {
    var counter = 0
    for _ in 0..<array.count {
        for i in 0..<array.count - 1 - counter {
            if array[i] > array[i+1] {
                array.swapAt(i, i+1)
            }
        }
        counter += 1
    }
    return array
}</code></pre>



<p>Add a bool to return the list if it is already sorted.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func bubbleSort(_ array: inout [Int]) -> [Int] {
    var counter = 0
    var inOrder = false
    while !inOrder {
        inOrder = true
        for i in 0..<array.count - 1 - counter {
            if array[i] > array[i+1] {
                array.swapAt(i, i+1)
                inOrder = false
            }
        }
        counter += 1
    }
    return array
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/bubble-sort/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fibonacci Sequence Algorithms Revisited</title>
		<link>https://ingax.com/fibonacci-sequence-algorithms-revisited/</link>
					<comments>https://ingax.com/fibonacci-sequence-algorithms-revisited/#respond</comments>
		
		<dc:creator><![CDATA[David Inga]]></dc:creator>
		<pubDate>Mon, 12 Jul 2021 16:38:41 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<guid isPermaLink="false">https://ingax.com/?p=6943</guid>

					<description><![CDATA[The algorithm for returning the \(nth \) number in the Fibonacci Sequence provides a simple demonstration on how different design choices effect the run time,...]]></description>
										<content:encoded><![CDATA[
<p>The algorithm for returning the \(nth \) number in the Fibonacci Sequence provides a simple demonstration on how different design choices effect the run time, storage, and readability of the code.</p>



<p>The sequence is as follows:</p>



<p><code>1, 1, 2, 3, 5, 8, 13, 21, 34, 55</code></p>



<p>The sequence follows the pattern of:</p>



\(fib(n) = fib(n &#8211; 1) + fib(n &#8211; 2)\) where \(n &gt; 0 \)



<p>I&#8217;ve written three algorithms. Each has pros and cons.</p>



<p>First I want to create a simple Error for a case where \(n\) is out of bounds. We will use this with all our algorithms.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">enum FibError: Error {
    case OutOfBounds
}</code></pre>



<p>Our first algorithm will use an iterative approach.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func fib(of n: Int) throws -> Int {
    guard n > 0 else { throw FibError.OutOfBounds }
    guard n > 2 else { return 1 }
    var result = 0, nMinusOne = 1, nMinusTwo = 1
    for _ in 3...n {
        result = (nMinusOne + nMinusTwo)
        nMinusTwo = nMinusOne
        nMinusOne = result
    }
    return result
}</code></pre>



<p>Our second algorithm will use a recursive approach. Notice how this algorithm is easier to read, but slightly more difficult to conceive.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">func fib(of n: Int) throws -> Int {
    guard n > 0 else { throw FibError.OutOfBounds }
    guard n > 2 else { return 1 }
    return try fib(of: n - 1) + fib(of: n - 2)
}</code></pre>



<p>Our third algorithm is a more optimal version of the recursive algorithm. Because of the nature of the recursive function calls, and more specifically the operation<code> try fib(of: n - 1) + fib(of: n - 2)</code>, we use a dictionary to avoid repetitive function calls.</p>



<pre class="wp-block-prismatic-blocks"><code class="language-swift">var sequenceValues = [Int: Int]()

func fib(of n: Int) throws -> Int {
    guard n > 0 else { throw FibError.OutOfBounds }
    guard n > 2 else { return 1 }
    var value: Int
    if sequenceValues[n] != nil  {
        value = sequenceValues[n]!
    } else {
        value = try fib(of: n - 1) + fib(of: n - 2)
        sequenceValues[n] = value
    }
    return value
}</code></pre>



<p>I hope this was helpful!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://ingax.com/fibonacci-sequence-algorithms-revisited/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Object Caching 0/181 objects using disk
Page Caching using disk: enhanced 
Database Caching using disk

Served from: ingax.com @ 2026-04-18 18:17:52 by W3 Total Cache
-->