You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.7 KiB

; Common utility functions.
(in-package :nea/utils)
(defun split-string-at (str pos &optional (consume-value-at-pos-p nil))
"Splits STR at POS, returning two values. If CONSUME-VALUE-AT-POS-P is truthy, throws away the character at POS."
(declare (type string str) (type fixnum pos))
((> pos (length str)) (error "Position is outside string."))
((eql pos (length str)) (values str ""))
(t (values (subseq str 0 pos) (subseq str (+ pos (if consume-value-at-pos-p 1 0)))))))
(defun split-string-at-first (str char &optional (consume-value-at-pos-p nil) (from-end nil))
"Splits STR at the first instance of CHAR, otherwise behaving like SPLIT-STRING-AT. If no CHAR is found, returns the input string and an empty string."
(declare (type string str) (type character char))
(let ((pos (position char str
:from-end from-end)))
(if pos
(split-string-at str pos consume-value-at-pos-p)
(values str ""))))
(defun starts-with (thing seq)
"Returns T if SEQ starts with THING."
(if (and seq (> (length seq) 0))
(eql (elt seq 0) thing)
(defun string-empty-p (str)
"Returns T if str is of length 0 or is NIL, NIL otherwise."
(if str
(eql (length str) 0)
(defun strip-ws (str)
"Strips leading and trailing whitespace from STR."
(string-trim '(#\Space #\Tab #\Return #\Linefeed) str))
(defun join-by-spaces (arr)
"Joins ARR with spaces, returning the result as a string."
(format nil "~{~A~^ ~}" arr))
(defmacro if-nil (form &rest body)
"If FORM is NIL, evaluates BODY; otherwise, returns FORM."
(let ((ret (gensym)))
`(let ((,ret ,form))
(if ,ret
(progn ,@body)))))