Anonymous user
LZW compression: Difference between revisions
m
→{{header|Swift}}
m (Optimized Lua decompress using table.concat. On 1.2mb test data, ~44x faster. 58.8s to 1.3s) |
|||
Line 4,904:
{{trans|JavaScript}}
<lang swift>class LZW {
class func compress(_ uncompressed:String) -> [Int] {
var dict = [String : Int]()
for i in 0 ..< 256 {
let s = String(
dict[s] = i
▲ }
var dictSize = 256▼
var result = [Int]()▼
for c in uncompressed {
} else {▼
result.append(dict[w]!)▼
}▼
}▼
if w != "" {▼
result.append(dict[w]!)
}▼
return result▼
}
class func decompress(_ compressed:[Int]) -> String? {▼
▲ var dictSize = 256
var
▲ var result = [Int]()
for
▲ w = wc
for k in compressed[1 ..< compressed.count] {▼
▲ w = String(c)
let entry : String▼
▲ }
if let x = dict[k] {
} else if k == dictSize {
} else {
return nil▼
}
result += entry▼
dict[dictSize+1] = w + String(entry[entry.startIndex])
w = entry
}▼
return result▼
}
▲ if w != "" {
▲ result.append(dict[w]!)
▲ }
▲ return result
▲ class func decompress(compressed:[Int]) -> String? {
▲ for k in compressed[1 ..< compressed.count] {
▲ let entry : String
▲ if let x = dict[k] {
▲ entry = x
▲ } else if k == dictSize {
▲ entry = w + String(first(w)!)
▲ } else {
▲ return nil
▲ }
▲ result += entry
▲ dict[dictSize++] = w + String(first(entry)!)
▲ w = entry
▲ return result
}
let comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT")
if let decomp = LZW.decompress(comp) {
}</lang>
{{out}}
|