parselink-old/include/parselink/proto/session_id.h
2023-11-06 22:56:35 -08:00

89 lines
2.7 KiB
C++

//-----------------------------------------------------------------------------
// ___ __ _ _
// / _ \__ _ _ __ ___ ___ / /(_)_ __ | | __
// / /_)/ _` | '__/ __|/ _ \/ / | | '_ \| |/ /
// / ___/ (_| | | \__ \ __/ /__| | | | | <
// \/ \__,_|_| |___/\___\____/_|_| |_|_|\_\ .
//
//-----------------------------------------------------------------------------
// Author: Kurt Sassenrath
// Module: proto
//
// Session ID. Used as a handle to access an existing user session, which can
// also be used to share parse data without any linking of users.
//
// Copyright (c) 2023 Kurt Sassenrath.
//
// License TBD.
//-----------------------------------------------------------------------------
#ifndef session_id_6598f9bae1cbb501
#define session_id_6598f9bae1cbb501
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <span>
namespace parselink {
namespace proto {
struct session_id {
public:
session_id() noexcept;
// Not the intended way to build a session id. Ideally, they'll be randomly
// generated.
explicit constexpr session_id(std::array<std::byte, 32> const& v) noexcept {
std::copy(v.begin(), v.end(), bytes_.begin());
}
[[nodiscard]] constexpr auto operator<=>(
session_id const& other) const noexcept {
return bytes_ <=> other.bytes_;
}
[[nodiscard]] constexpr auto operator==(
session_id const& other) const noexcept {
return bytes_ == other.bytes_;
}
[[nodiscard]] constexpr auto operator<=>(
std::span<std::byte const> other) const noexcept {
return std::lexicographical_compare_three_way(bytes_.begin(),
bytes_.end(), other.begin(), other.end(),
std::compare_three_way());
}
[[nodiscard]] constexpr auto operator==(
std::span<std::byte const> other) const noexcept {
return std::equal(
bytes_.begin(), bytes_.end(), other.begin(), other.end());
}
constexpr std::span<std::byte const> raw() const noexcept { return bytes_; }
private:
std::array<std::byte, 32> bytes_;
};
} // namespace proto
} // namespace parselink
// Hashing support
template <>
struct std::hash<parselink::proto::session_id> {
constexpr static std::uint32_t seed_var = 0x811c9dc5;
constexpr static std::uint32_t factor = 0x01000193;
constexpr auto operator()(auto const& sid) const noexcept {
std::uint32_t digest = seed_var * factor;
for (auto byte : sid.raw()) {
digest = (digest ^ static_cast<std::uint32_t>(byte)) * factor;
}
return digest >> 8;
}
};
#endif // session_id_6598f9bae1cbb501