import Foundation /// Splits a byte stream into newline-terminated lines, dropping CR and /// enforcing the 64 KB line cap — the same framing the C++ and Kotlin /// receivers use. Extracted so the logic is testable in isolation. final class LineAssembler { private var pending: [UInt8] = [] private let maxLine = SignalingMessage.maxMessageBytes /// Feed a chunk of received bytes; returns the complete lines it contained. func feed(_ chunk: [UInt8]) -> [String] { var lines: [String] = [] for b in chunk { if b == 0x0A { // \n let text = String(bytes: pending, encoding: .utf8) ?? "" pending.removeAll(keepingCapacity: true) if !text.isEmpty { lines.append(text) } } else if b != 0x0D { // \r if pending.count < maxLine { pending.append(b) } else { // Hostile or broken peer: drop the oversized line. pending.removeAll(keepingCapacity: true) } } } return lines } func reset() { pending.removeAll(keepingCapacity: true) } }