Pigweed
 
Loading...
Searching...
No Matches
cast.h
1// Copyright 2025 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 "pw_bytes/alignment.h"
17#include "pw_span/internal/config.h"
18#include "pw_span/span.h"
19
20namespace pw {
21namespace internal {
22
23template <class ResultT, size_t kSourceExtentBytes>
24using SpanFromBytes = span<ResultT,
25 (kSourceExtentBytes == dynamic_extent
26 ? dynamic_extent
27 : kSourceExtentBytes / sizeof(ResultT))>;
28
29} // namespace internal
30
33
53template <class ResultT, size_t kSourceExtentBytes>
54internal::SpanFromBytes<ResultT, kSourceExtentBytes> span_cast(
55 span<std::byte, kSourceExtentBytes> bytes) {
56 static_assert(sizeof(ResultT) == 1);
57
58 ResultT* const ptr = reinterpret_cast<ResultT*>(bytes.data());
59 const size_t count = bytes.size() / sizeof(ResultT);
60
61 auto result =
62 internal::SpanFromBytes<ResultT, kSourceExtentBytes>{ptr, count};
63
64 _PW_SPAN_ASSERT(IsAlignedAs<ResultT>(result.data()));
65 _PW_SPAN_ASSERT(result.size_bytes() == bytes.size_bytes());
66
67 return result;
68}
69
70// TODO: https://pwbug.dev/396493663 - Doxygen thinks this is the same function
71// as the non-const version above, and merges the docs together.
72
93template <class ResultT, size_t kSourceExtentBytes>
94internal::SpanFromBytes<const ResultT, kSourceExtentBytes> span_cast(
95 span<const std::byte, kSourceExtentBytes> bytes) {
96 static_assert(sizeof(ResultT) == 1);
97
98 const ResultT* const ptr = reinterpret_cast<const ResultT*>(bytes.data());
99 const size_t count = bytes.size() / sizeof(ResultT);
100
101 auto result =
102 internal::SpanFromBytes<const ResultT, kSourceExtentBytes>{ptr, count};
103
104 _PW_SPAN_ASSERT(IsAlignedAs<const ResultT>(result.data()));
105 _PW_SPAN_ASSERT(result.size_bytes() == bytes.size_bytes());
106
107 return result;
108}
109
111
112} // namespace pw
internal::SpanFromBytes< ResultT, kSourceExtentBytes > span_cast(span< std::byte, kSourceExtentBytes > bytes)
Definition: cast.h:54
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27