UsageInfo.h (2581B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=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 #ifndef mozilla_dom_quota_usageinfo_h__ 8 #define mozilla_dom_quota_usageinfo_h__ 9 10 #include <cstdint> 11 12 #include "mozilla/CheckedInt.h" 13 #include "mozilla/Maybe.h" 14 15 namespace mozilla::dom::quota { 16 17 enum struct UsageKind { Database, File }; 18 19 namespace detail { 20 inline void AddCapped(Maybe<uint64_t>& aValue, const Maybe<uint64_t> aDelta) { 21 if (aDelta.isSome()) { 22 CheckedUint64 value = aValue.valueOr(0); 23 24 value += aDelta.value(); 25 26 aValue = Some(value.isValid() ? value.value() : UINT64_MAX); 27 } 28 } 29 30 template <UsageKind Kind> 31 struct Usage { 32 explicit Usage(Maybe<uint64_t> aValue = Nothing{}) : mValue(aValue) {} 33 34 Maybe<uint64_t> GetValue() const { return mValue; } 35 36 Usage& operator+=(const Usage aDelta) { 37 AddCapped(mValue, aDelta.mValue); 38 39 return *this; 40 } 41 42 Usage operator+(const Usage aDelta) const { 43 Usage res = *this; 44 res += aDelta; 45 return res; 46 } 47 48 private: 49 Maybe<uint64_t> mValue; 50 }; 51 } // namespace detail 52 53 using DatabaseUsageType = detail::Usage<UsageKind::Database>; 54 using FileUsageType = detail::Usage<UsageKind::File>; 55 56 class UsageInfo final { 57 public: 58 UsageInfo() = default; 59 60 explicit UsageInfo(const DatabaseUsageType aUsage) : mDatabaseUsage(aUsage) {} 61 62 explicit UsageInfo(const FileUsageType aUsage) : mFileUsage(aUsage) {} 63 64 UsageInfo operator+(const UsageInfo& aUsageInfo) { 65 UsageInfo res = *this; 66 res += aUsageInfo; 67 return res; 68 } 69 70 UsageInfo& operator+=(const UsageInfo& aUsageInfo) { 71 mDatabaseUsage += aUsageInfo.mDatabaseUsage; 72 mFileUsage += aUsageInfo.mFileUsage; 73 return *this; 74 } 75 76 UsageInfo& operator+=(const DatabaseUsageType aUsage) { 77 mDatabaseUsage += aUsage; 78 return *this; 79 } 80 81 UsageInfo& operator+=(const FileUsageType aUsage) { 82 mFileUsage += aUsage; 83 return *this; 84 } 85 86 Maybe<uint64_t> DatabaseUsage() const { return mDatabaseUsage.GetValue(); } 87 88 Maybe<uint64_t> FileUsage() const { return mFileUsage.GetValue(); } 89 90 Maybe<uint64_t> TotalUsage() const { 91 Maybe<uint64_t> res = mDatabaseUsage.GetValue(); 92 detail::AddCapped(res, FileUsage()); 93 return res; 94 } 95 96 private: 97 DatabaseUsageType mDatabaseUsage; 98 FileUsageType mFileUsage; 99 }; 100 101 } // namespace mozilla::dom::quota 102 103 #endif // mozilla_dom_quota_usageinfo_h__