func forEachLineLength()

in Sources/SwiftSyntax/SourceLocation.swift [376:412]


  func forEachLineLength(
    prefix: SourceLength = .zero, body: (SourceLength) -> ()
  ) -> SourceLength {
    let utf8 = self.utf8
    let startIndex = utf8.startIndex
    let endIndex = utf8.endIndex
    var curIdx = startIndex
    var lineLength = prefix
    let advanceLengthByOne = { ()->() in
      lineLength += SourceLength(utf8Length: 1)
      curIdx = utf8.index(after: curIdx)
    }

    while curIdx < endIndex {
      let char = utf8[curIdx]
      advanceLengthByOne()

      /// From https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_line-break
      /// * line-break → U+000A
      /// * line-break → U+000D
      /// * line-break → U+000D followed by U+000A
      let isNewline = { () -> Bool in
        if char == 10 { return true }
        if char == 13 {
          if curIdx < endIndex && utf8[curIdx] == 10 { advanceLengthByOne() }
          return true
        }
        return false
      }

      if isNewline() {
        body(lineLength)
        lineLength = .zero
      }
    }
    return lineLength
  }