|
| 1 | +// Sources/SwiftProtobuf/Message+Applying.swift - Applying feature |
| 2 | +// |
| 3 | +// Copyright (c) 2014 - 2017 Apple Inc. and the project authors |
| 4 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 5 | +// |
| 6 | +// See LICENSE.txt for license information: |
| 7 | +// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt |
| 8 | +// |
| 9 | +// ----------------------------------------------------------------------------- |
| 10 | +/// |
| 11 | +/// Extends the `Message` type with applying behavior. |
| 12 | +/// |
| 13 | +// ----------------------------------------------------------------------------- |
| 14 | + |
| 15 | +public extension Message { |
| 16 | + |
| 17 | + /// Applies a value for a specific `fieldNumber` of the message |
| 18 | + /// and returns a copy of it. |
| 19 | + /// |
| 20 | + /// - Parameters: |
| 21 | + /// - value: The value to be applied. |
| 22 | + /// - fieldNumber: Protobuf index of the field that the value should be applied for. |
| 23 | + /// - Returns: A copy of the message with applied value. |
| 24 | + func applying(_ value: Any, for fieldNumber: Int) throws -> Self { |
| 25 | + var copy = self |
| 26 | + try copy.apply(value, for: fieldNumber) |
| 27 | + return copy |
| 28 | + } |
| 29 | + |
| 30 | + /// Applies a value for a specific `fieldNumber` of the message without |
| 31 | + /// making a copy. This method mutates the original message. |
| 32 | + /// |
| 33 | + /// - Parameters: |
| 34 | + /// - value: The value to be applied. |
| 35 | + /// - fieldNumber: Protobuf index of the field that the value should be applied for. |
| 36 | + mutating func apply(_ value: Any, for fieldNumber: Int) throws { |
| 37 | + var decoder = ApplyingDecoder(fieldNumber: fieldNumber, value: value) |
| 38 | + try decodeMessage(decoder: &decoder) |
| 39 | + } |
| 40 | +} |
0 commit comments