1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "SnappyUtils.h"
8
9 #include <stddef.h>
10 #include "mozilla/Assertions.h"
11 #include "mozilla/fallible.h"
12 #include "nsDebug.h"
13 #include "nsString.h"
14 #include "snappy/snappy.h"
15
16 namespace mozilla::dom {
17
SnappyCompress(const nsACString & aSource,nsACString & aDest)18 bool SnappyCompress(const nsACString& aSource, nsACString& aDest) {
19 MOZ_ASSERT(!aSource.IsVoid());
20
21 size_t uncompressedLength = aSource.Length();
22
23 if (uncompressedLength <= 16) {
24 aDest.SetIsVoid(true);
25 return true;
26 }
27
28 size_t compressedLength = snappy::MaxCompressedLength(uncompressedLength);
29
30 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) {
31 return false;
32 }
33
34 snappy::RawCompress(aSource.BeginReading(), uncompressedLength,
35 aDest.BeginWriting(), &compressedLength);
36
37 if (compressedLength >= uncompressedLength) {
38 aDest.SetIsVoid(true);
39 return true;
40 }
41
42 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) {
43 return false;
44 }
45
46 return true;
47 }
48
SnappyUncompress(const nsACString & aSource,nsACString & aDest)49 bool SnappyUncompress(const nsACString& aSource, nsACString& aDest) {
50 MOZ_ASSERT(!aSource.IsVoid());
51
52 const char* compressed = aSource.BeginReading();
53
54 size_t compressedLength = aSource.Length();
55
56 size_t uncompressedLength;
57 if (!snappy::GetUncompressedLength(compressed, compressedLength,
58 &uncompressedLength)) {
59 return false;
60 }
61
62 aDest.SetLength(uncompressedLength);
63
64 if (!snappy::RawUncompress(compressed, compressedLength,
65 aDest.BeginWriting())) {
66 return false;
67 }
68
69 return true;
70 }
71
72 } // namespace mozilla::dom
73