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 
41 constexpr B operator""_B(unsigned long long v) {  // NOLINT
42     return B{v};
43 }
44 
45 constexpr KiB operator""_KiB(unsigned long long v) {  // NOLINT
46     return KiB{v};
47 }
48 
49 constexpr MiB operator""_MiB(unsigned long long v) {  // NOLINT
50     return MiB{v};
51 }
52 
53 constexpr GiB operator""_GiB(unsigned long long v) {  // NOLINT
54     return GiB{v};
55 }
56 
57 template <typename Dest, typename Src>
size_cast(Src src)58 constexpr Dest size_cast(Src src) {
59     if (Src::power < Dest::power) {
60         return Dest(src.count() >> (Dest::power - Src::power));
61     }
62     if (Src::power > Dest::power) {
63         return Dest(src.count() << (Src::power - Dest::power));
64     }
65     return Dest(src.count());
66 }
67 
68 static_assert(1_B == 1);
69 static_assert(1_KiB == 1 << 10);
70 static_assert(1_MiB == 1 << 20);
71 static_assert(1_GiB == 1 << 30);
72 static_assert(size_cast<KiB>(1_B).count() == 0);
73 static_assert(size_cast<KiB>(1024_B).count() == 1);
74 static_assert(size_cast<KiB>(1_MiB).count() == 1024);
75 
76 }  // namespace storage_literals
77 }  // namespace android
78