span_id.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include <cstdint>
  5. #include <cstring>
  6. #include "opentelemetry/nostd/span.h"
  7. #include "opentelemetry/version.h"
  8. OPENTELEMETRY_BEGIN_NAMESPACE
  9. namespace trace
  10. {
  11. class SpanId final
  12. {
  13. public:
  14. // The size in bytes of the SpanId.
  15. static constexpr int kSize = 8;
  16. // An invalid SpanId (all zeros).
  17. SpanId() noexcept : rep_{0} {}
  18. // Creates a SpanId with the given ID.
  19. explicit SpanId(nostd::span<const uint8_t, kSize> id) noexcept { memcpy(rep_, id.data(), kSize); }
  20. // Populates the buffer with the lowercase base16 representation of the ID.
  21. void ToLowerBase16(nostd::span<char, 2 * kSize> buffer) const noexcept
  22. {
  23. constexpr char kHex[] = "0123456789abcdef";
  24. for (int i = 0; i < kSize; ++i)
  25. {
  26. buffer[i * 2 + 0] = kHex[(rep_[i] >> 4) & 0xF];
  27. buffer[i * 2 + 1] = kHex[(rep_[i] >> 0) & 0xF];
  28. }
  29. }
  30. // Returns a nostd::span of the ID.
  31. nostd::span<const uint8_t, kSize> Id() const noexcept
  32. {
  33. return nostd::span<const uint8_t, kSize>(rep_);
  34. }
  35. bool operator==(const SpanId &that) const noexcept { return memcmp(rep_, that.rep_, kSize) == 0; }
  36. bool operator!=(const SpanId &that) const noexcept { return !(*this == that); }
  37. // Returns false if the SpanId is all zeros.
  38. bool IsValid() const noexcept
  39. {
  40. static constexpr uint8_t kEmptyRep[kSize] = {0};
  41. return memcmp(rep_, kEmptyRep, kSize) != 0;
  42. }
  43. // Copies the opaque SpanId data to dest.
  44. void CopyBytesTo(nostd::span<uint8_t, kSize> dest) const noexcept
  45. {
  46. memcpy(dest.data(), rep_, kSize);
  47. }
  48. private:
  49. uint8_t rep_[kSize];
  50. };
  51. } // namespace trace
  52. OPENTELEMETRY_END_NAMESPACE