• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2019 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <stdint.h>
18 #include <stdlib.h>
19 
20 namespace android {
21 namespace storage_literals {
22 
23 template <size_t Power>
24 struct Size {
25     static constexpr size_t power = Power;
SizeSize26     explicit constexpr Size(uint64_t count) : value_(count) {}
27 
bytesSize28     constexpr uint64_t bytes() const { return value_ << power; }
countSize29     constexpr uint64_t count() const { return value_; }
uint64_tSize30     constexpr operator uint64_t() const { return bytes(); }
31 
32   private:
33     uint64_t value_;
34 };
35 
36 using B = Size<0>;
37 using KiB = Size<10>;
38 using MiB = Size<20>;
39 using GiB = Size<30>;
40 using TiB = Size<40>;
41 
42 constexpr B operator""_B(unsigned long long v) {  // NOLINT
43     return B{v};
44 }
45 
46 constexpr KiB operator""_KiB(unsigned long long v) {  // NOLINT
47     return KiB{v};
48 }
49 
50 constexpr MiB operator""_MiB(unsigned long long v) {  // NOLINT
51     return MiB{v};
52 }
53 
54 constexpr GiB operator""_GiB(unsigned long long v) {  // NOLINT
55     return GiB{v};
56 }
57 
58 constexpr TiB operator""_TiB(unsigned long long v) {  // NOLINT
59     return TiB{v};
60 }
61 
62 template <typename Dest, typename Src>
size_cast(Src src)63 constexpr Dest size_cast(Src src) {
64     if (Src::power < Dest::power) {
65         return Dest(src.count() >> (Dest::power - Src::power));
66     }
67     if (Src::power > Dest::power) {
68         return Dest(src.count() << (Src::power - Dest::power));
69     }
70     return Dest(src.count());
71 }
72 
73 static_assert(1_B == 1);
74 static_assert(1_KiB == 1 << 10);
75 static_assert(1_MiB == 1 << 20);
76 static_assert(1_GiB == 1 << 30);
77 static_assert(1_TiB == 1ULL << 40);
78 static_assert(size_cast<KiB>(1_B).count() == 0);
79 static_assert(size_cast<KiB>(1024_B).count() == 1);
80 static_assert(size_cast<KiB>(1_MiB).count() == 1024);
81 
82 }  // namespace storage_literals
83 }  // namespace android
84