InterceptorContextList.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. internal struct InterceptorContextList<Element> {
  23. /// The first element, stored at `middle.startIndex - 1`.
  24. internal var first: Element
  25. /// The last element, stored at the `middle.endIndex`.
  26. internal var last: Element
  27. /// The other elements.
  28. private var middle: [Element]
  29. /// The index of `first`
  30. private let firstIndex: Int
  31. /// The index of `last`.
  32. private let lastIndex: Int
  33. internal subscript(checked index: Int) -> Element? {
  34. switch index {
  35. case self.firstIndex:
  36. return self.first
  37. case self.lastIndex:
  38. return self.last
  39. default:
  40. return self.middle[checked: index]
  41. }
  42. }
  43. internal init(first: Element, middle: [Element], last: Element) {
  44. self.first = first
  45. self.middle = middle
  46. self.last = last
  47. self.firstIndex = middle.startIndex - 1
  48. self.lastIndex = middle.endIndex
  49. }
  50. }