File tree Expand file tree Collapse file tree 4 files changed +43
-0
lines changed Expand file tree Collapse file tree 4 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ #include " nix/util/alignment.hh"
2+
3+ #include < gtest/gtest.h>
4+
5+ namespace nix {
6+
7+ TEST (alignUp, value)
8+ {
9+ for (uint64_t i = 1 ; i <= 8 ; ++i)
10+ EXPECT_EQ (alignUp (i, 8 ), 8 );
11+ }
12+
13+ TEST (alignUp, notAPowerOf2)
14+ {
15+ ASSERT_DEATH ({ alignUp (1u , 42 ); }, " alignment must be a power of 2" );
16+ }
17+
18+ } // namespace nix
Original file line number Diff line number Diff line change @@ -44,6 +44,7 @@ config_priv_h = configure_file(
4444subdir (' nix-meson-build-support/common' )
4545
4646sources = files (
47+ ' alignment.cc' ,
4748 ' archive.cc' ,
4849 ' args.cc' ,
4950 ' base-n.cc' ,
Original file line number Diff line number Diff line change 1+ #pragma once
2+ // /@file
3+
4+ #include < cassert>
5+ #include < type_traits>
6+ #include < cstdint>
7+ #include < bit>
8+
9+ namespace nix {
10+
11+ // / Aligns val upwards to be a multiple of alignment.
12+ // /
13+ // / @pre alignment must be a power of 2.
14+ template <typename T>
15+ requires std::is_unsigned_v<T>
16+ constexpr T alignUp (T val, unsigned alignment)
17+ {
18+ assert (std::has_single_bit (alignment) && " alignment must be a power of 2" );
19+ T mask = ~(T{alignment} - 1u );
20+ return (val + alignment - 1 ) & mask;
21+ }
22+
23+ } // namespace nix
Original file line number Diff line number Diff line change @@ -4,6 +4,7 @@ include_dirs = [ include_directories('../..') ]
44
55headers = files (
66 ' abstract-setting-to-json.hh' ,
7+ ' alignment.hh' ,
78 ' ansicolor.hh' ,
89 ' archive.hh' ,
910 ' args.hh' ,
You can’t perform that action at this time.
0 commit comments