C/C++ API Reference
Loading...
Searching...
No Matches
seek.h
1// Copyright 2021 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
15// Defines functions for implementing seeking in a stream.
16#pragma once
17
18#include <cstddef>
19
20#include "pw_stream/stream.h"
21
22namespace pw::stream {
23
25
26// Adds a seek offset to the specified origin.
27constexpr ptrdiff_t ResolveSeekOffset(ptrdiff_t offset,
28 Stream::Whence origin,
29 size_t end_position,
30 size_t current_position) {
31 switch (origin) {
33 return offset;
35 return static_cast<ptrdiff_t>(current_position) + offset;
36 case Stream::kEnd:
37 default:
38 return static_cast<ptrdiff_t>(end_position) + offset;
39 }
40}
41
42// Implements seek for a class that supports absolute position changes. The
43// new position is calculated and assigned to the provided position variable.
44//
45// Returns OUT_OF_RANGE for seeks to a negative position or past the end.
46constexpr Status CalculateSeek(ptrdiff_t offset,
47 Stream::Whence origin,
48 size_t end_position,
49 size_t& current_position) {
50 const ptrdiff_t new_position =
51 ResolveSeekOffset(offset, origin, end_position, current_position);
52
53 if (new_position < 0 || static_cast<size_t>(new_position) > end_position) {
54 return Status::OutOfRange();
55 }
56
57 current_position = static_cast<size_t>(new_position);
58 return OkStatus();
59}
60
62
63} // namespace pw::stream
static constexpr Status OutOfRange()
Operation attempted out of range; e.g. seeking past end of file.
Definition: status.h:172
Whence
Positions from which to seek.
Definition: stream.h:48
@ kCurrent
Definition: stream.h:58
@ kBeginning
Definition: stream.h:51
@ kEnd
Definition: stream.h:62
constexpr Status OkStatus()
Definition: status.h:297