x/term: prevent invalid indexing into stRingBuffer

The exported method (*stRingBuffer).NthPreviousEntry does not correctly
handle arguments with negative values. A negative value will index
beyond slice boundaries in most cases (unless size = max = INT_MAX) and
cause an access violation at runtime.

This change adds a condition to return ok = false for all negatively
valued arguments, which is the same behavior that occurs with positively
valued arguments exceeding buffer length.

Adding the capability to index backwards (from the end of the slice)
does not seem like the intent of this method, and it would not improve
or simplify existing functionality. It would also be inconsistent with
the handling of positive values out-of-bounds.

Change-Id: Ib4113330f0044dd5b73c7d75c5cdcdd27d60ee77
GitHub-Last-Rev: fec355f53687dfbee962f611297355059efabd48
GitHub-Pull-Request: golang/term#8
Reviewed-on: https://go-review.googlesource.com/c/term/+/408754
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
diff --git a/terminal.go b/terminal.go
index 535ab82..4b48a58 100644
--- a/terminal.go
+++ b/terminal.go
@@ -935,7 +935,7 @@
 // next most recent, and so on. If such an element doesn't exist then ok is
 // false.
 func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
-	if n >= s.size {
+	if n < 0 || n >= s.size {
 		return "", false
 	index := s.head - n