Skip to content

Commit fb46d42

Browse files
nvgrwcopybara-github
authored andcommitted
Add Fprint128ToBytes utility function.
PiperOrigin-RevId: 755405286
1 parent e0dbd15 commit fb46d42

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

tsl/platform/fingerprint.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ limitations under the License.
1616
#ifndef TENSORFLOW_TSL_PLATFORM_FINGERPRINT_H_
1717
#define TENSORFLOW_TSL_PLATFORM_FINGERPRINT_H_
1818

19+
#include <array>
20+
#include <climits>
21+
#include <cstdint>
22+
1923
#include "xla/tsl/platform/types.h"
2024
#include "tsl/platform/platform.h"
2125
#include "tsl/platform/stringpiece.h"
@@ -122,6 +126,19 @@ inline Fprint128 FingerprintCat128(const Fprint128& a, const uint64_t b) {
122126
return {x, FingerprintCat64(a.high64, x)};
123127
}
124128

129+
inline std::array<char, 16> Fprint128ToBytes(tsl::Fprint128 fprint) {
130+
static_assert(sizeof(char) == 1, "Size of char is not 1 bytes.");
131+
static_assert(CHAR_BIT == 8, "Size of byte is not 8 bits.");
132+
std::array<char, 16> result;
133+
for (int i = 0; i < 8; ++i) {
134+
result[8 - i - 1] = fprint.low64 & 0xFF;
135+
result[16 - i - 1] = fprint.high64 & 0xFF;
136+
fprint.low64 >>= 8;
137+
fprint.high64 >>= 8;
138+
}
139+
return result;
140+
}
141+
125142
} // namespace tsl
126143

127144
#endif // TENSORFLOW_TSL_PLATFORM_FINGERPRINT_H_

tsl/platform/fingerprint_test.cc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ limitations under the License.
1515

1616
#include "tsl/platform/fingerprint.h"
1717

18+
#include <array>
1819
#include <unordered_set>
1920

2021
#include "xla/tsl/platform/test.h"
@@ -69,5 +70,14 @@ TEST(FingerprintCat64, Idempotence) {
6970
FingerprintCat64(Fingerprint64("Hello"), Fingerprint64("World")));
7071
}
7172

73+
TEST(Fprint128ToBytes, WorksCorrectly) {
74+
const Fprint128 fprint = {0xCAFEF00DDEADBEEF, 0xC0FFEE123456789A};
75+
constexpr std::array<char, 16> kExpected = {
76+
'\xca', '\xfe', '\xf0', '\x0d', '\xde', '\xad', '\xbe', '\xef',
77+
'\xc0', '\xff', '\xee', '\x12', '\x34', '\x56', '\x78', '\x9a',
78+
};
79+
EXPECT_EQ(Fprint128ToBytes(fprint), kExpected);
80+
}
81+
7282
} // namespace
7383
} // namespace tsl

0 commit comments

Comments
 (0)