Swift和Go之间的Zlib压缩

My Swift application communicates to a server written in Go. I'd like the data transferred to be compressed using Zlib, but it appears that the compression results are different from Swift and Go.

Here is the Go version:

sourceString := "A-t-elle besoin d'autres preuves ? Acceptez-la pour le plaisir. J'ai tant fait que de la cueillir, Et c'est presque une fleur-des-veuves."

// Compression
var b bytes.Buffer
writer := zlib.NewWriter(&b)
writer.Write([]byte(sourceString))
writer.Close()

// Base 64
b64 := base64.StdEncoding.EncodeToString(b.Bytes())

fmt.Println(b64)

It gives the following (Go Playground):

eJwczb2tg0AQReFWbkbylhaeCJy4i/FykUYaLev5IXD1Fs6Pzre1bDQjXoxTB/ZFKp2B6ayLgX9svXMmP80E8yyHEdNEQ33FcxFFykgcool3ETthgl5UM/U/PBJ9YeS9jDuoQRzG8rYz2vVz1m8AAAD//++yMFQ=

Now using the following Swift code (based on this article):

let sourceString = "A-t-elle besoin d'autres preuves ? Acceptez-la pour le plaisir. J'ai tant fait que de la cueillir, Et c'est presque une fleur-des-veuves."

var sourceBuffer = Array(sourceString.utf8)

let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: sourceString.count)

let algorithm = COMPRESSION_ZLIB

let compressedSize = compression_encode_buffer(destinationBuffer, sourceString.count, &sourceBuffer, sourceString.count, nil, algorithm)

if compressedSize == 0 {
    fatalError("Encoding failed.")
}

// EDIT after @Steffen Ullrich answer
// let encodedString = String(cString: destinationBuffer)
// let encodedStringb64 = Data(encodedString.utf8).base64EncodedString()

let encodedData = NSData(bytesNoCopy: destinationBuffer, length: compressedSize)
let encodedStringb64 = encodedData.base64EncodedString()

print(encodedStringb64)

We get:

H̶e̶+̶/̶v̶T̶E̶O̶7̶7̶+̶9̶M̶A̶x̶D̶0̶a̶t̶w̶7̶7̶+̶9̶U̶u̶+̶/̶v̶Q̶p̶F̶7̶7̶+̶9̶L̶O̶+̶/̶v̶e̶+̶/̶v̶e̶+̶/̶v̶T̶D̶v̶v̶7̶0̶=̶ Hc0xDsMwDEPRq3DzUucKRYYsvYXqMIAAwXFtKUNPX6cTlwf+NXumGfHmOLViTxLeOdA645r7xFoKm/ObTdDO6Ji6mejQvuCVROFSHYeo4xPETkxZgmqm/YHNURKH35fjBlGJwxg97xz5+neWHw==

As you can see it is very different, what am i doing wrong here?

查看全部
dongyun7571
dongyun7571
2019/06/20 01:46
  • zlib
  • compression
  • swift
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复