21
21
22
22
_LIBCPP_BEGIN_NAMESPACE_STD
23
23
24
- // __for_each_n_segment is a utility function for optimizing iterating over segmented iterators linearly.
25
- // __first and __orig_n are represent the begining and size of a segmented range. __func is expected to
26
- // take a range of local iterators. Anything that is returned from __func is ignored.
24
+ // __for_each_n_segment optimizes linear iteration over segmented iterators. It processes a segmented
25
+ // input range defined by (__first, __orig_n), where __first is the starting segmented iterator and
26
+ // __orig_n is the number of elements to process. The functor __func is applied to each segment using
27
+ // local iterator pairs for that segment. The return value of __func is ignored, and the function
28
+ // returns an iterator pointing to one past the last processed element in the input range.
27
29
28
30
template <class _SegmentedIterator , class _Size , class _Functor >
29
31
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _SegmentedIterator
@@ -40,32 +42,33 @@ __for_each_n_segment(_SegmentedIterator __first, _Size __orig_n, _Functor __func
40
42
auto __lfirst = _Traits::__local (__first);
41
43
auto __seg_size = static_cast <_IntegralSize>(std::distance (__lfirst, __slast));
42
44
43
- // We have only one single segment, which might not start or end at the boundaries of the segment
45
+ // Single-segment case: input range fits within a single segment (may not align with segment boundaries)
44
46
if (__n <= __seg_size) {
45
47
auto __llast = std::next (__lfirst, __n);
46
48
__func (__lfirst, __llast);
47
49
return _Traits::__compose (__seg, __llast);
48
50
}
49
51
50
- // We have more than one segment. Iterate over the first segment which might not start at the beginning
51
- __func (__lfirst, std::next (__lfirst, __seg_size));
52
+ // Multi-segment case: input range spans multiple segments.
53
+ // Process the first segment which might not start at the beginning of the segment
54
+ __func (__lfirst, __slast);
52
55
++__seg;
53
56
__n -= __seg_size;
54
57
55
- // Iterate over the 2nd to last segments which are guaranteed to start at the beginning of each segment
58
+ // Process the 2nd to last segments guaranteed to start at the beginning of each segment
56
59
while (true ) {
57
60
__sfirst = _Traits::__begin (__seg);
58
61
__slast = _Traits::__end (__seg);
59
62
__seg_size = std::distance (__sfirst, __slast);
60
63
61
- // We are in the last segment
64
+ // The last (potentially partial) segment
62
65
if (__n <= __seg_size) {
63
66
auto __llast = std::next (__sfirst, __n);
64
67
__func (__sfirst, __llast);
65
68
return _Traits::__compose (__seg, __llast);
66
69
}
67
70
68
- // We are in middle segments that are completely in the range
71
+ // Middle whole segments that are completely in the range
69
72
__func (__sfirst, __slast);
70
73
++__seg;
71
74
__n -= __seg_size;
0 commit comments