Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optics fails on struct pointer type #63

Open
fogfish opened this issue Feb 2, 2025 · 0 comments
Open

optics fails on struct pointer type #63

fogfish opened this issue Feb 2, 2025 · 0 comments
Labels
[T] bug the bug report

Comments

@fogfish
Copy link
Owner

fogfish commented Feb 2, 2025

The following example causes the crash for library

package main

import (
	"fmt"

	"github.com/fogfish/golem/optics"
)

type Story struct {
	Text *string
}

func main() {
	l := optics.ForProduct1[*Story, *string]()
	s := &Story{}
	x := "xxx"

	l.Put(&s, &x)

	fmt.Printf("==> %+v\n", s)
	fmt.Printf("==> %v\n", s.Text)
	fmt.Printf("==> %s\n", *s.Text) // <= crash here
}

The reason is lens internals. It assume S is pure structure. As fix, the lens needs to know a metadata about S type.

func (lens *lens[S, A]) Put(s *S, a A) *S {
	*(*A)(unsafe.Pointer(uintptr(unsafe.Pointer(s)) + lens.Offset + lens.RootOffs)) = a
	return s
}

func (lens *lens[S, A]) Get(s *S) A {
	return *(*A)(unsafe.Pointer(uintptr(unsafe.Pointer(s)) + lens.Offset + lens.RootOffs))
}
@fogfish fogfish added the [T] bug the bug report label Feb 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[T] bug the bug report
Projects
None yet
Development

No branches or pull requests

1 participant