OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "sync/internal_api/public/base/node_ordinal.h" | |
6 | |
7 #include <stddef.h> | |
8 #include <stdint.h> | |
9 | |
10 #include <algorithm> | |
11 #include <string> | |
12 | |
13 namespace syncer { | |
14 | |
15 NodeOrdinal Int64ToNodeOrdinal(int64_t x) { | |
16 uint64_t y = static_cast<uint64_t>(x); | |
17 y ^= 0x8000000000000000ULL; | |
18 std::string bytes(NodeOrdinal::kMinLength, '\x00'); | |
19 if (y == 0) { | |
20 // 0 is a special case since |bytes| must not be all zeros. | |
21 bytes.push_back('\x80'); | |
22 } else { | |
23 for (int i = 7; i >= 0; --i) { | |
24 bytes[i] = static_cast<uint8_t>(y); | |
25 y >>= 8; | |
26 } | |
27 } | |
28 NodeOrdinal ordinal(bytes); | |
29 DCHECK(ordinal.IsValid()); | |
30 return ordinal; | |
31 } | |
32 | |
33 int64_t NodeOrdinalToInt64(const NodeOrdinal& ordinal) { | |
34 uint64_t y = 0; | |
35 const std::string& s = ordinal.ToInternalValue(); | |
36 size_t l = NodeOrdinal::kMinLength; | |
37 if (s.length() < l) { | |
38 NOTREACHED(); | |
39 l = s.length(); | |
40 } | |
41 for (size_t i = 0; i < l; ++i) { | |
42 const uint8_t byte = s[l - i - 1]; | |
43 y |= static_cast<uint64_t>(byte) << (i * 8); | |
44 } | |
45 y ^= 0x8000000000000000ULL; | |
46 // This is technically implementation-defined if y > INT64_MAX, so | |
47 // we're assuming that we're on a twos-complement machine. | |
48 return static_cast<int64_t>(y); | |
49 } | |
50 | |
51 } // namespace syncer | |
OLD | NEW |