From d76ad44427cf7972cdc833d9aa3b92d2c8c357aa Mon Sep 17 00:00:00 2001 From: Ned Palacios Date: Wed, 20 Mar 2024 21:21:54 +0800 Subject: [PATCH] fix(server/rope): crash on nil insert --- server/types/rope.go | 4 ++-- server/types/rope_test.go | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/server/types/rope.go b/server/types/rope.go index f9babed..e096419 100644 --- a/server/types/rope.go +++ b/server/types/rope.go @@ -20,11 +20,11 @@ func NewRope(text string) *Rope { // Insert inserts text at the specified position in the rope. func (r *Rope) Insert(position int, text string) { - if position < 0 || position > len(r.text) { + if position < 0 || (r != nil && position > len(r.text)) { panic("Invalid position") } - if len(text) == 0 { + if r == nil || len(text) == 0 { return } diff --git a/server/types/rope_test.go b/server/types/rope_test.go index 3d11cc0..cbb420e 100644 --- a/server/types/rope_test.go +++ b/server/types/rope_test.go @@ -70,6 +70,12 @@ func TestRope(t *testing.T) { r.Insert(15, "Invalid Insert") }) + t.Run("Insert on Nil Rope", func(t *testing.T) { + var r *Rope = nil + + r.Insert(0, "Invalid Insert") + }) + t.Run("Invalid Delete", func(t *testing.T) { r := NewRope("Hello, World!")