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/. */
7 #include "SnappyUtils.h"
10 #include "mozilla/Assertions.h"
11 #include "mozilla/CheckedInt.h"
12 #include "mozilla/fallible.h"
15 #include "snappy/snappy.h"
17 namespace mozilla::dom
{
19 static_assert(SNAPPY_VERSION
== 0x010200);
21 bool SnappyCompress(const nsACString
& aSource
, nsACString
& aDest
) {
22 MOZ_ASSERT(!aSource
.IsVoid());
24 size_t uncompressedLength
= aSource
.Length();
26 if (uncompressedLength
<= 16) {
27 aDest
.SetIsVoid(true);
31 size_t compressedLength
= snappy::MaxCompressedLength(uncompressedLength
);
33 if (NS_WARN_IF(!aDest
.SetLength(compressedLength
, fallible
))) {
37 snappy::RawCompress(aSource
.BeginReading(), uncompressedLength
,
38 aDest
.BeginWriting(), &compressedLength
);
40 if (compressedLength
>= uncompressedLength
) {
41 aDest
.SetIsVoid(true);
45 if (NS_WARN_IF(!aDest
.SetLength(compressedLength
, fallible
))) {
52 bool SnappyUncompress(const nsACString
& aSource
, nsACString
& aDest
) {
53 MOZ_ASSERT(!aSource
.IsVoid());
55 const char* compressed
= aSource
.BeginReading();
57 auto compressedLength
= static_cast<size_t>(aSource
.Length());
59 size_t uncompressedLength
= 0u;
60 if (!snappy::GetUncompressedLength(compressed
, compressedLength
,
61 &uncompressedLength
)) {
65 CheckedUint32
checkedLength(uncompressedLength
);
66 if (!checkedLength
.isValid()) {
70 aDest
.SetLength(checkedLength
.value());
72 if (!snappy::RawUncompress(compressed
, compressedLength
,
73 aDest
.BeginWriting())) {
80 } // namespace mozilla::dom