unpack.go 1001 B

12345678910111213141516171819202122232425262728293031
  1. // Copyright (c) 2021 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package binary
  7. import (
  8. "bytes"
  9. "compress/zlib"
  10. "fmt"
  11. "io"
  12. )
  13. // Unpack unpacks the given decrypted data from the WhatsApp web API.
  14. //
  15. // It checks the first byte to decide whether to uncompress the data with zlib or just return as-is
  16. // (without the first byte). There's currently no corresponding Pack function because Marshal
  17. // already returns the data with a leading zero (i.e. not compressed).
  18. func Unpack(data []byte) ([]byte, error) {
  19. dataType, data := data[0], data[1:]
  20. if 2&dataType > 0 {
  21. if decompressor, err := zlib.NewReader(bytes.NewReader(data)); err != nil {
  22. return nil, fmt.Errorf("failed to create zlib reader: %w", err)
  23. } else if data, err = io.ReadAll(decompressor); err != nil {
  24. return nil, err
  25. }
  26. }
  27. return data, nil
  28. }