|
| 1 | +//===------------------------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftTencentSCFRuntime open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2020 stevapple and the SwiftTencentSCFRuntime project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftTencentSCFRuntime project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===------------------------------------------------------------------------------------===// |
| 14 | +// |
| 15 | +// This source file was part of the SwiftAWSLambdaRuntime open source project |
| 16 | +// |
| 17 | +// Copyright (c) 2017-2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors |
| 18 | +// Licensed under Apache License v2.0 |
| 19 | +// |
| 20 | +// See LICENSE.txt for license information |
| 21 | +// See http://github.com/swift-server/swift-aws-lambda-runtime/blob/master/CONTRIBUTORS.txt |
| 22 | +// for the list of SwiftAWSLambdaRuntime project authors |
| 23 | +// |
| 24 | +// SPDX-License-Identifier: Apache-2.0 |
| 25 | +// |
| 26 | +//===------------------------------------------------------------------------------------===// |
| 27 | + |
| 28 | +internal extension String { |
| 29 | + func jsonEncoded() -> String { |
| 30 | + var bytes = [UInt8]() |
| 31 | + let stringBytes = self.utf8 |
| 32 | + var startCopyIndex = stringBytes.startIndex |
| 33 | + var nextIndex = startCopyIndex |
| 34 | + |
| 35 | + while nextIndex != stringBytes.endIndex { |
| 36 | + switch stringBytes[nextIndex] { |
| 37 | + case 0 ..< 32, UInt8(ascii: "\""), UInt8(ascii: "\\"): |
| 38 | + // All Unicode characters may be placed within the |
| 39 | + // quotation marks, except for the characters that MUST be escaped: |
| 40 | + // quotation mark, reverse solidus, and the control characters (U+0000 |
| 41 | + // through U+001F). |
| 42 | + // https://tools.ietf.org/html/rfc7159#section-7 |
| 43 | + // copy the current range over |
| 44 | + bytes.append(contentsOf: stringBytes[startCopyIndex ..< nextIndex]) |
| 45 | + bytes.append(UInt8(ascii: "\\")) |
| 46 | + bytes.append(stringBytes[nextIndex]) |
| 47 | + |
| 48 | + nextIndex = stringBytes.index(after: nextIndex) |
| 49 | + startCopyIndex = nextIndex |
| 50 | + default: |
| 51 | + nextIndex = stringBytes.index(after: nextIndex) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return String(bytes: bytes, encoding: .utf8)! |
| 56 | + } |
| 57 | +} |
0 commit comments