InterceptorContextList.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2020, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /// A non-empty list which is guaranteed to have a first and last element.
  17. ///
  18. /// This is required since we want to directly store the first and last elements: in some cases
  19. /// `Array.first` and `Array.last` will allocate: unfortunately this currently happens to be the
  20. /// case for the interceptor pipelines. Storing the `first` and `last` directly allows us to avoid
  21. /// this. See also: https://bugs.swift.org/browse/SR-11262.
  22. @usableFromInline
  23. internal struct InterceptorContextList<Element> {
  24. /// The first element, stored at `middle.startIndex - 1`.
  25. @usableFromInline
  26. internal var first: Element
  27. /// The last element, stored at the `middle.endIndex`.
  28. @usableFromInline
  29. internal var last: Element
  30. /// The other elements.
  31. @usableFromInline
  32. internal var _middle: [Element]
  33. /// The index of `first`
  34. @usableFromInline
  35. internal let firstIndex: Int
  36. /// The index of `last`.
  37. @usableFromInline
  38. internal let lastIndex: Int
  39. @usableFromInline
  40. internal subscript(checked index: Int) -> Element? {
  41. switch index {
  42. case self.firstIndex:
  43. return self.first
  44. case self.lastIndex:
  45. return self.last
  46. default:
  47. return self._middle[checked: index]
  48. }
  49. }
  50. @inlinable
  51. internal init(first: Element, middle: [Element], last: Element) {
  52. self.first = first
  53. self._middle = middle
  54. self.last = last
  55. self.firstIndex = middle.startIndex - 1
  56. self.lastIndex = middle.endIndex
  57. }
  58. }