Skip to content

Instantly share code, notes, and snippets.

@networkextension
Created August 11, 2016 03:26
Show Gist options
  • Save networkextension/55e07499e4625b0e0e0a11215320e169 to your computer and use it in GitHub Desktop.
Save networkextension/55e07499e4625b0e0e0a11215320e169 to your computer and use it in GitHub Desktop.
http Transfer-Encodeing parser Swift sample
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let a = "25\r\nThis is the data in the first chunk\r\n" + "1C\r\nand this is the second one\r\n" + "3\r\ncon" + "8\r\nsequence" + "0\r\n\r\n"
let d = a.data(using: .utf8, allowLossyConversion: false)
struct chunked{
var len:Int = 0
var leftLen:Int = 0
var data:Data?
init(l:Int, rLen:Int){
len = l
leftLen -= rLen
}
}
let b = "\r\n".data(using: .utf8, allowLossyConversion: false)!
var packets :[chunked] = []
func dataToInt(d:Data) ->UInt32{
var result:UInt32 = 0
let x = "0x" + String.init(data: d, encoding: .utf8)!
print("xx:" + x)
_ = Scanner(string:x).scanHexInt32(&result)
return result
}
func parser(data:NSData){
print(data)
var used = 0
let total = data.length
let opt = NSData.SearchOptions.init(rawValue: 0)
while used < total {
let r = data.range(of: b as Data, options: opt, in: NSRange(location: used,length: data.length-used))
if r.location != NSNotFound {
print("used xx: \(used) \(r.location)")
let l = data.subdata(with: NSMakeRange(used, r.location - used))
print("l \(l) len: \(l.count)")
used += l.count // count length
used += r.length //算上\r\n
print("used: \(used)")
let c_leng = Int(dataToInt(d: l))
if c_leng == 0 {
let r2 = data.range(of: b as Data, options: opt, in: NSRange(location: used,length: data.length-used))
if r.location != NSNotFound {
used += r2.length
}
if used == total{
print("find last ")
return
}
}
print("thunk len: \(c_leng) \(used + c_leng)")
if used + c_leng <= total {
var p = chunked.init(l: c_leng, rLen: 0)
if used + c_leng != total {
p.data = data.subdata(with: NSMakeRange(used, c_leng))
}
packets.append(p)
used += c_leng
print("found \(used) \(r.location) \(r.location) \(used) \(p.data)")
}else {
print("not full")
print("found \(used + c_leng ) \(r.location) \(r.location) \(used) ")
return
}
print("used: \(used)")
}else {
print("not found")
}
print("used: \(used)")
}
}
parser(data: d!)
for p in packets {
print("len \(p.len) left:\(p.leftLen)")
if let data = p.data {
print(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment