From 7e83be82cb6d64ba35c6d7cfa4907b9e3aa1261c Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Wed, 21 Sep 2022 04:56:06 +0400 Subject: [PATCH] Calculate offset for ReadAt() instead of using Seek(). Fixed going out of bounds. --- internal/radio/icecast.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go index a2b28cb..ba3d205 100644 --- a/internal/radio/icecast.go +++ b/internal/radio/icecast.go @@ -119,7 +119,8 @@ func IcecastLastSong(playlistPath string) (Song, error) { func icecastLastPlayedSongs(playlistPath string, n int) ([]Song, error) { songs := make([]Song, n) - buf := make([]byte, bufferSize) + var buf []byte + var offset int64 = 0 playlist, err := os.Open(playlistPath) if err != nil { @@ -133,24 +134,29 @@ func icecastLastPlayedSongs(playlistPath string, n int) ([]Song, error) { return nil, nil } - playlist.Seek(-bufferSize, os.SEEK_END) + if playlist_stat.Size() < bufferSize { + buf = make([]byte, playlist_stat.Size()) + } else { + buf = make([]byte, bufferSize) + offset = playlist_stat.Size() - bufferSize + } - _, err = playlist.Read(buf) + _, err = playlist.ReadAt(buf, offset) if err != nil && err != io.EOF { return nil, err } lines := bytes.Split(buf, []byte("\n")) - if len(lines) < 2 { + if len(lines) < 3 { return nil, nil } - if len(lines) < n { - n = len(lines) - } + lines = lines[:len(lines)-2] - lines = lines[len(lines)-n-2 : len(lines)-2] + if len(lines) > n { + lines = lines[len(lines)-n:] + } for _, line := range lines { fields := bytes.Split(line, []byte("|"))