Tannic
A C++ Tensor Library
Loading...
Searching...
No Matches
indexing.hpp
Go to the documentation of this file.
1// Copyright 2025 Eric Hermosis
2//
3// This file is part of the Tannic Tensor Library.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
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, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16//
17
18#ifndef INDEXING_HPP
19#define INDEXING_HPP
20
33#include <cassert>
34#include "concepts.hpp"
35#include "exceptions.hpp"
36
38
56struct Range {
57 int start = 0;
58 int stop = -1;
59};
60
86template<Integral Index, Integral Size>
87constexpr inline Index normalize(Index index, Size bound) {
88 if (index < 0) index += bound;
89 if (index < 0 | index > bound)
90 throw Exception("Index out of bounds");
91 return index;
92}
93
120template<Integral Size>
121constexpr inline Range normalize(Range range, Size size) {
122 int start = range.start < 0 ? size + range.start : range.start;
123 int stop = range.stop < 0 ? size + range.stop + 1 : range.stop;
124
125 if (start < 0 | start > size | stop < 0 | stop > size)
126 throw Exception("Range out of bounds");
127 return {start, stop};
128}
129
130} namespace tannic {
131
140
141}
142
143#endif // INDEXING_H
A simple generic exception type for the Tannic Tensor Library.
Definition: exceptions.hpp:44
Definition: indexing.hpp:37
constexpr Index normalize(Index index, Size bound)
Normalize a possibly-negative index into the valid range [0, bound).
Definition: indexing.hpp:87
Definition: buffer.hpp:41
Represents a half-open interval [start, stop) for slicing.
Definition: indexing.hpp:56
int start
Definition: indexing.hpp:57
int stop
Definition: indexing.hpp:58