• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 Google Inc. All rights reserved.
3  *
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 
17 public protocol FlatBufferGRPCMessage {
18 
19   /// Raw pointer which would be pointing to the beginning of the readable bytes
20   var rawPointer: UnsafeMutableRawPointer { get }
21 
22   /// Size of readable bytes in the buffer
23   var size: Int { get }
24 
25   init(byteBuffer: ByteBuffer)
26 }
27 
28 /// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
29 /// GRPC library
30 public struct Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
31   internal var buffer: ByteBuffer
32 
33   /// Returns the an object of type T that would be  read from the buffer
34   public var object: T {
35     T.init(
36       buffer,
37       o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + Int32(buffer.reader))
38   }
39 
40   public var rawPointer: UnsafeMutableRawPointer { buffer.memory.advanced(by: buffer.reader) }
41 
42   public var size: Int { Int(buffer.size) }
43 
44   /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over
45   /// GRPC
46   /// - Parameter byteBuffer: Flatbuffer ByteBuffer object
47   public init(byteBuffer: ByteBuffer) {
48     buffer = byteBuffer
49   }
50 
51   /// Initializes the message by copying the buffer to the message to be sent.
52   /// from the builder
53   /// - Parameter builder: FlatbufferBuilder that has the bytes created in
54   /// - Note: Use  `builder.finish(offset)` before passing the builder without prefixing anything to it
55   public init(builder: inout FlatBufferBuilder) {
56     buffer = builder.sizedBuffer
57     builder.clear()
58   }
59 }
60