i have some hex encoding code that’s growing (in my opinion), an absurd amount of boilerplate.
public
enum Base16
{
@inlinable public static
func encodeBigEndian<Words>(_ words:Words, as _:String.Type = String.self,
by ascii:(UInt8) throws -> UInt8) rethrows -> String
{
try .init(unsafeUninitializedCapacity: 2 * MemoryLayout<Words>.size)
{
var utf8:UnsafeMutableBufferPointer<UInt8> = $0
try Self.encodeBigEndian(words, utf8: &utf8, by: ascii)
return $0.count
}
}
@inlinable public static
func encodeBigEndian<Words>(lowercasing words:Words, as _:String.Type = String.self)
-> String
{
Self.encodeBigEndian(words, by: Self.ascii(lowercasing:))
}
@inlinable public static
func encodeBigEndian<Words>(uppercasing words:Words, as _:String.Type = String.self)
-> String
{
Self.encodeBigEndian(words, by: Self.ascii(uppercasing:))
}
@inlinable public static
func encodeBigEndian<Words>(lowercasing words:Words, as _:[UInt8].Type = [UInt8].self)
-> [UInt8]
{
Self.encodeBigEndian(words, by: Self.ascii(lowercasing:))
}
@inlinable public static
func encodeBigEndian<Words>(uppercasing words:Words, as _:[UInt8].Type = [UInt8].self)
-> [UInt8]
{
Self.encodeBigEndian(words, by: Self.ascii(uppercasing:))
}
@inlinable public static
func encodeBigEndian<Words>(_ words:Words, as _:[UInt8].Type = [UInt8].self,
by ascii:(UInt8) throws -> UInt8) rethrows -> [UInt8]
{
try .init(unsafeUninitializedCapacity: 2 * MemoryLayout<Words>.size)
{
try Self.encodeBigEndian(words, utf8: &$0, by: ascii)
$1 = $0.count
}
}
@inlinable public static
func encodeBigEndian<UTF8, Words>(lowercasing words:Words, utf8:inout UTF8)
where UTF8:MutableCollection, UTF8.Element == UInt8
{
Self.encodeBigEndian(words, utf8: &utf8, by: Self.ascii(lowercasing:))
}
@inlinable public static
func encodeBigEndian<UTF8, Words>(uppercasing words:Words, utf8:inout UTF8)
where UTF8:MutableCollection, UTF8.Element == UInt8
{
Self.encodeBigEndian(words, utf8: &utf8, by: Self.ascii(uppercasing:))
}
@inlinable public static
func encodeBigEndian<UTF8, Words>(_ words:Words, utf8:inout UTF8,
by ascii:(UInt8) throws -> UInt8) rethrows
where UTF8:MutableCollection, UTF8.Element == UInt8
{
try withUnsafeBytes(of: words)
{
assert(utf8.count == $0.count * 2)
var offset:UTF8.Index = utf8.startIndex
for byte:UInt8 in $0
{
utf8[offset] = try ascii(byte >> 4)
utf8.formIndex(after: &offset)
utf8[offset] = try ascii(byte & 0x0f)
utf8.formIndex(after: &offset)
}
}
}
}
any tips on how to cut this down to size?