Forked from patrickjuchli/FourCharCode+String.swift
Last active
June 23, 2022 01:03
-
-
Save donly/a591ee23b669dc61159b49f5a3a91d48 to your computer and use it in GitHub Desktop.
This file contains hidden or 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: ExpressibleByStringLiteral { | |
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.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 bytes: [CChar] = [ | |
CChar((self >> 24) & 0xff), | |
CChar((self >> 16) & 0xff), | |
CChar((self >> 8) & 0xff), | |
CChar(self & 0xff), | |
0 | |
] | |
let result = String(cString: bytes) | |
let characterSet = CharacterSet.whitespaces | |
return result.trimmingCharacters(in: characterSet) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: