Skip to content

Commit

Permalink
handle out-of-bounds writes nicely
Browse files Browse the repository at this point in the history
  • Loading branch information
stylewarning committed Feb 5, 2018
1 parent a52ba1b commit e5c9299
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 9 deletions.
41 changes: 34 additions & 7 deletions canvas.lisp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
;;;; canvas.lisp
;;;;
;;;; Copyright (c) 2013 Robert Smith
;;;; Copyright (c) 2013-2018 Robert Smith
;;;;
;;;; A simple notion of a "canvas" on which we can draw formulas.

Expand Down Expand Up @@ -28,10 +28,37 @@
"Obtain the character (X, Y) in the canvas CANVAS."
(aref (canvas-data canvas) y x))

(defvar *error-on-out-of-bounds-write* nil
"Error when attempting to write out of bounds on a canvas.")

(defvar *warn-on-out-of-bounds-write* t
"Warn when attempting to write out of bounds on a canvas.")

(defun canvas-set (canvas x y new-data)
"Set the character at (X, Y) in the canvas CANVAS to the value NEW-DATA."
(setf (aref (canvas-data canvas) y x)
new-data))
(destructuring-bind (width height) (canvas-dimensions canvas)
(cond
((and (<= 0 x (1- width))
(<= 0 y (1- height)))
(setf (aref (canvas-data canvas) y x)
new-data))
(t
(cond
(*error-on-out-of-bounds-write*
(cerror "Ignore write."
"Attempting to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas))
(*warn-on-out-of-bounds-write*
(warn "Attempted to write ~S out of bounds at ~
position (~D, ~D) for canvas ~A."
new-data
x
y
canvas)))))))

(defsetf canvas-ref canvas-set)

Expand All @@ -55,21 +82,21 @@
(terpri stream)
(destructuring-bind (width height)
(canvas-dimensions canvas)
(loop :initially (write-char #\+ stream)
(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
(write-char #\+ stream)
(terpri stream)))

(dotimes (y height)
(write-char #\| stream)
(dotimes (x width)
(write-char (canvas-ref canvas x y) stream))
(write-char #\| stream)
(terpri stream))
(loop :initially (write-char #\+ stream)

(loop :initially (write-char #\+ stream)
:repeat width
:do (write-char #\- stream)
:finally (progn
Expand Down
7 changes: 5 additions & 2 deletions package.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@

;; canvas.lisp
(:export
#:canvas
#:canvas ; TYPE/STRUCTURE
#:canvasp
#:make-canvas
#:canvas-dimensions
#:canvas-ref)
#:*error-on-out-of-bounds-write* ; VARIABLE
#:*warn-on-out-of-bounds-write* ; VARIABLE
#:canvas-ref ; FUNCTION, SETF
)

;; boxes.lisp
(:export
Expand Down

0 comments on commit e5c9299

Please sign in to comment.