trace_id.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // TraceId represents an opaque 128-bit trace identifier. The trace identifier
  12. // remains constant across the trace. A valid trace identifier is a 16-byte array with at
  13. // least one non-zero byte.
  14. class TraceId final
  15. {
  16. public:
  17. // The size in bytes of the TraceId.
  18. static constexpr int kSize = 16;
  19. // An invalid TraceId (all zeros).
  20. TraceId() noexcept : rep_{0} {}
  21. // Creates a TraceId with the given ID.
  22. explicit TraceId(nostd::span<const uint8_t, kSize> id) noexcept
  23. {
  24. memcpy(rep_, id.data(), kSize);
  25. }
  26. // Populates the buffer with the lowercase base16 representation of the ID.
  27. void ToLowerBase16(nostd::span<char, 2 * kSize> buffer) const noexcept
  28. {
  29. constexpr char kHex[] = "0123456789abcdef";
  30. for (int i = 0; i < kSize; ++i)
  31. {
  32. buffer[i * 2 + 0] = kHex[(rep_[i] >> 4) & 0xF];
  33. buffer[i * 2 + 1] = kHex[(rep_[i] >> 0) & 0xF];
  34. }
  35. }
  36. // Returns a nostd::span of the ID.
  37. nostd::span<const uint8_t, kSize> Id() const noexcept
  38. {
  39. return nostd::span<const uint8_t, kSize>(rep_);
  40. }
  41. bool operator==(const TraceId &that) const noexcept
  42. {
  43. return memcmp(rep_, that.rep_, kSize) == 0;
  44. }
  45. bool operator!=(const TraceId &that) const noexcept { return !(*this == that); }
  46. // Returns false if the TraceId is all zeros.
  47. bool IsValid() const noexcept { return *this != TraceId(); }
  48. // Copies the opaque TraceId data to dest.
  49. void CopyBytesTo(nostd::span<uint8_t, kSize> dest) const noexcept
  50. {
  51. memcpy(dest.data(), rep_, kSize);
  52. }
  53. private:
  54. uint8_t rep_[kSize];
  55. };
  56. } // namespace trace
  57. OPENTELEMETRY_END_NAMESPACE