damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

Enum.swift (1950B)


      1 /*
      2  * Copyright 2023 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 #if !os(WASI)
     18 import Foundation
     19 #else
     20 import SwiftOverlayShims
     21 #endif
     22 
     23 /// Enum is a protocol that all flatbuffers enums should conform to
     24 /// Since it allows us to get the actual `ByteSize` and `Value` from
     25 /// a swift enum.
     26 public protocol Enum {
     27   /// associatedtype that the type of the enum should conform to
     28   associatedtype T: Scalar & Verifiable
     29   /// Size of the current associatedtype in the enum
     30   static var byteSize: Int { get }
     31   /// The current value the enum hosts
     32   var value: T { get }
     33 }
     34 
     35 extension Enum where Self: Verifiable {
     36 
     37   /// Verifies that the current value is which the bounds of the buffer, and if
     38   /// the current `Value` is aligned properly
     39   /// - Parameters:
     40   ///   - verifier: Verifier that hosts the buffer
     41   ///   - position: Current position within the buffer
     42   ///   - type: The type of the object to be verified
     43   /// - Throws: Errors coming from `inBuffer` function
     44   public static func verify<T>(
     45     _ verifier: inout Verifier,
     46     at position: Int,
     47     of type: T.Type) throws where T: Verifiable
     48   {
     49     try verifier.inBuffer(position: position, of: type.self)
     50   }
     51 
     52 }
     53 
     54 /// UnionEnum is a Protocol that allows us to create Union type of enums
     55 /// and their value initializers. Since an `init` was required by
     56 /// the verifier
     57 public protocol UnionEnum: Enum {
     58   init?(value: T) throws
     59 }