Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2026 Project CHIP Authors
4 : * All rights reserved.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 : #pragma once
19 :
20 : #include <lib/support/Span.h>
21 :
22 : namespace chip {
23 :
24 : /// Provides the ability to split a given span into spans of or below a given size
25 : template <size_t kSize>
26 : class ChunkSplitter
27 : {
28 : public:
29 4 : ChunkSplitter(CharSpan s) : span(s) {}
30 :
31 : /// Returns the next character span
32 : ///
33 : /// out - contains the next span of size at most kSize or an empty span if no more elements are available
34 : ///
35 : /// Returns true if an element is available, false otherwise.
36 14 : bool Next(CharSpan & out)
37 : {
38 14 : if (offset >= span.size())
39 : {
40 7 : out = CharSpan();
41 7 : return false; // nothing left
42 : }
43 : else
44 : {
45 7 : size_t nextSize = std::min(kSize, span.size() - offset);
46 7 : out = span.SubSpan(offset, nextSize);
47 7 : offset += nextSize;
48 7 : return true;
49 : }
50 : }
51 :
52 : protected:
53 : const CharSpan span; // the full span to split
54 : size_t offset = 0; // the start of the next chunk to return
55 : };
56 :
57 : } // namespace chip
|