allegro / bigcache

Efficient cache for gigabytes of data written in Go.
http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html
Apache License 2.0
7.45k stars 593 forks source link

Improve error handling in BytesQueue.Push function in queue.go #400

Open akanchha25 opened 1 month ago

akanchha25 commented 1 month ago

The Push function in BytesQueue currently uses a generic error message when the queue is full. It is suggested to use errFullQueue for a more descriptive error message.

Current Code:

var (
    errEmptyQueue       = &queueError{"Empty queue"}
    errInvalidIndex     = &queueError{"Index must be greater than zero. Invalid index."}
    errIndexOutOfBounds = &queueError{"Index out of range"}
)

Push function

if !q.canInsertAfterTail(neededSize) {
        if q.canInsertBeforeHead(neededSize) {
            q.tail = leftMarginIndex
        } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 {
            return -1, &queueError{"Full queue. Maximum size limit reached."}
        } else {
            q.allocateAdditionalMemory(neededSize)
        }
    }

Updated code

var (
    errEmptyQueue       = &queueError{"Queue is empty."}
    errInvalidIndex     = &queueError{"Index must be greater than zero. Invalid index."}
    errIndexOutOfBounds = &queueError{"Index out of range."}
    errFullQueue        = &queueError{"Queue is full. Maximum size limit reached."} 
)
if !q.canInsertAfterTail(neededSize) {
        if q.canInsertBeforeHead(neededSize)) {
            q.tail = leftMarginIndex
        } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 {
            return -1, errFullQueue 
        } else {
            q.allocateAdditionalMemory(neededSize)
        }
    }

This will improve the code quality

janisz commented 1 month ago

@akanchha25 Indeed it's a good improvement. Do you think errors should be unexpeorted? If we export them then they could be used to check for given error like with io.EOF

akanchha25 commented 1 month ago

@janisz That's a great point. Exporting the errors would indeed allow for more robust error handling, similar to checking for specific errors like io.EOF. This could be beneficial for users of the BytesQueue package to handle different error scenarios more explicitly.

I can update the code to export these error variables, making it easier for others to handle specific error conditions. I'll proceed with the changes if that sounds good to you.