# f_subptr — borrowed array views

### *function*  f_subptr_module/f_subptr(ptr, n, from, lbound, shape, region, size)

Return a rank-one pointer into existing contiguous storage, without copying
or allocating payload. Available through `use futile` or
`use f_subptr_module, only: f_subptr`.

## Synopsis

Use the source as the first positional argument and keyword window controls.
Legacy positional forms differ between overloads.

```fortran
flat => f_subptr(source)
flat => f_subptr(source, from=offset, n=count)
flat => f_subptr(source, shape=extents)
flat => f_subptr(source, region=first.to.last)
```

## Arguments

| Argument   | Type / default                                  | Meaning                                                                                                                                                                                                                                                                                    |
|------------|-------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ptr`      | Intrinsic array, rank 1–7; required             | Persistent contiguous `TARGET` or `POINTER` of a supported<br/>`f_precisions` ABI kind. Numeric, logical, complex and character families<br/>are supported. Its original lower bounds do not affect window offsets.                                                                        |
| `ptr_addr` | Intrinsic scalar; alternative source            | Legacy scalar-source keyword, not a numeric address. The scalar is the beginning of a raw<br/>contiguous buffer. An explicit window is required; the caller guarantees<br/>backing capacity and lifetime. A scalar string counts as one string<br/>element, not its individual characters. |
| `n`        | Integer scalar; optional                        | Nonnegative number of source elements. For array sources, omission of<br/>all window selectors selects the complete array or the suffix at `from`.                                                                                                                                         |
| `size`     | Integer scalar; optional                        | Legacy spelling of `n`. Do not supply both.                                                                                                                                                                                                                                                |
| `shape`    | Integer vector, zero to seven extents; optional | Selects the product of nonnegative extents. The result still has rank<br/>one. A zero extent gives an explicit empty window; a zero-length vector<br/>has product one. Shape multiplication is checked in `f_size_t`.                                                                      |
| `from`     | Integer scalar; default 1                       | One-based element offset in the flattened source, in Fortran<br/>array-element order. Must be positive. Cannot accompany `region`.                                                                                                                                                         |
| `lbound`   | Integer scalar; default 1                       | Lower bound of the rank-one result. Does not change source selection.                                                                                                                                                                                                                      |
| `region`   | `type(array_bounds)`; optional                  | Inclusive first/last element offsets, constructed with `first.to.last`.<br/>The `.to.` operator is exported by `futile`. Reversed endpoints give<br/>an explicit empty window.                                                                                                             |

Integer controls accept `f_integer` and `f_size_t`, including supported
mixed-kind combinations. `n`, `size`, `shape` and `region` are mutually
exclusive selectors. Prefer keywords rather than relying on legacy positional
ordering.

## Result and ownership

The result has the source’s intrinsic type and kind; character views preserve
its element length. For an array with no explicit selector the extent is the
remaining flattened element count. Otherwise it is the selected count.

Writes through the result modify the owner. The owner must outlive every view;
do not pass temporary expressions. Never `deallocate` or `f_free` a view.
Nullify aliases before freeing their owner. Noncontiguous array sections are
rejected rather than packed into temporary storage.

## Empty windows

| Request                                                            | Pointer result                                             |
|--------------------------------------------------------------------|------------------------------------------------------------|
| Explicit zero `n` or `size`, zero shape product, or empty `region` | Disassociated (null), including for a scalar buffer start. |
| Whole empty array with no explicit selector                        | Associated zero-size rank-one view; owns no allocation.    |
| `shape` with no entries                                            | One element, because the product of zero factors is one.   |

An associated zero-size view is a valid array argument, including for
`f_memcpy`. A null pointer must not be passed as an ordinary assumed-shape
array argument or used as a pointer bounds-remapping target. Do not query an
empty view’s first or last element address. For zero-size sections of nonempty
parents, contiguity can be processor dependent; whole empty arrays are supported.

## Multidimensional views

Native pointer bounds remapping gives a borrowed view its desired result rank.
`shape=` validates the selected element count; the bounds on the left of
`=>` determine the rank and extents. Match those extents to the selected count.
Use lower and upper bounds on every result dimension. The result follows
Fortran array-element order and neither allocates nor copies data.

```fortran
  subroutine check_nonempty()
    integer(f_integer), pointer :: owner(:),table(:,:)
    integer :: i
    owner=f_malloc_ptr(12,id='remap_owner')
    owner=[(i,i=1,12)]
    ! SHAPE selects six elements; the left-hand bounds give the result its rank.
    table(1:2,1:3)=>f_subptr(owner,from=3,shape=[2,3])
    if (any(shape(table)/=[2,3])) error stop 'nonempty shape'
    if (f_loc(table(1,1))/=f_loc(owner(3))) error stop 'first address'
    if (f_loc(table(2,3))/=f_loc(owner(8))) error stop 'last address'
    table(2,3)=-7
    if (owner(8)/=-7) error stop 'view write did not reach owner'
    nullify(table)
    call f_free_ptr(owner)
  end subroutine
```

For an explicit window that may be empty, first obtain the flat pointer and
check `associated`. This guard must precede remapping, even when the requested
multidimensional shape also has zero total size.

This is a language requirement, not a compiler workaround: bounds remapping
requires an associated, defined pointer target. See the pointer-assignment
rules in the [WG5 working draft N2014](https://wg5-fortran.org/N2001-N2050/N2014.pdf).

```fortran
  subroutine example_guarded_remap()
    integer(f_integer), pointer :: owner(:),flat(:),table(:,:)
    integer :: rows
    owner=f_malloc0_ptr(6,id='guarded_owner')
    do rows=0,2,2
      flat=>f_subptr(owner,shape=[rows,3])
      ! Never use a disassociated pointer as a bounds-remapping target.
      if (associated(flat)) then
        table(1:rows,1:3)=>flat
      else
        nullify(table)
      end if
      if (rows==0) then
        if (associated(table)) error stop 'explicit empty view must be null'
      else
        table(2,3)=9
        if (owner(6)/=9) error stop 'guarded view write'
      end if
      nullify(table,flat)
    end do
    call f_free_ptr(owner)
  end subroutine
```

If an associated empty multidimensional view is wanted, take the implicit whole
view of an actual empty array and remap that associated pointer instead.

```fortran
  subroutine example_empty_remap()
    integer(f_integer), pointer :: owner(:),flat(:),table(:,:),destination(:,:)
    owner=f_malloc_ptr(0,id='empty_owner')
    flat=>f_subptr(owner)
    if (.not.associated(flat)) error stop 'implicit empty view is associated'
    table(1:0,1:3)=>flat
    if (.not.associated(table)) error stop 'remapped empty view is associated'
    if (any(shape(table)/=[0,3])) error stop 'empty result shape'
    destination=f_malloc_ptr([0,3],id='empty_copy_destination')
    ! Associated zero-size views are valid array arguments; no payload is read.
    call f_memcpy(src=table,dest=destination)
    nullify(table,flat)
    call f_free_ptr(destination)
    call f_free_ptr(owner)
  end subroutine
```

## Errors

Invalid selectors, negative sizes/extents, invalid offsets, capacity violations,
overflow and noncontiguous nonempty sources raise `ERR_INVALID_MALLOC`.
The result is null when the error is caught. Inspect the Futile error status;
a null pointer alone does not distinguish an error from a valid explicit empty
window. Raw scalar-source capacities remain the caller’s responsibility.

## Examples and related APIs

The original flattening/copy example also covers nondefault owner bounds:

```fortran
  p=>f_subptr(a)
  if (.not.associated(p)) error stop 'whole view'
  if (f_loc(p(1))/=f_loc(a(-2,4))) error stop 'implicit source lower bounds'
  p=>f_subptr(a,size=2_f_size_t,from=2_f_integer,lbound=-1_f_integer)
  p(-1)=123.0_f_double
  if(a(-1,4)/=123.0_f_double)error stop 'mixed count kinds or shallow alias'
  p=>f_subptr(a,2_f_size_t,2_f_size_t,-3_f_size_t)
  if(lbound(p,1)/=-3.or.f_size(p)/=2)error stop 'legacy wide positional call'
  q=>f_subptr(a)
  r=>f_subptr(out)
  call f_memcpy(src=q,dest=r)
  if(any(out/=reshape(a,[6])))error stop 'copy between shallow flat views'
  nullify(p,q,r)
```

See [f_subptr_str — character-unit views](f_subptr_str.md) for character-unit and C-string views, and
[Memory handling](memory.md) for allocation, raw copying and size inquiries.

## Deprecated f_subptr2

`f_subptr2` remains a compatibility interface for default-integer rank-one
sources and rank-two results. It is deprecated in favor of `f_subptr` plus
native bounds remapping. New code should use the checked pattern above;
liborbs’ packed compression tables now use it. No runtime warning is emitted.
This deprecation does not add empty-window guarantees to the legacy helper.
