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
25
26// Aliases for spans of bytes.
27using ByteSpan = span<std::byte>;
28
29using ConstByteSpan = span<const std::byte>;
30
44template <typename T>
45span<const std::byte, sizeof(T)> ObjectAsBytes(const T& obj) {
46 static_assert(std::is_trivially_copyable_v<T>,
47 "cannot treat object as bytes: "
48 "copying bytes may result in an invalid object");
49 static_assert(std::has_unique_object_representations_v<T>,
50 "cannot treat object as bytes: "
51 "type includes indeterminate bytes which may leak information "
52 "or result in incorrect object hashing");
53
54 auto s = pw::span<const T, 1>(std::addressof(obj), 1);
55 return pw::as_bytes(s);
56}
57
70template <typename T>
71span<std::byte, sizeof(T)> ObjectAsWritableBytes(T& obj) {
72 static_assert(std::is_trivially_copyable_v<T>,
73 "cannot treat object as bytes: "
74 "copying bytes may result in an invalid object");
75 static_assert(std::has_unique_object_representations_v<T>,
76 "cannot treat object as bytes: "
77 "type includes indeterminate bytes which may leak information "
78 "or result in incorrect object hashing");
79
80 auto s = pw::span<T, 1>(std::addressof(obj), 1);
81 return pw::as_writable_bytes(s);
82}
83
85
86} // namespace pw
Definition: span_impl.h:235
span< const std::byte, sizeof(T)> ObjectAsBytes(const T &obj)
Definition: span.h:45
span< std::byte, sizeof(T)> ObjectAsWritableBytes(T &obj)
Definition: span.h:71
The Pigweed namespace.
Definition: alignment.h:27