Last active
November 22, 2024 18:41
-
-
Save patrickjuchli/d1b07f97e0ea1da5db09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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