<commit_before>//===--- ArrayBridge.swift - Array<T> <=> NSArray bridging ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SwiftShims

/// Class used whose sole instance is used as storage for empty
/// arrays.  The instance is defined in the runtime and statically
/// initialized.  See stdlib/runtime/GlobalObjects.cpp for details.
internal final class _EmptyArrayStorage
  : _ContiguousArrayStorageBase {

  init(_doNotCallMe: ()) {
    _sanityCheckFailure("creating instance of _EmptyArrayStorage")
  }
  
  var countAndCapacity: _ArrayBody

  override func _withVerbatimBridgedUnsafeBuffer<R>(
    body: (UnsafeBufferPointer<AnyObject>)->R
  ) -> R? {
    return body(UnsafeBufferPointer(start: .null(), count: 0))
  }

  override func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
    return 0
  }

  override func _getNonVerbatimBridgedHeapBuffer(
    dummy: Void
  ) -> _HeapBuffer<Int, AnyObject> {
    return _HeapBuffer<Int, AnyObject>(
      _HeapBufferStorage<Int, AnyObject>.self, 0, 0)
  }

  override func canStoreElementsOfDynamicType(_: Any.Type) -> Bool {
    return false
  }

  /// A type that every element in the array is.
  override var staticElementType: Any.Type {
    return Void.self
  }
}

/// The empty array prototype.  We use the same object for all empty
/// [Native]Array<T>s.
internal var _emptyArrayStorage : _EmptyArrayStorage {
  return Builtin.bridgeFromRawPointer(
    Builtin.addressof(&_swiftEmptyArrayStorage))
}

// FIXME: This whole class is a workaround for
// <rdar://problem/18560464> Can't override generic method in generic
// subclass.  If it weren't for that bug, we'd override
// _withVerbatimBridgedUnsafeBuffer directly in
// _ContiguousArrayStorage<T>.
class _ContiguousArrayStorage1 : _ContiguousArrayStorageBase {
  /// If the `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements and return the result.
  /// Otherwise, return `nil`.
  final override func _withVerbatimBridgedUnsafeBuffer<R>(
    body: (UnsafeBufferPointer<AnyObject>)->R
  ) -> R? {
    var result: R? = nil
    self._withVerbatimBridgedUnsafeBufferImpl {
      result = body($0)
    }
    return result
  }

  /// If `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements.
  internal func _withVerbatimBridgedUnsafeBufferImpl(
    body: (UnsafeBufferPointer<AnyObject>)->Void
  ) {
    _sanityCheckFailure(
      "Must override _withVerbatimBridgedUnsafeBufferImpl in derived classes")
  }
}

// The class that implements the storage for a ContiguousArray<T>
final class _ContiguousArrayStorage<T> : _ContiguousArrayStorage1 {
  typealias Buffer = _ContiguousArrayBuffer<T>

  deinit {
    let b = Buffer(self)
    b.baseAddress.destroy(b.count)
    b._base._value.destroy()
  }

  final func __getInstanceSizeAndAlignMask() -> (Int,Int) {
    return Buffer(self)._base._allocatedSizeAndAlignMask()
  }

  /// If `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements.
  internal final override func _withVerbatimBridgedUnsafeBufferImpl(
    body: (UnsafeBufferPointer<AnyObject>)->Void
  ) {
    if _isBridgedVerbatimToObjectiveC(T.self) {
      let nativeBuffer = Buffer(self)
      body(
        UnsafeBufferPointer(
          start: UnsafePointer(nativeBuffer.baseAddress),
          count: nativeBuffer.count))
      _fixLifetime(self)
    }
  }

  /// Returns the number of elements in the array.
  ///
  /// Precondition: `T` is bridged non-verbatim.
  override internal func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
    _sanityCheck(
      !_isBridgedVerbatimToObjectiveC(T.self),
      "Verbatim bridging should be handled separately")
    return Buffer(self).count
  }

  /// Bridge array elements and return a new buffer that owns them.
  ///
  /// Precondition: `T` is bridged non-verbatim.
  override internal func _getNonVerbatimBridgedHeapBuffer(dummy: Void) ->
    _HeapBuffer<Int, AnyObject> {
    _sanityCheck(
      !_isBridgedVerbatimToObjectiveC(T.self),
      "Verbatim bridging should be handled separately")
    let nativeBuffer = Buffer(self)
    let count = nativeBuffer.count
    let result = _HeapBuffer<Int, AnyObject>(
      _HeapBufferStorage<Int, AnyObject>.self, count, count)
    let resultPtr = result.baseAddress
    for i in 0..<count {
      (resultPtr + i).initialize(
        _bridgeToObjectiveCUnconditional(nativeBuffer[i]))
    }
    return result
  }

  /// Return true if the `proposedElementType` is `T` or a subclass of
  /// `T`.  We can't store anything else without violating type
  /// safety; for example, the destructor has static knowledge that
  /// all of the elements can be destroyed as `T`
  override func canStoreElementsOfDynamicType(
    proposedElementType: Any.Type
  ) -> Bool {
    return proposedElementType is T.Type
  }

  /// A type that every element in the array is.
  override var staticElementType: Any.Type {
    return T.self
  }
}

public struct _ContiguousArrayBuffer<T> : _ArrayBufferType {

  /// Make a buffer with uninitialized elements.  After using this
  /// method, you must either initialize the count elements at the
  /// result's .baseAddress or set the result's .count to zero.
  public init(count: Int, minimumCapacity: Int)
  {
    let realMinimumCapacity = max(count, minimumCapacity)
    if realMinimumCapacity == 0 {
      self = _ContiguousArrayBuffer<T>()
    }
    else {
      _base = _HeapBuffer(
        _ContiguousArrayStorage<T>.self,
        _ArrayBody(),
        realMinimumCapacity)

      var bridged = false
      if _canBeClass(T.self) != 0 {
        bridged = _isBridgedVerbatimToObjectiveC(T.self)
      }

      _base.value = _ArrayBody(
        count: count, capacity: _base._capacity(),
        elementTypeIsBridgedVerbatim: bridged)
    }
  }

  init(_ storage: _ContiguousArrayStorageBase?) {
    _base = unsafeBitCast(storage, _HeapBuffer<_ArrayBody, T>.self)
  }

  public var hasStorage: Bool {
    return _base.hasStorage
  }

  /// If the elements are stored contiguously, a pointer to the first
  /// element. Otherwise, nil.
  public var baseAddress: UnsafeMutablePointer<T> {
    return _base.hasStorage ? _base.baseAddress : nil
  }

  /// A pointer to the first element, assuming that the elements are stored
  /// contiguously.
  var _unsafeElementStorage: UnsafeMutablePointer<T> {
    return _base.baseAddress
  }

  /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
  /// underlying contiguous storage.
  public func withUnsafeBufferPointer<R>(
    body: (UnsafeBufferPointer<Element>)->R
  ) -> R {
    let ret = body(UnsafeBufferPointer(start: self.baseAddress, count: count))<commit_msg>[stdlib] ContiguousArrayBuffer: tiny logic cleanup<commit_after>//===--- ArrayBridge.swift - Array<T> <=> NSArray bridging ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SwiftShims

/// Class used whose sole instance is used as storage for empty
/// arrays.  The instance is defined in the runtime and statically
/// initialized.  See stdlib/runtime/GlobalObjects.cpp for details.
internal final class _EmptyArrayStorage
  : _ContiguousArrayStorageBase {

  init(_doNotCallMe: ()) {
    _sanityCheckFailure("creating instance of _EmptyArrayStorage")
  }
  
  var countAndCapacity: _ArrayBody

  override func _withVerbatimBridgedUnsafeBuffer<R>(
    body: (UnsafeBufferPointer<AnyObject>)->R
  ) -> R? {
    return body(UnsafeBufferPointer(start: .null(), count: 0))
  }

  override func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
    return 0
  }

  override func _getNonVerbatimBridgedHeapBuffer(
    dummy: Void
  ) -> _HeapBuffer<Int, AnyObject> {
    return _HeapBuffer<Int, AnyObject>(
      _HeapBufferStorage<Int, AnyObject>.self, 0, 0)
  }

  override func canStoreElementsOfDynamicType(_: Any.Type) -> Bool {
    return false
  }

  /// A type that every element in the array is.
  override var staticElementType: Any.Type {
    return Void.self
  }
}

/// The empty array prototype.  We use the same object for all empty
/// [Native]Array<T>s.
internal var _emptyArrayStorage : _EmptyArrayStorage {
  return Builtin.bridgeFromRawPointer(
    Builtin.addressof(&_swiftEmptyArrayStorage))
}

// FIXME: This whole class is a workaround for
// <rdar://problem/18560464> Can't override generic method in generic
// subclass.  If it weren't for that bug, we'd override
// _withVerbatimBridgedUnsafeBuffer directly in
// _ContiguousArrayStorage<T>.
class _ContiguousArrayStorage1 : _ContiguousArrayStorageBase {
  /// If the `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements and return the result.
  /// Otherwise, return `nil`.
  final override func _withVerbatimBridgedUnsafeBuffer<R>(
    body: (UnsafeBufferPointer<AnyObject>)->R
  ) -> R? {
    var result: R? = nil
    self._withVerbatimBridgedUnsafeBufferImpl {
      result = body($0)
    }
    return result
  }

  /// If `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements.
  internal func _withVerbatimBridgedUnsafeBufferImpl(
    body: (UnsafeBufferPointer<AnyObject>)->Void
  ) {
    _sanityCheckFailure(
      "Must override _withVerbatimBridgedUnsafeBufferImpl in derived classes")
  }
}

// The class that implements the storage for a ContiguousArray<T>
final class _ContiguousArrayStorage<T> : _ContiguousArrayStorage1 {
  typealias Buffer = _ContiguousArrayBuffer<T>

  deinit {
    let b = Buffer(self)
    b.baseAddress.destroy(b.count)
    b._base._value.destroy()
  }

  final func __getInstanceSizeAndAlignMask() -> (Int,Int) {
    return Buffer(self)._base._allocatedSizeAndAlignMask()
  }

  /// If `T` is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements.
  internal final override func _withVerbatimBridgedUnsafeBufferImpl(
    body: (UnsafeBufferPointer<AnyObject>)->Void
  ) {
    if _isBridgedVerbatimToObjectiveC(T.self) {
      let nativeBuffer = Buffer(self)
      body(
        UnsafeBufferPointer(
          start: UnsafePointer(nativeBuffer.baseAddress),
          count: nativeBuffer.count))
      _fixLifetime(self)
    }
  }

  /// Returns the number of elements in the array.
  ///
  /// Precondition: `T` is bridged non-verbatim.
  override internal func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
    _sanityCheck(
      !_isBridgedVerbatimToObjectiveC(T.self),
      "Verbatim bridging should be handled separately")
    return Buffer(self).count
  }

  /// Bridge array elements and return a new buffer that owns them.
  ///
  /// Precondition: `T` is bridged non-verbatim.
  override internal func _getNonVerbatimBridgedHeapBuffer(dummy: Void) ->
    _HeapBuffer<Int, AnyObject> {
    _sanityCheck(
      !_isBridgedVerbatimToObjectiveC(T.self),
      "Verbatim bridging should be handled separately")
    let nativeBuffer = Buffer(self)
    let count = nativeBuffer.count
    let result = _HeapBuffer<Int, AnyObject>(
      _HeapBufferStorage<Int, AnyObject>.self, count, count)
    let resultPtr = result.baseAddress
    for i in 0..<count {
      (resultPtr + i).initialize(
        _bridgeToObjectiveCUnconditional(nativeBuffer[i]))
    }
    return result
  }

  /// Return true if the `proposedElementType` is `T` or a subclass of
  /// `T`.  We can't store anything else without violating type
  /// safety; for example, the destructor has static knowledge that
  /// all of the elements can be destroyed as `T`
  override func canStoreElementsOfDynamicType(
    proposedElementType: Any.Type
  ) -> Bool {
    return proposedElementType is T.Type
  }

  /// A type that every element in the array is.
  override var staticElementType: Any.Type {
    return T.self
  }
}

public struct _ContiguousArrayBuffer<T> : _ArrayBufferType {

  /// Make a buffer with uninitialized elements.  After using this
  /// method, you must either initialize the count elements at the
  /// result's .baseAddress or set the result's .count to zero.
  public init(count: Int, minimumCapacity: Int)
  {
    let realMinimumCapacity = max(count, minimumCapacity)
    if realMinimumCapacity == 0 {
      self = _ContiguousArrayBuffer<T>()
    }
    else {
      _base = _HeapBuffer(
        _ContiguousArrayStorage<T>.self,
        _ArrayBody(),
        realMinimumCapacity)

      let verbatim = _isBridgedVerbatimToObjectiveC(T.self)
      
      _base.value = _ArrayBody(
        count: count, capacity: _base._capacity(),
        elementTypeIsBridgedVerbatim: verbatim)
    }
  }

  init(_ storage: _ContiguousArrayStorageBase?) {
    _base = unsafeBitCast(storage, _HeapBuffer<_ArrayBody, T>.self)
  }

  public var hasStorage: Bool {
    return _base.hasStorage
  }

  /// If the elements are stored contiguously, a pointer to the first
  /// element. Otherwise, nil.
  public var baseAddress: UnsafeMutablePointer<T> {
    return _base.hasStorage ? _base.baseAddress : nil
  }

  /// A pointer to the first element, assuming that the elements are stored
  /// contiguously.
  var _unsafeElementStorage: UnsafeMutablePointer<T> {
    return _base.baseAddress
  }

  /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
  /// underlying contiguous storage.
  public func withUnsafeBufferPointer<R>(
    body: (UnsafeBufferPointer<Element>)->R
  ) -> R {
    let ret = body(UnsafeBufferPointer(start: self.baseAddress, count: count))
{'fraction_non_alphanumeric': 0.10970017636684304, 'fraction_numerical': 0.0038800705467372134, 'mean_word_length': 3.2228179922549898, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 89, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2751896', 'n_tokens_mistral': 4394, 'n_tokens_neox': 4180, 'n_words': 1222}