Advertisement
JetForMe

Untitled

Jul 29th, 2020
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.09 KB | None | 0 0
  1. //
  2. //  BinaryReader.swift
  3. //  TerrainFun
  4. //
  5. //  Created by Rick Mann on 2020-07-28.
  6. //  Copyright © 2020 Latency: Zero, LLC. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11.  
  12.  
  13.  
  14. struct
  15. BinaryReader
  16. {
  17.     init(data inData: Data)
  18.     {
  19.         self.data = inData
  20.     }
  21.    
  22.     mutating
  23.     func
  24.     get<T>()
  25.         -> T where T : FixedWidthInteger
  26.     {
  27.         let size = MemoryLayout<T>.size
  28.         let v: T = self.data.subdata(in: self.idx..<self.idx + size).withUnsafeBytes { $0.load(as: T.self) }
  29.         self.idx += size
  30.         if self.bigEndian
  31.         {
  32.             return T(bigEndian: v)
  33.         }
  34.         else
  35.         {
  36.             return T(littleEndian: v)
  37.         }
  38.     }
  39.    
  40.     mutating
  41.     func
  42.     seek(by inDelta: Int)
  43.     {
  44.         self.idx += inDelta
  45.         precondition(self.idx >= 0 && self.idx < self.data.count, "seek(by: \(inDelta)) out of bounds")
  46.     }
  47.    
  48.     mutating
  49.     func
  50.     seek(to inOffset: Int)
  51.     {
  52.         precondition(inOffset >= 0 && inOffset < self.data.count, "seek(to: \(inOffset)) out of bounds")
  53.         self.idx = inOffset
  54.     }
  55.    
  56.     mutating
  57.     func
  58.     seek(to inOffset: UInt32)
  59.     {
  60.         seek(to: Int(inOffset))
  61.     }
  62.    
  63.     let data            :   Data
  64.     var idx                         =   0
  65.     var bigEndian                   =   true
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement