1// SPDX-FileCopyrightText: 2025 The Project Pterodactyl Developers 2// 3// SPDX-License-Identifier: MPL-2.0 4 5import Algorithms 6import Foundation 7 8public struct LineMap: Codable, Sendable { 9 private let utf16LineOffsets: [Int] 10 11 public init(source: String) { 12 var offsets: [Int] = [0] 13 for idx in source.indices { 14 let c = source[idx] 15 if c == "\n" || c == "\r\n" || c == "\r" { 16 let next = source.index(after: idx) 17 let utf16Offset = next.utf16Offset(in: source) 18 offsets.append(utf16Offset) 19 } 20 } 21 self.utf16LineOffsets = offsets 22 } 23 24 public func location(at utf16Offset: Int) -> (line: Int, column: Int) { 25 let partitioningIndex = utf16LineOffsets.partitioningIndex { $0 > utf16Offset } 26 let lineIndex = partitioningIndex == 0 ? 0 : partitioningIndex - 1 27 let lineStart = utf16LineOffsets[lineIndex] 28 let lineNumber = lineIndex 29 let columnNumber = utf16Offset - lineStart 30 return (lineNumber, columnNumber) 31 } 32}