trace_flags.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include <cstdint>
  5. #include "opentelemetry/nostd/span.h"
  6. #include "opentelemetry/version.h"
  7. OPENTELEMETRY_BEGIN_NAMESPACE
  8. namespace trace
  9. {
  10. // TraceFlags represents options for a Trace. These options are propagated to all child Spans
  11. // and determine features such as whether a Span should be traced. TraceFlags
  12. // are implemented as a bitmask.
  13. class TraceFlags final
  14. {
  15. public:
  16. static constexpr uint8_t kIsSampled = 1;
  17. static constexpr uint8_t kIsRandom = 2;
  18. /**
  19. * Valid flags in W3C Trace Context version 1.
  20. * See https://www.w3.org/TR/trace-context-1/#trace-flags
  21. */
  22. static constexpr uint8_t kAllW3CTraceContext1Flags = kIsSampled;
  23. /**
  24. * Valid flags in W3C Trace Context version 2.
  25. * See https://www.w3.org/TR/trace-context-1/#trace-flags
  26. */
  27. static constexpr uint8_t kAllW3CTraceContext2Flags = kIsSampled | kIsRandom;
  28. TraceFlags() noexcept : rep_{0} {}
  29. explicit TraceFlags(uint8_t flags) noexcept : rep_(flags) {}
  30. bool IsSampled() const noexcept { return rep_ & kIsSampled; }
  31. bool IsRandom() const noexcept { return rep_ & kIsRandom; }
  32. // Populates the buffer with the lowercase base16 representation of the flags.
  33. void ToLowerBase16(nostd::span<char, 2> buffer) const noexcept
  34. {
  35. constexpr char kHex[] = "0123456789ABCDEF";
  36. buffer[0] = kHex[(rep_ >> 4) & 0xF];
  37. buffer[1] = kHex[(rep_ >> 0) & 0xF];
  38. }
  39. uint8_t flags() const noexcept { return rep_; }
  40. bool operator==(const TraceFlags &that) const noexcept { return rep_ == that.rep_; }
  41. bool operator!=(const TraceFlags &that) const noexcept { return !(*this == that); }
  42. // Copies the TraceFlags to dest.
  43. void CopyBytesTo(nostd::span<uint8_t, 1> dest) const noexcept { dest[0] = rep_; }
  44. private:
  45. uint8_t rep_;
  46. };
  47. } // namespace trace
  48. OPENTELEMETRY_END_NAMESPACE