C/C++ API Reference
Loading...
Searching...
No Matches
span.h
1// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <cstddef>
17#include <memory>
18#include <type_traits>
19
20#include "pw_span/span.h"
21
22namespace pw {
23
24// Aliases for spans of bytes.
25using ByteSpan = span<std::byte>;
26
27using ConstByteSpan = span<const std::byte>;
28
42template <typename T>
43span<const std::byte, sizeof(T)> ObjectAsBytes(const T& obj) {
44 static_assert(std::is_trivially_copyable_v<T>,
45 "cannot treat object as bytes: "
46 "copying bytes may result in an invalid object");
47 static_assert(std::has_unique_object_representations_v<T>,
48 "cannot treat object as bytes: "
49 "type includes indeterminate bytes which may leak information "
50 "or result in incorrect object hashing");
51
52 auto s = pw::span<const T, 1>(std::addressof(obj), 1);
53 return pw::as_bytes(s);
54}
55
68template <typename T>
69span<std::byte, sizeof(T)> ObjectAsWritableBytes(T& obj) {
70 static_assert(std::is_trivially_copyable_v<T>,
71 "cannot treat object as bytes: "
72 "copying bytes may result in an invalid object");
73 static_assert(std::has_unique_object_representations_v<T>,
74 "cannot treat object as bytes: "
75 "type includes indeterminate bytes which may leak information "
76 "or result in incorrect object hashing");
77
78 auto s = pw::span<T, 1>(std::addressof(obj), 1);
79 return pw::as_writable_bytes(s);
80}
81
82} // namespace pw
Definition: span_impl.h:235
The Pigweed namespace.
Definition: alignment.h:27
span< const std::byte, sizeof(T)> ObjectAsBytes(const T &obj)
Definition: span.h:43
span< std::byte, sizeof(T)> ObjectAsWritableBytes(T &obj)
Definition: span.h:69