Files

348 lines
12 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 - 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
//
//===----------------------------------------------------------------------===//
#if COLLECTIONS_FOUNDATION_TOOLCHAIN_MODULE
import _FoundationCollections
#elseif COLLECTIONS_SINGLE_MODULE
import Collections
#else
import InternalCollectionsUtilities
import DequeModule
#endif
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 6.4, *)
extension RigidDeque: Container where Element: ~Copyable {
@_alwaysEmitIntoClient
@_lifetime(borrow self)
public func makeBorrowingIterator(
from start: Index, to end: Index
) -> BorrowingIterator {
BorrowingIterator(_deque: self, from: start, to: end)
}
@_alwaysEmitIntoClient
public func currentIndex(of iterator: inout BorrowingIterator) -> Index {
// FIXME: This should validate that the iterator belongs to this deque.
return iterator._position
}
}
@available(SwiftStdlib 6.4, *)
extension RigidDeque: BidirectionalContainer where Element: ~Copyable {}
@available(SwiftStdlib 6.4, *)
extension RigidDeque: RandomAccessContainer where Element: ~Copyable {}
@available(SwiftStdlib 6.4, *)
extension RigidDeque: MutableContainer where Element: ~Copyable {}
@available(SwiftStdlib 6.4, *)
extension RigidDeque: DrainableContainer where Element: ~Copyable {}
@available(SwiftStdlib 6.4, *)
extension RigidDeque: RangeReplaceableContainer where Element: ~Copyable {}
@available(SwiftStdlib 6.4, *)
extension RigidDeque.SubrangeConsumer: ContainerDrain where Element: ~Copyable {
}
@available(SwiftStdlib 6.4, *)
extension RigidDeque where Element: ~Copyable {
/// Creates a new rigid deque of the specified capacity, populating it with
/// all items generated by a given producer.
///
/// If the capacity is exhausted before the producer reaches its end, then
/// this triggers a runtime error.
///
/// If the producer throws an error during this initializer, then all
/// previously produced items are discarded and the initializer rethrows the
/// error.
///
/// - Parameters:
/// - capacity: The desired storage capacity of the new array.
/// - producer: A producer that generates the items to append to the new
/// deque.
///
/// - Complexity: O(`capacity`)
@_alwaysEmitIntoClient
public init<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
capacity: Int,
from producer: consuming P
) throws(E)
where P.Element: ~Copyable
{
self.init(capacity: capacity)
try self.append(addingCount: capacity, from: &producer)
try producer._expectEnd("RigidDeque capacity overflow")
}
/// Creates a new rigid deque of the specified capacity, populating it with
/// all items generated by a given counted producer.
///
/// If the capacity is exhausted before the producer reaches its end, then
/// this triggers a runtime error.
///
/// If the producer throws an error during this initializer, then all
/// previously produced items are discarded and the initializer rethrows the
/// error.
///
/// - Parameters:
/// - capacity: The desired storage capacity of the new array, or nil
/// to allocate exactly as much room as needed to store the new items.
/// - producer: A producer that generates the items to append to the new
/// deque.
///
/// - Complexity: O(`capacity`)
@_alwaysEmitIntoClient
public init<
E: Error,
P: CountedProducer<Element, E> & ~Copyable & ~Escapable
>(
capacity: Int? = nil,
from producer: consuming P
) throws(E)
where P.Element: ~Copyable
{
let c = producer.count
let capacity = capacity ?? c
precondition(capacity >= c, "RigidDeque capacity overflow")
self.init(capacity: capacity)
try self.append(addingCount: c, from: &producer)
try producer._expectEnd("Invalid CountedProducer")
}
/// Prepends at most `newItemCount` items generated by a producer to the
/// front of this deque.
///
/// If the target deque does not have sufficient capacity to hold the
/// specified number of new items, then this triggers a runtime error.
///
/// This operation prepends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `newItemCount` items in
/// the producer; if the producer has more, then they remain available after
/// this method returns.
///
/// Note: Partial prepends create a gap in ring buffer storage that needs to
/// be closed by moving newly prepended items to their correct positions given
/// the adjusted count. This adds some overhead compared to adding exactly as
/// many items as promised.
///
/// - Parameters:
/// - newItemCount: The maximum number of items to prepend to the deque.
/// - producer: A producer that generates the items to prepend.
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`newItemCount`)
@_alwaysEmitIntoClient
@inline(__always)
@discardableResult
public mutating func prepend<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
addingCount newItemCount: Int,
from producer: inout P
) throws(E) -> Range<Int>
where P.Element: ~Copyable
{
try self.prepend(addingCount: newItemCount) { target throws(E) in
try producer.generate(into: &target)
}
}
/// Prepends all items generated by a counted producer to the front of this deque.
///
/// If the target deque does not have sufficient capacity to hold all items
/// generated by the producer, then this triggers a runtime error.
///
/// - Parameters:
/// - producer: A counted producer that generates the items to prepend.
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`newItemCount`)
@_alwaysEmitIntoClient
@inline(__always)
@discardableResult
public mutating func prepend<
E: Error,
P: CountedProducer<Element, E> & ~Copyable & ~Escapable
>(
from producer: consuming P
) throws(E) -> Range<Int>
where P.Element: ~Copyable
{
let range = try self.prepend(addingCount: producer.count, from: &producer)
try producer._expectEnd("Invalid CountedProducer")
return range
}
/// Moves the elements of a given container to the front of this deque, leaving
/// the source container empty.
///
/// The target deque must be able to accommodate all items in the source
/// container.
///
/// - Parameters:
/// - items: A container whose contents to move into this container.
/// - Returns: A valid index range addressing the newly inserted items.
@_alwaysEmitIntoClient
@discardableResult
public mutating func prepend<
C: DrainableContainer<Element> & ~Copyable & ~Escapable
>(
moving items: inout C
) -> Range<Index>
where C.Element: ~Copyable {
self.prepend(from: items.consumeAll())
}
@_alwaysEmitIntoClient
@discardableResult
public mutating func prepend<
C: DrainableContainer<Element> & ~Copyable & ~Escapable
>(
moving sourceSubrange: some RangeExpression2<C.Index>,
from source: inout C
) -> Range<Index>
where C.Element: ~Copyable {
let sourceSubrange = sourceSubrange.relative(to: source)
let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound)
var producer = source.consumeSubrange(sourceSubrange)
let range = self.prepend(addingCount: c, from: &producer)
producer._expectEnd("Invalid Container")
return range
}
}
@available(SwiftStdlib 6.4, *)
extension RigidDeque /*where Element: Copyable*/ {
/// Creates a new deque with the specified capacity, holding a copy
/// of the contents of the given container.
///
/// - Parameters:
/// - capacity: The storage capacity of the new deque, or nil to allocate
/// just enough capacity to store the contents of the source container.
/// - span: The containers whose contents to copy into the new deque.
/// The container must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init<
C: Container<Element> & ~Copyable & ~Escapable
>(
capacity: Int? = nil,
copying items: borrowing C
) {
self.init(capacity: capacity ?? items.count)
self.append(copying: items)
}
/// Creates a new deque with the specified capacity, holding a copy
/// of the contents of the given container.
///
/// - Parameters:
/// - capacity: The storage capacity of the new deque, or nil to allocate
/// just enough capacity to store the contents of the source container.
/// - span: The containers whose contents to copy into the new deque.
/// The container must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init<
C: Container<Element> & Sequence<Element>
>(
capacity: Int? = nil,
copying items: __shared C
) {
self.init(capacity: capacity ?? items.count)
self.append(copying: items)
}
/// Creates a new deque with the specified capacity, holding a copy
/// of the contents of the given container.
///
/// - Parameters:
/// - capacity: The storage capacity of the new deque, or nil to allocate
/// just enough capacity to store the contents of the source container.
/// - span: The containers whose contents to copy into the new deque.
/// The container must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init<
C: Container<Element> & Collection<Element>
>(
capacity: Int? = nil,
copying items: __shared C
) {
self.init(capacity: capacity ?? items.count)
self.append(copying: items)
}
/// Copies the elements of a container and prepends them to the front
/// of this deque.
///
/// If the deque does not have sufficient capacity to hold all items in the
/// container, then this triggers a runtime error.
///
/// - Parameters:
/// - items: The new elements to copy into the deque.
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func prepend<C: Container<Element> & ~Copyable & ~Escapable>(
copying items: borrowing C
) -> Range<Index> {
self._prepend(copying: items, exactCount: items.count)
}
/// Copies the elements of a container to the front of this deque.
///
/// If the deque does not have sufficient capacity to hold all items in the
/// sequence, then this triggers a runtime error.
///
/// - Parameters:
/// - items: The new elements to copy into the deque.
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*m*), where *m* is the length of `items`.
@_alwaysEmitIntoClient
@discardableResult
public mutating func prepend<C: Container<Element> & Sequence<Element>>(
copying items: borrowing C
) -> Range<Index> {
self._prepend(copying: items, exactCount: items.count)
}
/// Copies the elements of a container to the front of this deque.
///
/// If the deque does not have sufficient capacity to hold all items in the
/// sequence, then this triggers a runtime error.
///
/// - Parameters:
/// - items: The new elements to copy into the deque.
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*m*), where *m* is the length of `items`.
@_alwaysEmitIntoClient
@discardableResult
public mutating func prepend<C: Container<Element> & Collection<Element>>(
copying items: borrowing C
) -> Range<Index> {
self._prepend(copying: items, exactCount: items.count)
}
}
#endif