SnappyUtils.cpp (2080B)
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 11 #include "mozilla/Assertions.h" 12 #include "mozilla/CheckedInt.h" 13 #include "mozilla/fallible.h" 14 #include "nsDebug.h" 15 #include "nsString.h" 16 #include "snappy/snappy.h" 17 18 namespace mozilla::dom { 19 20 static_assert(SNAPPY_VERSION == 0x010202); 21 22 bool SnappyCompress(const nsACString& aSource, nsACString& aDest) { 23 MOZ_ASSERT(!aSource.IsVoid()); 24 25 size_t uncompressedLength = aSource.Length(); 26 27 if (uncompressedLength <= 16) { 28 aDest.SetIsVoid(true); 29 return true; 30 } 31 32 size_t compressedLength = snappy::MaxCompressedLength(uncompressedLength); 33 34 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) { 35 return false; 36 } 37 38 snappy::RawCompress(aSource.BeginReading(), uncompressedLength, 39 aDest.BeginWriting(), &compressedLength); 40 41 if (compressedLength >= uncompressedLength) { 42 aDest.SetIsVoid(true); 43 return true; 44 } 45 46 if (NS_WARN_IF(!aDest.SetLength(compressedLength, fallible))) { 47 return false; 48 } 49 50 return true; 51 } 52 53 bool SnappyUncompress(const nsACString& aSource, nsACString& aDest) { 54 MOZ_ASSERT(!aSource.IsVoid()); 55 56 const char* compressed = aSource.BeginReading(); 57 58 auto compressedLength = static_cast<size_t>(aSource.Length()); 59 60 size_t uncompressedLength = 0u; 61 if (!snappy::GetUncompressedLength(compressed, compressedLength, 62 &uncompressedLength)) { 63 return false; 64 } 65 66 CheckedUint32 checkedLength(uncompressedLength); 67 if (!checkedLength.isValid()) { 68 return false; 69 } 70 71 aDest.SetLength(checkedLength.value()); 72 73 if (!snappy::RawUncompress(compressed, compressedLength, 74 aDest.BeginWriting())) { 75 return false; 76 } 77 78 return true; 79 } 80 81 } // namespace mozilla::dom