Enhance slice functionality: support reverse slicing and edge cases #2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Enhances
tofu_tensor_arange()andtofu_tensor_rearange()to support full NumPy-compatible slicing including reverse slicing with negative steps and proper handling of edge cases. This resolves TODOs atsrc/tofu_tensor.c:161andsrc/tofu_tensor.c:191.Problem
Previous implementation had two limitations:
Assertion
stop > startprevented:arange(10, 0, -1)should produce[10, 9, ..., 1]arange(5, 5, 1)should return NULLLength calculation
ceil((stop - start) / step)only worked for positive stepsSolution
Enhanced length calculation:
This correctly handles:
start < stopfor non-empty resultstart > stopfor non-empty resultarange(0, 10, -1))Both functions updated:
tofu_tensor_arange()- Allocates and returns new tensortofu_tensor_rearange()- In-place fill of existing tensorTesting
New Test Suite
Created
test/standalone/test_arange_enhanced.cwith 6 comprehensive test categories:Forward Slicing (3 tests)
arange(0, 5, 1)→[0, 1, 2, 3, 4]arange(1, 10, 2)→[1, 3, 5, 7, 9]arange(0.5, 3.5, 0.5)→[0.5, 1.0, ..., 3.0]Reverse Slicing (4 tests)
arange(10, 0, -1)→[10, 9, 8, ..., 1]arange(5, -1, -1)→[5, 4, 3, 2, 1, 0]arange(10, 0, -2)→[10, 8, 6, 4, 2]arange(3.0, 0.0, -0.5)→[3.0, 2.5, ..., 0.5]Empty Arrays (3 tests)
arange(5, 5, 1)→ NULLarange(0, 0, 1)→ NULLarange(5, 5, -1)→ NULLIncompatible Step Direction (3 tests)
arange(0, 10, -1)→ NULLarange(10, 0, 1)→ NULLarange(5, 2, 0.5)→ NULLIn-place Rearange (3 tests)
Data Types (2 tests)
Results: All 6 test categories pass
Existing Tests
Impact
Resolves
Part of v1.1.0 roadmap - Priority 2 (P2) feature enhancement
src/tofu_tensor.c:161src/tofu_tensor.c:191