Skip to content
This repository was archived by the owner on Apr 15, 2023. It is now read-only.
This repository was archived by the owner on Apr 15, 2023. It is now read-only.

How to wrap object fields #65

@planetis-m

Description

@planetis-m

Not everything needs to be wrapped, for example math objects are ok. Fields with naming like xCount need to be write protected. However object like Mesh hold collections that need to be wrapped in order to implement range checks for example.

First one is easy, remove export marker and write procs, as explained in the manual:

proc glyphCount*(x: Front): int32 = x.glyphCount

My solution for the last one is to return hidden pointers (this has the cost of introducing temporaries) and define array access operators on distinct types, one for each field:

type
  MaterialMaps* = distinct Material

template maps*(x: Material): MaterialMaps = MaterialMaps(x)

proc `[]`*(x: MaterialMaps, i: MaterialMapIndex): MaterialMap =
  # implement range checks here
  result = Material(x).maps[i]

proc `[]`*(x: var MaterialMaps, i: MaterialMapIndex): var MaterialMap =
  result = Material(x).maps[i]

proc `[]=`*(x: var MaterialMaps, i: MaterialMapIndex, val: MaterialMap) =
  Material(x).maps[i] = val

Tested and it works. Pros: Accidentally creating a copy: let x = x.maps is prevented by the compiler (no =copy defined for distincts), also the syntax remains the same. Cons: temporary pointer variables are introduced by the C back end.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions