Skip to content

Commit

Permalink
util/SpanCast: add ReferenceAsBytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxKellermann committed Oct 21, 2023
1 parent 0de09e0 commit 7d00543
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/io/BufferedOutputStream.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public:
*/
template<typename T>
void WriteT(const T &value) {
Write(std::as_bytes(std::span{&value, 1}));
Write(ReferenceAsBytes(value));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/net/control/Builder.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ private:
}

void AppendT(const auto &s) noexcept {
Append(std::as_bytes(std::span{&s, 1}));
Append(ReferenceAsBytes(s));
}
};
3 changes: 2 additions & 1 deletion src/spawn/ResourceLimits.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "util/djb_hash.hxx"
#include "util/CharUtil.hxx"
#include "util/Sanitizer.hxx"
#include "util/SpanCast.hxx"

#include <cassert>

Expand Down Expand Up @@ -68,7 +69,7 @@ ResourceLimits::IsEmpty() const noexcept
inline std::size_t
ResourceLimits::GetHash() const noexcept
{
return djb_hash(std::as_bytes(std::span{this, 1}));
return djb_hash(ReferenceAsBytes(*this));
}

char *
Expand Down
3 changes: 2 additions & 1 deletion src/spawn/daemon/Builder.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "net/SendMessage.hxx"
#include "io/Iovec.hxx"
#include "util/CRC32.hxx"
#include "util/SpanCast.hxx"
#include "util/StaticVector.hxx"

class DatagramBuilder {
Expand Down Expand Up @@ -44,7 +45,7 @@ public:
}

void Append(const SpawnDaemon::RequestHeader &rh) noexcept {
AppendRaw(std::as_bytes(std::span{&rh, 1}));
AppendRaw(ReferenceAsBytes(rh));
}

void Append(const SpawnDaemon::ResponseHeader &rh) noexcept {
Expand Down
10 changes: 10 additions & 0 deletions src/util/SpanCast.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ AsBytes(std::string_view sv) noexcept
return std::as_bytes(ToSpan(sv));
}

/**
* Cast a reference to a fixed-size std::span<const std::byte>.
*/
template<typename T>
constexpr auto
ReferenceAsBytes(const T &value) noexcept
{
return std::as_bytes(std::span<const T, 1>{&value, 1});
}

constexpr std::string_view
ToStringView(std::span<const char> s) noexcept
{
Expand Down

0 comments on commit 7d00543

Please sign in to comment.