Bug 1795723 - Unified extensions UI should support High Contrast Mode. r=ayeddi,deskt...
[gecko.git] / dom / localstorage / SnappyUtils.cpp
blobcf47421bc5338f4ceb407f5727ae42ef9eb05ea5
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"
9 #include <stddef.h>
10 #include "mozilla/Assertions.h"
11 #include "mozilla/CheckedInt.h"
12 #include "mozilla/fallible.h"
13 #include "nsDebug.h"
14 #include "nsString.h"
15 #include "snappy/snappy.h"
17 namespace mozilla::dom {
19 static_assert(SNAPPY_VERSION == 0x010109);
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);
28 return true;
31 size_t compressedLength = snappy::MaxCompressedLength(uncompressedLength);
33 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) {
34 return false;
37 snappy::RawCompress(aSource.BeginReading(), uncompressedLength,
38 aDest.BeginWriting(), &compressedLength);
40 if (compressedLength >= uncompressedLength) {
41 aDest.SetIsVoid(true);
42 return true;
45 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) {
46 return false;
49 return true;
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)) {
62 return false;
65 CheckedUint32 checkedLength(uncompressedLength);
66 if (!checkedLength.isValid()) {
67 return false;
70 aDest.SetLength(checkedLength.value());
72 if (!snappy::RawUncompress(compressed, compressedLength,
73 aDest.BeginWriting())) {
74 return false;
77 return true;
80 } // namespace mozilla::dom