Skip to content

Instantly share code, notes, and snippets.

@KentaKudo
Created January 15, 2017 22:14
Show Gist options
  • Save KentaKudo/71afd9d2786fc39e34653e7c77928d7c to your computer and use it in GitHub Desktop.
Save KentaKudo/71afd9d2786fc39e34653e7c77928d7c to your computer and use it in GitHub Desktop.
VBCode in Swift
import Foundation
// encode single UInt32 number
func vbEncodeNumber(n: UInt32) -> [UInt8] {
var n = n
var result = [UInt8]()
while true {
let byte = n % 128
result.insert(UInt8(byte), at: 0)
if n < 128 {
break
}
n = n / 128
}
result[result.count - 1] += 128
return result
}
// encode UInt32 numbers to VB code numbers
func vbEncode(ns: [UInt32]) -> [UInt8] {
return ns.flatMap(vbEncodeNumber)
}
// decode VB code numbers to UInt32 numbers
func vbDecode(bytes: [UInt8]) -> [UInt32] {
var result = [UInt32]()
var n: UInt32 = 0
for byte in bytes {
if byte < 128 {
n = 128 * n + UInt32(byte)
} else {
n = 128 * n + (UInt32(byte) - 128)
result.append(n)
n = 0
}
}
return result
}
// single number encode test
func vbEncodeNumberTest() -> Bool {
let result1 = (vbEncodeNumber(n: 5) == [UInt8(133)])
let result2 = (vbEncodeNumber(n: 130) == [UInt8(1), UInt8(130)])
return result1 && result2
}
// VB code encode test
func vbEncodeTest() -> Bool {
let numbers: [UInt32] = [5, 130, 45, 12, 150]
let result = vbEncode(ns: numbers)
return result == [UInt8(133), UInt8(1), UInt8(130), UInt8(173), UInt8(140), UInt8(1), UInt8(150)]
}
// VB code decode test
func vbDecodeTest() -> Bool {
let bytesteam = [UInt8(133), UInt8(1), UInt8(130), UInt8(173), UInt8(140), UInt8(1), UInt8(150)]
let result = vbDecode(bytes: bytesteam)
return result == [5, 130, 45, 12, 150]
}
vbEncodeNumberTest()
vbEncodeTest()
vbDecodeTest()
//let result = (1 ... 1000).map { [$0] }.map(vb_encode).flatMap(vb_decode)
//result == Array(1 ... 1000)
let helloworld = "hello, world".utf8.map{ UInt32($0) }
let encoded = vbEncode(ns: helloworld)
let decoded = vbDecode(bytes: encoded)
helloworld == decoded
// [UInt32] -> String
let uni = helloworld.flatMap(UnicodeScalar.init)
let chars = uni.map(Character.init)
String(chars)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment