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 { 9 private var utf16LineOffsets: [Int] = [0] 10 11 public init(source: String) { 12 for idx in source.indices { 13 let c = source[idx] 14 if c == "\n" || c == "\r\n" || c == "\r" { 15 let next = source.index(after: idx) 16 let utf16Offset = next.utf16Offset(in: source) 17 utf16LineOffsets.append(utf16Offset) 18 } 19 } 20 } 21 22 public func location(at utf16Offset: Int) -> (line: Int, column: Int) { 23 let partitioningIndex = utf16LineOffsets.partitioningIndex { $0 > utf16Offset } 24 let lineIndex = partitioningIndex == 0 ? 0 : partitioningIndex - 1 25 let lineStart = utf16LineOffsets[lineIndex] 26 let lineNumber = lineIndex + 1 27 let columnNumber = utf16Offset - lineStart + 1 28 return (lineNumber, columnNumber) 29 } 30}