Android-cuttlefish cvd tool
storage_literals.h
Go to the documentation of this file.
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
20namespace android {
21namespace storage_literals {
22
23template <size_t Power>
24struct Size {
25 static constexpr size_t power = Power;
26 explicit constexpr Size(uint64_t count) : value_(count) {}
27
28 constexpr uint64_t bytes() const { return value_ << power; }
29 constexpr uint64_t count() const { return value_; }
30 constexpr operator uint64_t() const { return bytes(); }
31
32 private:
33 uint64_t value_;
34};
35
36using B = Size<0>;
37using KiB = Size<10>;
38using MiB = Size<20>;
39using GiB = Size<30>;
40using TiB = Size<40>;
41
42constexpr B operator""_B(unsigned long long v) { // NOLINT
43 return B{v};
44}
45
46constexpr KiB operator""_KiB(unsigned long long v) { // NOLINT
47 return KiB{v};
48}
49
50constexpr MiB operator""_MiB(unsigned long long v) { // NOLINT
51 return MiB{v};
52}
53
54constexpr GiB operator""_GiB(unsigned long long v) { // NOLINT
55 return GiB{v};
56}
57
58constexpr TiB operator""_TiB(unsigned long long v) { // NOLINT
59 return TiB{v};
60}
61
62template <typename Dest, typename Src>
63constexpr 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
73static_assert(1_B == 1);
74static_assert(1_KiB == 1 << 10);
75static_assert(1_MiB == 1 << 20);
76static_assert(1_GiB == 1 << 30);
77static_assert(1_TiB == 1ULL << 40);
78static_assert(size_cast<KiB>(1_B).count() == 0);
79static_assert(size_cast<KiB>(1024_B).count() == 1);
80static_assert(size_cast<KiB>(1_MiB).count() == 1024);
81
82} // namespace storage_literals
83} // namespace android
constexpr Dest size_cast(Src src)
Definition: storage_literals.h:63
Definition: map_ptr.h:34
Definition: storage_literals.h:24
constexpr uint64_t count() const
Definition: storage_literals.h:29
uint64_t value_
Definition: storage_literals.h:33
constexpr uint64_t bytes() const
Definition: storage_literals.h:28
constexpr Size(uint64_t count)
Definition: storage_literals.h:26
static constexpr size_t power
Definition: storage_literals.h:25