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

Potential bug in Stream.Size() #26

Open
chavacava opened this issue Jan 17, 2021 · 2 comments
Open

Potential bug in Stream.Size() #26

chavacava opened this issue Jan 17, 2021 · 2 comments

Comments

@chavacava
Copy link

The current implementation of Stream.Size() is:

// Size returns the number of bytes of the stream.
func (k *Stream) Size() (int64, error) {
	// Go has no internal ReadSeeker function to get current ReadSeeker size,
	// thus we use the following trick.
	// Remember our current position
	curPos, err := k.Pos()
	if err != nil {
		return 0, err
	}
	// Seek to the end of the File object
	_, err = k.Seek(0, io.SeekEnd)
	if err != nil {
		return 0, err
	}
	// Remember position, which is equal to the full length
	fullSize, err := k.Pos()
	if err != nil {
		return fullSize, err
	}
	// Seek back to the current position
	_, err = k.Seek(curPos, io.SeekStart)
	return fullSize, err
}

It seems that if the assignment fullSize, err := k.Pos() returns an error the current position pointer is never set to its original value.

A potential mitigation of the problem could be:

// Size returns the number of bytes of the stream.
func (k *Stream) Size() (int64, error) {
	// Go has no internal ReadSeeker function to get current ReadSeeker size,
	// thus we use the following trick.
	// Remember our current position
	curPos, err := k.Pos()
	if err != nil {
		return 0, err
	}

        // Deferred seek back to the current position
	defer k.Seek(curPos, io.SeekStart)

	// Seek to the end of the File object
	_, err = k.Seek(0, io.SeekEnd)
	if err != nil {
		return 0, err
	}

	// return position, which is equal to the full length
	return k.Pos()
}
@generalmimon
Copy link
Member

@chavacava Good catch! Can you please open a pull request with the fix?

@chavacava chavacava mentioned this issue Jan 19, 2021
@chavacava
Copy link
Author

@generalmimon please check PR #27

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 a pull request may close this issue.

2 participants