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

Read value on a given offset and return pointer back. #8

Closed
Zekfad opened this issue Apr 3, 2024 · 2 comments
Closed

Read value on a given offset and return pointer back. #8

Zekfad opened this issue Apr 3, 2024 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@Zekfad
Copy link

Zekfad commented Apr 3, 2024

Hi, thank you for the great package!

It would be nice to have a flag for offset options to be able to restore offset after reading referenced chunk.

I have an archive structure that have sparsely referenced buffers. I'm using the following reader method:

type File struct {
	Offset uint64
	Size uint32
	
	InlineBuffer []byte `bin:"FileReadInlineBuffer"`
	// desired
	// InlineBuffer []byte `bin:"offsetStart:Offset, len:Size, restoreOffsetOrSomeBetterNameForThisFlag:true"`
}

func (file *File) FileReadInlineBuffer(r binstruct.Reader) error {
	oldPos, err := r.Seek(0, io.SeekCurrent)
	if err != nil {
		return err
	}

	_, err = r.Seek(int64(file.Offset), io.SeekStart)
	if err != nil {
		return err
	}

	size := int(file.Size)
	file.InlineBuffer = make([]byte, size)
	n, err := r.Read(file.InlineBuffer)
	if err != nil {
		return err
	}
	if n != size {
		return fmt.Errorf("failed to read inline buffer: expected %d bytes, got: %d", size, n)
	}

	_, err = r.Seek(oldPos, io.SeekStart)
	if err != nil {
		return err
	}
	return nil
}
@ghostiam ghostiam self-assigned this Apr 3, 2024
@ghostiam ghostiam added the enhancement New feature or request label Apr 3, 2024
@ghostiam
Copy link
Owner

ghostiam commented Apr 3, 2024

Hi, check out the new version.

func Test_OffsetRestore(t *testing.T) {
	var v struct {
		Offset uint8
		Size   uint8
		Data   []byte `bin:"offsetStart:Offset,len:Size,offsetRestore"`
		Other  []byte `bin:"len:3"`
	}

	err := UnmarshalBE([]byte{0x05, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05}, &v)
	require.NoError(t, err)
	require.Equal(t, uint8(5), v.Offset)
	require.Equal(t, uint8(2), v.Size)
	require.Equal(t, []byte{0x04, 0x05}, v.Data)
	require.Equal(t, []byte{0x01, 0x02, 0x03}, v.Other)
}

@Zekfad
Copy link
Author

Zekfad commented Apr 4, 2024

Thank you very much, works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants