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

feature: replaced *bytes.Buffer with io.Writer #134

Merged
merged 1 commit into from
Aug 9, 2024

Conversation

Freebien
Copy link
Contributor

@Freebien Freebien commented Aug 9, 2024

replaced *bytes.Buffer with io.Writer to be able to use any kind of buffers.

I needed to compute a hash as I downloaded the file and for that I needed to implement use an io.Writer instead of a *bytes.Buffer.

Here is an example of the usage afterwards

type HashWriter struct {
	w io.Writer
	h hash.Hash
}

func NewHashWriter(w io.Writer, h hash.Hash) *HashWriter {
	return &HashWriter{
		w: w,
		h: h,
	}
}

func (hw *HashWriter) Read(b []byte) (int, error) {
	return hw.Read(b)
}

func (hw *HashWriter) Write(b []byte) (int, error) {
	_, err := hw.h.Write(b)
	if err != nil {
		return 0, fmt.Errorf("writing hash: %w", err)
	}
	return hw.w.Write(b)
}

func (hw *HashWriter) Sum(b []byte) []byte {
	return hw.h.Sum(b)
}

func (hw *HashWriter) String() string {
	return fmt.Sprintf("%x", hw.h.Sum(nil))
}

func Download(client *telegram.Client, m *telegram.DocumentObj) (io.Reader, error) {
	_, dcid, _, _, err := telegram.GetFileLocation(m)
	if err != nil {
		return nil, fmt.Errorf("got error getting file info: %w", err)
	}
	buf := &bytes.Buffer{}
	hw := NewHashWriter(buf, sha256.New())
	_, err = client.DownloadMedia(m, &telegram.DownloadOptions{Buffer: hw, DCId: dcid})
	if err != nil {
		return nil, fmt.Errorf("got error getting file: %w", err)
	}
	return hw, fmt.Errorf("got error getting file: %w", err)
}

@AmarnathCJD
Copy link
Owner

ANy issues detected?

@AmarnathCJD AmarnathCJD merged commit bbf698e into AmarnathCJD:master Aug 9, 2024
3 checks passed
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 this pull request may close these issues.

2 participants