File: OutputByteStream.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (550 lines) | stat: -rw-r--r-- 19,606 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

public import struct Foundation.Data

/// Convert an integer in 0..<16 to its hexadecimal ASCII character.
private func hexdigit(_ value: UInt8) -> UInt8 {
    return value < 10 ? (0x30 + value) : (0x41 + value - 10)
}

public protocol ByteStreamable {
    func writeTo(_ stream: OutputByteStream)
}

public final class JSONOutputStreamer {
    private let stream: OutputByteStream
    private var queuedPairs = [(any ByteStreamable, any ByteStreamable)]()

    fileprivate init(stream: OutputByteStream) {
        self.stream = stream
    }

    fileprivate func writeObject(_ body: ((_ json: JSONOutputStreamer) -> Void)) {
        stream <<< UInt8(ascii: "{")
        let innerStreamer = JSONOutputStreamer(stream: stream)
        body(innerStreamer)
        for (i, pair) in innerStreamer.queuedPairs.enumerated() {
            if i != 0 { stream <<< UInt8(ascii: ",") }
            stream <<< pair.0
            stream <<< UInt8(ascii: ":")
            stream <<< pair.1
        }
        stream <<< UInt8(ascii: "}")
    }

    public subscript(key: String) -> ByteString {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> String {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> [String] {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> [ByteString] {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> KeyValuePairs<String, String> {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> [(String, String)] {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), Format.asJSON(newValue))) }
    }

    public subscript(key: String) -> Bool {
        get { fatalError() }
        set { queuedPairs.append((Format.asJSON(key), newValue ? "true" : "false")) }
    }
}

@available(*, unavailable)
extension JSONOutputStreamer: Sendable { }

// This extension contains methods designed to write JSON to the stream,
// where the *value* (not the key) of the dictionary is pre-encoded JSON bytes.
extension JSONOutputStreamer {
    public func writeMapWithLiteralValues(_ json: KeyValuePairs<String, ByteString>, forKey key: String) {
        queuedPairs.append((Format.asJSON(key), Format.asJSON(json)))
    }

    public func writeMapWithLiteralValues(_ json: [(String, ByteString)], forKey key: String) {
        queuedPairs.append((Format.asJSON(key), Format.asJSON(json)))
    }
}

extension OutputByteStream {
    public func writeJSONObject(_ body: ((_ json: JSONOutputStreamer) -> Void)) {
        JSONOutputStreamer(stream: self).writeObject(body)
    }

    public func writingJSONObject(_ body: ((_ json: JSONOutputStreamer) -> Void)) -> OutputByteStream {
        writeJSONObject(body)
        return self
    }
}

/// An output byte stream.
///
/// This class is designed to be able to support efficient streaming to different output destinations, e.g., a file or an in memory buffer. This is loosely modeled on LLVM's llvm::raw_ostream class.
///
/// The stream is generally used in conjunction with the custom streaming operator '<<<'. For example:
///
///   let stream = OutputByteStream()
///   stream <<< "Hello, world!"
///
/// would write the UTF8 encoding of "Hello, world!" to the stream.
///
/// The stream accepts a number of custom formatting operators which are defined in the `Format` struct (used for namespacing purposes). For example:
///
///   let items = ["hello", "world"]
///   stream <<< Format.asSeparatedList(items, separator: " ")
///
/// would write each item in the list to the stream, separating them with a space.
public final class OutputByteStream: TextOutputStream {
    /// The data buffer.
    private var buffer: [UInt8]

    public init() {
        self.buffer = []
    }

    // MARK: Data Access API

    /// The current offset within the output stream.
    public var position: Int {
        return buffer.count
    }

    /// The contents of the output stream.
    ///
    /// This method implicitly flushes the stream.
    public var bytes: ByteString {
        flush()
        return ByteString(self.buffer)
    }

    // MARK: Data Output API

    public func flush() {
        // Do nothing.
    }

    /// Write an individual byte to the buffer.
    public func write(_ byte: UInt8) {
        buffer.append(byte)
    }

    /// Write a sequence of bytes to the buffer.
    public func write(_ bytes: [UInt8]) {
        buffer += bytes
    }

    /// Write a data chunk to the buffer.
    public func write(_ bytes: Data) {
        // FIXME: [UInt8] has no fast path for Data: <rdar://problem/32069787> [UInt8] += has no fast path for Data
        bytes.withUnsafeBytes {
            buffer += $0
        }
    }

    /// Write a sequence of bytes to the buffer.
    public func write(_ bytes: ArraySlice<UInt8>) {
        buffer += bytes
    }

    /// Write a sequence of bytes to the buffer.
    public func write<S: Sequence>(_ sequence: S) where S.Iterator.Element == UInt8 {
        buffer += sequence
    }

    /// Write a string to the buffer (as UTF8).
    public func write(_ string: String) {
        // FIXME: We used to have a very valuable fast path for contiguous strings. See: <rdar://problem/29208285>
        //
        // For some reason Swift itself doesn't implement this optimization: <rdar://problem/24100375> Missing fast path for [UInt8] += String.UTF8View
        buffer += string.utf8
    }

    /// Write a character to the buffer (as UTF8).
    public func write(_ character: Character) {
        buffer += String(character).utf8
    }

    /// Write an arbitrary byte streamable to the buffer.
    public func write(_ value: any ByteStreamable) {
        value.writeTo(self)
    }

    /// Write an arbitrary streamable to the buffer.
    public func write(_ value: any TextOutputStreamable) {
        // Get a mutable reference.
        var stream: OutputByteStream = self
        value.write(to: &stream)
    }

    /// Write a string (as UTF8) to the buffer, with escaping appropriate for embedding within a JSON document.
    ///
    /// NOTE: This writes the literal data applying JSON string escaping, but does not write any other characters (like the quotes that would surround a JSON string).
    public func writeJSONEscaped(_ string: String) {
        writeJSONEscaped(string: string.utf8)
    }

    /// Write a UTF8 encoded string to the buffer, with escaping appropriate for embedding within a JSON document.
    ///
    /// NOTE: This writes the literal data applying JSON string escaping, but does not write any other characters (like the quotes that would surround a JSON string).
    public func writeJSONEscaped<T: Collection>(
        string sequence: T
    ) where T.Iterator.Element == UInt8 {
        // See RFC7159 for reference.
        for character in sequence {
            switch character {
            // Literal characters.
            case 0x20...0x21, 0x23...0x5B, 0x5D...0xFF:
                buffer.append(character)

                // Single-character escaped characters.
            case 0x22: // '"'
                buffer.append(0x5C) // '\'
                buffer.append(0x22) // '"'
            case 0x5C: // '\\'
                buffer.append(0x5C) // '\'
                buffer.append(0x5C) // '\'
            case 0x08: // '\b'
                buffer.append(0x5C) // '\'
                buffer.append(0x62) // 'b'
            case 0x0C: // '\f'
                buffer.append(0x5C) // '\'
                buffer.append(0x66) // 'f'
            case 0x0A: // '\n'
                buffer.append(0x5C) // '\'
                buffer.append(0x6E) // 'n'
            case 0x0D: // '\r'
                buffer.append(0x5C) // '\'
                buffer.append(0x72) // 'r'
            case 0x09: // '\t'
                buffer.append(0x5C) // '\'
                buffer.append(0x74) // 't'

                // Multi-character escaped characters.
            default:
                buffer.append(0x5C) // '\'
                buffer.append(0x75) // 'u'
                buffer.append(hexdigit(0))
                buffer.append(hexdigit(0))
                buffer.append(hexdigit(character >> 4))
                buffer.append(hexdigit(character & 0xF))
            }
        }
    }
}

@available(*, unavailable)
extension OutputByteStream: Sendable { }

/// Define an output stream operator. We need it to be left associative, so we
/// use `<<<`.
infix operator <<< : StreamingPrecedence
precedencegroup StreamingPrecedence {
    associativity: left
    higherThan: AssignmentPrecedence
}

// MARK: Output Operator Implementations
//
// NOTE: It would be nice to use a protocol here and the adopt it by all the things we can efficiently stream out. However, that doesn't work because we ultimately need to provide a manual overload for, e.g., TextOutputStreamable, but that will then cause ambiguous lookup versus the implementation just using the defined protocol.

@discardableResult
public func <<<(stream: OutputByteStream, value: UInt8) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: [UInt8]) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: Data) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: ArraySlice<UInt8>) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<<S: Sequence>(stream: OutputByteStream, value: S) -> OutputByteStream where S.Iterator.Element == UInt8 {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: String) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: Character) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: any ByteStreamable) -> OutputByteStream {
    stream.write(value)
    return stream
}

@discardableResult
public func <<<(stream: OutputByteStream, value: any TextOutputStreamable) -> OutputByteStream {
    stream.write(value)
    return stream
}

extension UInt8: ByteStreamable {
    public func writeTo(_ stream: OutputByteStream) {
        stream.write(self)
    }
}

extension Character: ByteStreamable {
    public func writeTo(_ stream: OutputByteStream) {
        stream.write(self)
    }
}

extension String: ByteStreamable {
    public func writeTo(_ stream: OutputByteStream) {
        stream.write(self)
    }
}

// MARK: Formatted Streaming Output

// Not nested because it is generic.
private struct SeparatedListStreamable<T: ByteStreamable>: ByteStreamable {
    let items: [T]
    let separator: String

    func writeTo(_ stream: OutputByteStream) {
        for (i, item) in items.enumerated() {
            // Add the separator, if necessary.
            if i != 0 {
                stream <<< separator
            }

            stream <<< item
        }
    }
}

// Not nested because it is generic.
private struct TransformedSeparatedListStreamable<T>: ByteStreamable {
    let items: [T]
    let transform: (T) -> any ByteStreamable
    let separator: String

    func writeTo(_ stream: OutputByteStream) {
        for (i, item) in items.enumerated() {
            if i != 0 { stream <<< separator }
            stream <<< transform(item)
        }
    }
}

// Not nested because it is generic.
private struct JSONEscapedTransformedStringListStreamable<T>: ByteStreamable {
    let items: [T]
    let transform: (T) -> String

    func writeTo(_ stream: OutputByteStream) {
        stream <<< UInt8(ascii: "[")
        for (i, item) in items.enumerated() {
            if i != 0 { stream <<< UInt8(ascii: ",") }
            stream <<< Format.asJSON(transform(item))
        }
        stream <<< UInt8(ascii: "]")
    }
}

/// Provides operations for returning derived streamable objects to implement various forms of formatted output.
public enum Format: Sendable {
    /// Write the input string encoded as a JSON object.
    static public func asJSON(_ string: String) -> any ByteStreamable {
        return JSONEscapedStringStreamable(value: string)
    }
    private struct JSONEscapedStringStreamable: ByteStreamable {
        let value: String

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "\"")
            stream.writeJSONEscaped(value)
            stream <<< UInt8(ascii: "\"")
        }
    }

    /// Write the input byte string encoded as a JSON string.
    static public func asJSON(_ string: ByteString) -> any ByteStreamable {
        return JSONEscapedByteStringStreamable(value: string)
    }
    private struct JSONEscapedByteStringStreamable: ByteStreamable {
        let value: ByteString

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "\"")
            stream.writeJSONEscaped(string: value.bytes)
            stream <<< UInt8(ascii: "\"")
        }
    }

    /// Write the input string list encoded as a JSON object.
    //
    // FIXME: We might be able to make this more generic through the use of a "JSONEncodable" protocol.
    static public func asJSON(_ items: [String]) -> any ByteStreamable {
        return JSONEscapedStringListStreamable(items: items)
    }
    private struct JSONEscapedStringListStreamable: ByteStreamable {
        let items: [String]

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "[")
            for (i, item) in items.enumerated() {
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(item)
            }
            stream <<< UInt8(ascii: "]")
        }
    }

    /// Write the input byte string list encoded as a JSON object.
    //
    // FIXME: We might be able to make this more generic through the use of a "JSONEncodable" protocol.
    static public func asJSON(_ items: [ByteString]) -> any ByteStreamable {
        return JSONEscapedByteStringListStreamable(items: items)
    }
    private struct JSONEscapedByteStringListStreamable: ByteStreamable {
        let items: [ByteString]

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "[")
            for (i, item) in items.enumerated() {
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(item)
            }
            stream <<< UInt8(ascii: "]")
        }
    }

    /// Write the input dictionary encoded as a JSON object.
    static public func asJSON(_ items: KeyValuePairs<String, String>) -> any ByteStreamable {
        return JSONEscapedDictionaryLiteralStreamable(items: items)
    }
    private struct JSONEscapedDictionaryLiteralStreamable: ByteStreamable {
        let items: KeyValuePairs<String, String>

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "{")
            for (offset: i, element: (key: key, value: value)) in items.enumerated() {
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(key) <<< ":" <<< Format.asJSON(value)
            }
            stream <<< UInt8(ascii: "}")
        }
    }

    static public func asJSON(_ items: KeyValuePairs<String, ByteString>) -> any ByteStreamable {
        return JSONEscapedDictionaryByteStringLiteralStreamable(items: items)
    }
    private struct JSONEscapedDictionaryByteStringLiteralStreamable: ByteStreamable {
        let items: KeyValuePairs<String, ByteString>

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "{")
            for (offset: i, element: (key: key, value: value)) in items.enumerated() {
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(key) <<< ":" <<< /*Format.asJSON*/(value) // value is pre-escaped
            }
            stream <<< UInt8(ascii: "}")
        }
    }

    /// Write the input dictionary encoded as a JSON object.
    static public func asJSON(_ items: [(String, String)]) -> any ByteStreamable {
        return JSONEscapedDictionaryStreamable(items: items)
    }
    private struct JSONEscapedDictionaryStreamable: ByteStreamable {
        let items: [(String, String)]

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "{")
            for i in 0..<items.count {
                let (key: key, value: value) = items[i]
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(key) <<< ":" <<< Format.asJSON(value)
            }
            stream <<< UInt8(ascii: "}")
        }
    }

    /// Write the input dictionary encoded as a JSON object.
    static public func asJSON(_ items: [(String, ByteString)]) -> any ByteStreamable {
        return JSONEscapedByteStringPairSequenceStreamable(items: items)
    }
    private struct JSONEscapedByteStringPairSequenceStreamable: ByteStreamable {
        let items: [(String, ByteString)]

        func writeTo(_ stream: OutputByteStream) {
            stream <<< UInt8(ascii: "{")
            for i in 0..<items.count {
                let (key: key, value: value) = items[i]
                if i != 0 { stream <<< UInt8(ascii: ",") }
                stream <<< Format.asJSON(key) <<< ":" <<< /*Format.asJSON*/(value) // value is pre-escaped
            }
            stream <<< UInt8(ascii: "}")
        }
    }

    /// Write the input list (after applying a transform to each item) encoded as a JSON object.
    //
    // FIXME: We might be able to make this more generic through the use of a "JSONEncodable" protocol.
    static public func asJSON<T>(_ items: [T], transform: @escaping (T) -> String) -> any ByteStreamable {
        return JSONEscapedTransformedStringListStreamable(items: items, transform: transform)
    }

    /// Write the input list to the stream with the given separator between items.
    static public func asSeparatedList<T: ByteStreamable>(_ items: [T], separator: String) -> any ByteStreamable {
        return SeparatedListStreamable(items: items, separator: separator)
    }

    /// Write the input list to the stream (after applying a transform to each item) with the given separator between items.
    static public func asSeparatedList<T>(_ items: [T], transform: @escaping (T) -> any ByteStreamable, separator: String) -> any ByteStreamable {
        return TransformedSeparatedListStreamable(items: items, transform: transform, separator: separator)
    }
}