blob: eb0bad972b471edc5c6c9190373e956a0d259ccf [file] [log] [blame]
Austin Schuh58b9b472020-11-25 19:12:44 -08001/*
James Kuszmaul8e62b022022-03-22 09:33:25 -07002 * Copyright 2021 Google Inc. All rights reserved.
Austin Schuh58b9b472020-11-25 19:12:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
James Kuszmaul8e62b022022-03-22 09:33:25 -070017import Foundation
18
19/// FlatBufferGRPCMessage protocol that should allow us to invoke
20/// initializers directly from the GRPC generated code
Austin Schuh272c6132020-11-14 16:37:52 -080021public protocol FlatBufferGRPCMessage {
Austin Schuh58b9b472020-11-25 19:12:44 -080022
23 /// Raw pointer which would be pointing to the beginning of the readable bytes
24 var rawPointer: UnsafeMutableRawPointer { get }
25
26 /// Size of readable bytes in the buffer
27 var size: Int { get }
28
29 init(byteBuffer: ByteBuffer)
Austin Schuh272c6132020-11-14 16:37:52 -080030}
31
32/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
33/// GRPC library
James Kuszmaul8e62b022022-03-22 09:33:25 -070034public struct Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
Austin Schuh58b9b472020-11-25 19:12:44 -080035 internal var buffer: ByteBuffer
36
37 /// Returns the an object of type T that would be read from the buffer
38 public var object: T {
39 T.init(
40 buffer,
James Kuszmaul8e62b022022-03-22 09:33:25 -070041 o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) +
42 Int32(buffer.reader))
Austin Schuh58b9b472020-11-25 19:12:44 -080043 }
44
James Kuszmaul8e62b022022-03-22 09:33:25 -070045 public var rawPointer: UnsafeMutableRawPointer {
46 buffer.memory.advanced(by: buffer.reader) }
Austin Schuh58b9b472020-11-25 19:12:44 -080047
48 public var size: Int { Int(buffer.size) }
49
50 /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over
51 /// GRPC
52 /// - Parameter byteBuffer: Flatbuffer ByteBuffer object
53 public init(byteBuffer: ByteBuffer) {
54 buffer = byteBuffer
55 }
56
57 /// Initializes the message by copying the buffer to the message to be sent.
58 /// from the builder
59 /// - Parameter builder: FlatbufferBuilder that has the bytes created in
60 /// - Note: Use `builder.finish(offset)` before passing the builder without prefixing anything to it
61 public init(builder: inout FlatBufferBuilder) {
62 buffer = builder.sizedBuffer
63 builder.clear()
64 }
Austin Schuh272c6132020-11-14 16:37:52 -080065}