Skip to content

Instantly share code, notes, and snippets.

@davepeck
Last active July 7, 2016 21:23
Show Gist options
  • Save davepeck/495ea71f815ce292d6e0 to your computer and use it in GitHub Desktop.
Save davepeck/495ea71f815ce292d6e0 to your computer and use it in GitHub Desktop.
Swift Toys
//
// BinaryDataScanner.swift
//
// Created by Dave Peck on 7/20/14.
// Copyright (c) 2014 Dave Peck. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
/*
Toying with tools to help read binary formats.
I've seen lots of approaches in swift that create
an intermediate object per-read (usually another NSData)
but even if these are lightweight under the hood,
it seems like overkill. Plus this taught me about <()> aka <Void>
And it would be nice to have an extension to
NSFileHandle too that does much the same.
*/
protocol BinaryReadable {
var littleEndian: Self { get }
var bigEndian: Self { get }
}
extension UInt8: BinaryReadable {
var littleEndian: UInt8 { return self }
var bigEndian: UInt8 { return self }
}
extension UInt16: BinaryReadable {}
extension UInt32: BinaryReadable {}
extension UInt64: BinaryReadable {}
class BinaryDataScanner {
let data: NSData
let littleEndian: Bool
let encoding: NSStringEncoding
var current: UnsafePointer<Void>
var remaining: Int
init(data: NSData, littleEndian: Bool, encoding: NSStringEncoding) {
self.data = data
self.littleEndian = littleEndian
self.encoding = encoding
self.current = self.data.bytes
self.remaining = self.data.length
}
func read<T: BinaryReadable>() -> T? {
if remaining < sizeof(T) {
return nil
}
let tCurrent = UnsafePointer<T>(current)
let v = tCurrent.memory
current = UnsafePointer<Void>(tCurrent.successor())
remaining -= sizeof(T)
return littleEndian ? v.littleEndian : v.bigEndian
}
/* convenience read funcs */
func readByte() -> UInt8? {
return read()
}
func read16() -> UInt16? {
return read()
}
func read32() -> UInt32? {
return read()
}
func read64() -> UInt64? {
return read()
}
func readNullTerminatedString() -> String? {
var string:String? = nil
var tCurrent = UnsafePointer<UInt8>(current)
var count: Int = 0
// scan
while (remaining > 0 && tCurrent.memory != 0) {
remaining -= 1
count += 1
tCurrent = tCurrent.successor()
}
// create string if available
if (remaining > 0 && tCurrent.memory == 0) {
string = NSString(bytes: current, length: count, encoding: encoding) as String
current = UnsafePointer<()>(tCurrent.successor())
remaining -= 1
}
return string
}
}
@davepeck
Copy link
Author

Would be really nice to have a func readEndian<T>(byteCount: Int) -> T? that calls underlying read<T>() and then uses the scanner's littleEndian property to return the correct final value... doesn't seem possible since there's no common protocol?

@davepeck
Copy link
Author

Thanks to @natecook1000 -- have an answer for that.

@davepeck
Copy link
Author

Updated for swiftb6

@arunicus
Copy link

Is there anything special I need todo in order to read a float? I tried to do it the way you did Int but i'm not getting the correct value.

@davepeck
Copy link
Author

@arunvenkate Just noticed your question. I haven't actually updated this for Swift 1.0 (or 1.1 betas) but in theory I think it should work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment