Skip to content

Instantly share code, notes, and snippets.

@patrickjuchli
Last active June 22, 2022 10:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save patrickjuchli/d1b07f97e0ea1da5db09 to your computer and use it in GitHub Desktop.
Save patrickjuchli/d1b07f97e0ea1da5db09 to your computer and use it in GitHub Desktop.
import Foundation
/**
Set FourCharCode/OSType using a String.
Examples:
let test: FourCharCode = "420v"
let test2 = FourCharCode("420f")
print(test.string, test2.string)
*/
extension FourCharCode: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
var code: FourCharCode = 0
// Value has to consist of 4 printable ASCII characters, e.g. '420v'.
// Note: This implementation does not enforce printable range (32-126)
if value.characters.count == 4 && value.utf8.count == 4 {
for byte in value.utf8 {
code = code << 8 + FourCharCode(byte)
}
}
else {
print("FourCharCode: Can't initialize with '\(value)', only printable ASCII allowed. Setting to '????'.")
code = 0x3F3F3F3F // = '????'
}
self = code
}
public init(extendedGraphemeClusterLiteral value: String) {
self = FourCharCode(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self = FourCharCode(stringLiteral: value)
}
public init(_ value: String) {
self = FourCharCode(stringLiteral: value)
}
public var string: String? {
let cString: [CChar] = [
CChar(self >> 24 & 0xFF),
CChar(self >> 16 & 0xFF),
CChar(self >> 8 & 0xFF),
CChar(self & 0xFF),
0
]
return String.fromCString(cString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment