Austin Schuh | 272c613 | 2020-11-14 16:37:52 -0800 | [diff] [blame^] | 1 | import Foundation |
| 2 | |
| 3 | /// Mutable is a protocol that allows us to mutate Scalar values within the buffer |
| 4 | public protocol Mutable { |
| 5 | /// makes Flatbuffer accessed within the Protocol |
| 6 | var bb: ByteBuffer { get } |
| 7 | /// makes position of the table/struct accessed within the Protocol |
| 8 | var postion: Int32 { get } |
| 9 | } |
| 10 | |
| 11 | extension Mutable { |
| 12 | |
| 13 | /// Mutates the memory in the buffer, this is only called from the access function of table and structs |
| 14 | /// - Parameters: |
| 15 | /// - value: New value to be inserted to the buffer |
| 16 | /// - index: index of the Element |
| 17 | func mutate<T: Scalar>(value: T, o: Int32) -> Bool { |
| 18 | guard o != 0 else { return false } |
| 19 | bb.write(value: value, index: Int(o), direct: true) |
| 20 | return true |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | extension Mutable where Self == Table { |
| 25 | |
| 26 | /// Mutates a value by calling mutate with respect to the position in the table |
| 27 | /// - Parameters: |
| 28 | /// - value: New value to be inserted to the buffer |
| 29 | /// - index: index of the Element |
| 30 | public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { |
| 31 | guard index != 0 else { return false } |
| 32 | return mutate(value: value, o: index + postion) |
| 33 | } |
| 34 | |
| 35 | /// Directly mutates the element by calling mutate |
| 36 | /// |
| 37 | /// Mutates the Element at index ignoring the current position by calling mutate |
| 38 | /// - Parameters: |
| 39 | /// - value: New value to be inserted to the buffer |
| 40 | /// - index: index of the Element |
| 41 | public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { |
| 42 | return mutate(value: value, o: index) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | extension Mutable where Self == Struct { |
| 47 | |
| 48 | /// Mutates a value by calling mutate with respect to the position in the struct |
| 49 | /// - Parameters: |
| 50 | /// - value: New value to be inserted to the buffer |
| 51 | /// - index: index of the Element |
| 52 | public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { |
| 53 | return mutate(value: value, o: index + postion) |
| 54 | } |
| 55 | |
| 56 | /// Directly mutates the element by calling mutate |
| 57 | /// |
| 58 | /// Mutates the Element at index ignoring the current position by calling mutate |
| 59 | /// - Parameters: |
| 60 | /// - value: New value to be inserted to the buffer |
| 61 | /// - index: index of the Element |
| 62 | public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { |
| 63 | return mutate(value: value, o: index) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | extension Struct: Mutable {} |
| 68 | extension Table: Mutable {} |