]> git.proxmox.com Git - ceph.git/blob - ceph/src/seastar/include/seastar/core/byteorder.hh
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / seastar / include / seastar / core / byteorder.hh
1 /*
2 * This file is open source software, licensed to you under the terms
3 * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4 * distributed with this work for additional information regarding copyright
5 * ownership. You may not use this file except in compliance with the License.
6 *
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 */
18 /*
19 * Copyright (C) 2015 Scylladb, Ltd.
20 */
21
22 #pragma once
23
24 #include <algorithm>
25 #include <boost/endian/conversion.hpp>
26 #include <seastar/core/unaligned.hh>
27
28 namespace seastar {
29
30 template <typename T>
31 inline T cpu_to_le(T x) noexcept {
32 return boost::endian::native_to_little(x);
33 }
34 template <typename T>
35 inline T le_to_cpu(T x) noexcept {
36 return boost::endian::little_to_native(x);
37 }
38
39 template <typename T>
40 inline T cpu_to_be(T x) noexcept {
41 return boost::endian::native_to_big(x);
42 }
43 template <typename T>
44 inline T be_to_cpu(T x) noexcept {
45 return boost::endian::big_to_native(x);
46 }
47
48 template <typename T>
49 inline T cpu_to_le(const unaligned<T>& v) noexcept {
50 return cpu_to_le(T(v));
51 }
52
53 template <typename T>
54 inline T le_to_cpu(const unaligned<T>& v) noexcept {
55 return le_to_cpu(T(v));
56 }
57
58 template <typename T>
59 inline
60 T
61 read_le(const char* p) noexcept {
62 T datum;
63 std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
64 return le_to_cpu(datum);
65 }
66
67 template <typename T>
68 inline
69 void
70 write_le(char* p, T datum) noexcept {
71 datum = cpu_to_le(datum);
72 std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
73 }
74
75 template <typename T>
76 inline
77 T
78 read_be(const char* p) noexcept {
79 T datum;
80 std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
81 return be_to_cpu(datum);
82 }
83
84 template <typename T>
85 inline
86 void
87 write_be(char* p, T datum) noexcept {
88 datum = cpu_to_be(datum);
89 std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
90 }
91
92 template <typename T>
93 inline
94 T
95 consume_be(const char*& p) noexcept {
96 auto ret = read_be<T>(p);
97 p += sizeof(T);
98 return ret;
99 }
100
101 template <typename T>
102 inline
103 void
104 produce_be(char*& p, T datum) noexcept {
105 write_be<T>(p, datum);
106 p += sizeof(T);
107 }
108
109 }