Skip to content

Add slice_to_unit() C API for single-element slice detection#209

Draft
Copilot wants to merge 5 commits into
masterfrom
copilot/slice-to-unit-function
Draft

Add slice_to_unit() C API for single-element slice detection#209
Copilot wants to merge 5 commits into
masterfrom
copilot/slice-to-unit-function

Conversation

Copilot AI commented Jun 26, 2026

Copy link
Copy Markdown

This PR adds a CPython-exposed utility that collapses unit slices (e.g., slice(3, 4), slice(0, 1)) to their integer index and returns -1 for all non-unit slices. The goal is to provide a fast, explicit primitive for callers that can substitute scalar indexing when a slice semantically selects exactly one positive-position element.

  • API surface

    • Added slice_to_unit() to the extension module method table.
    • Exported it through arraykit.__init__ and added typing in __init__.pyi:
      • def slice_to_unit(__slice: slice, /) -> int
  • Core C implementation

    • Implemented slice_to_unit(PyObject *a) in src/methods.c (declared in src/methods.h).
    • Behavior:
      • Accepts only slice objects (TypeError otherwise).
      • Requires stop to be present and integral.
      • Accepts start is None and treats it as 0.
      • Accepts step is None or step == 1; any other step returns -1.
      • Returns start only when start >= 0, stop >= 0, and stop - start == 1; otherwise returns -1.
  • Targeted coverage

    • Added focused tests in test/test_util.py for:
      • Positive matches: slice(3, 4), slice(0, 1), slice(None, 1)
      • Non-unit cases: width != 1, non-default step, missing stop, negative start
      • Type validation (TypeError on non-slice input)
from arraykit import slice_to_unit

slice_to_unit(slice(3, 4))      # 3
slice_to_unit(slice(0, 1))      # 0
slice_to_unit(slice(None, 1))   # 0
slice_to_unit(slice(0, 2))      # -1
slice_to_unit(slice(-1, 0))     # -1

Copilot AI changed the title [WIP] Implement slice_to_unit() function to determine unit slices Add slice_to_unit() C API for single-element slice detection Jun 26, 2026
Copilot AI requested a review from flexatone June 26, 2026 18:28
Comment thread src/methods.c Outdated
Comment thread src/methods.c Outdated
Copilot AI requested a review from flexatone June 26, 2026 18:42
@flexatone

Copy link
Copy Markdown
Contributor

@copilot instead of returning None for non unit slices, lets return -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants