Skip to content

Commit 9db4387

Browse files
authored
Merge pull request #1749 from evoskuil/master
Add literal_length() constexprs.
2 parents 6c5664a + 2f1dcdf commit 9db4387

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

include/bitcoin/system/types.hpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ using unsigned_exact_type =
175175
iif<Bytes == sizeof(uint64_t), uint64_t,
176176
uintx_t<Bytes * 8u>>>>>>;
177177

178-
/// Text capture.
178+
/// Literal capture.
179179
/// ---------------------------------------------------------------------------
180180

181181
// Implementation requires c-style array.
@@ -200,6 +200,21 @@ struct text_t
200200
}
201201
};
202202

203+
template <size_t Size, typename Byte,
204+
std::enable_if_t<std::is_same_v<Byte, char>, bool> = true>
205+
constexpr size_t literal_length(const Byte(&)[Size]) noexcept
206+
{
207+
// Excludes literal string null terminator.
208+
return Size - 1;
209+
}
210+
211+
template <size_t Size, typename Byte,
212+
std::enable_if_t<std::is_same_v<Byte, uint8_t>, bool> = true>
213+
constexpr size_t literal_length(const Byte(&)[Size]) noexcept
214+
{
215+
return Size;
216+
}
217+
203218
BC_POP_WARNING()
204219
BC_POP_WARNING()
205220

test/types.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,22 @@ static_assert(is_same_type<unsigned_exact_type<256>, uintx_t<to_bits(256u)>>);
236236
static_assert(is_same_type<unsigned_exact_type<512>, uintx_t<to_bits(512u)>>);
237237
static_assert(is_same_type<unsigned_exact_type<1024>, uintx_t<to_bits(1024u)>>);
238238
static_assert(is_same_type<unsigned_exact_type<2048>, uintx_t<to_bits(2048u)>>);
239+
240+
// literal_length
241+
// ----------------------------------------------------------------------------
242+
243+
static_assert(literal_length("") == 0_size);
244+
static_assert(literal_length("abc") == 3_size);
245+
static_assert(literal_length("a\0c") == 3_size);
246+
247+
static constexpr const char empty_text[] = "";
248+
static_assert(literal_length(empty_text) == 0_size);
249+
250+
static constexpr const char double_terminated[] = "abc\0";
251+
static_assert(literal_length(double_terminated) == 4_size);
252+
253+
static constexpr const char middle_terminated[] = "a\0c";
254+
static_assert(literal_length(middle_terminated) == 3_size);
255+
256+
static constexpr const uint8_t not_empty_bytes[] = { 0x42, 0x00, 0x42, 0x00 };
257+
static_assert(literal_length(not_empty_bytes) == 4_size);

0 commit comments

Comments
 (0)