From 8e4093b647d49c76759fe623618c4a0798f71871 Mon Sep 17 00:00:00 2001 From: Natercio Date: Tue, 11 Nov 2025 10:02:35 +0000 Subject: [PATCH] support nil receivers --- internal/record.go | 18 ++++++++++++------ internal/record_test.go | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/internal/record.go b/internal/record.go index 7fe70b2..dcbecce 100644 --- a/internal/record.go +++ b/internal/record.go @@ -18,22 +18,28 @@ type RecordQueue struct { l *list.List } +// Push inserts the Record at the back of the queue. If pushing a nil Record then it's a no-op. func (rq *RecordQueue) Push(r Record) { - if rq.l == nil { - rq.l = list.New() - } - if r == nil { return } + if rq == nil { + // This would cause a panic anyway so, we panic with a more meaningful message + panic("Push to nil RecordQueue") + } + + if rq.l == nil { + rq.l = list.New() + } + rq.l.PushBack(r) } // Pop removes and returns the first element of the list as the first return value. If the list is // empty returns falso on the 2nd return value, true otherwise. func (rq *RecordQueue) Pop() (Record, bool) { - if rq.l == nil { + if rq == nil || rq.l == nil { return nil, false } @@ -48,7 +54,7 @@ func (rq *RecordQueue) Pop() (Record, bool) { } func (rq *RecordQueue) Len() int { - if rq.l == nil { + if rq == nil || rq.l == nil { return 0 } diff --git a/internal/record_test.go b/internal/record_test.go index 2898abc..5d5c505 100644 --- a/internal/record_test.go +++ b/internal/record_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func TestRecordQueue_Push(t *testing.T) { +func TestRecordQueue(t *testing.T) { var recCount int newRecord := func() Record { recCount++ @@ -52,6 +52,37 @@ func TestRecordQueue_Push(t *testing.T) { } } +func TestRecordQueueNilReceiver(t *testing.T) { + var rq *RecordQueue + + if rq.Len() > 0 { + t.Fatalf("nil receiver should have zero lenght") + } + + _, ok := rq.Pop() + if ok { + t.Fatalf("Pop() on a nil receiver should return (_,false)") + } + + rq.Push(nil) + if rq.Len() != 0 { + t.Fatalf("Push(nil) on a nil receiver should be a no-op") + } + + defer func() { + r := recover() + if r == nil { + t.Fatalf("expected a panic but got nothing") + } + + expMsg := "Push to nil RecordQueue" + if msg, ok := r.(string); !ok || msg != expMsg { + t.Fatalf(`want panic message %q but got "%v"`, expMsg, r) + } + }() + rq.Push(testRecord{}) +} + type testRecord struct { Record