Skip to content

Instantly share code, notes, and snippets.

@alexbosworth
Created January 12, 2017 17:58
Show Gist options
  • Save alexbosworth/dbbbef3857dd4572674d544a4c9c83a7 to your computer and use it in GitHub Desktop.
Save alexbosworth/dbbbef3857dd4572674d544a4c9c83a7 to your computer and use it in GitHub Desktop.
/** Compact size uint marker byte
*/
enum CompactSizeMarker: Byte {
case uint8, uint16 = 253, uint32, uint64
/** Byte length of discriminant
*/
static let discriminantByteLength = 1
/** Hex byte length
*/
static let hexByteLength = 2
/** Init from discriminator byte
*/
init(from discriminator: Byte) throws {
switch discriminator {
case type(of: self).uint8.marker..<type(of: self).uint16.marker:
self = .uint8
case type(of: self).uint16.marker:
self = .uint16
case type(of: self).uint32.marker:
self = .uint32
case type(of: self).uint64.marker:
self = .uint64
default:
throw MarkerError.unexpectedDiscriminatorValue
}
}
/** Marker that indicates type
*/
var marker: Byte { return rawValue }
/** Compact size errors
*/
enum MarkerError: String, Error {
case unexpectedDiscriminatorValue
}
/** Value byte length
*/
var valueByteLength: Int {
switch self {
case .uint8:
return 0
case .uint16:
return 2
case .uint32:
return 4
case .uint64:
return 8
}
}
/** In a hex, length of characters for the value
*/
var valueHexOffset: String.IndexDistance {
return String.IndexDistance(valueByteLength * type(of: self).hexByteLength)
}
/** Byte length required for the compact size representation
*/
var variableByteLength: Int {
return type(of: self).discriminantByteLength + valueByteLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment