summaryrefslogtreecommitdiff
path: root/src/strings.lisp
blob: 68289aaf3dceb2651dd7242d6dbae21d613321ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
;; SPDX-License-Identifier: EUPL-1.2
;; SPDX-FileCopyrightText: 2025 Uko Kokņevičs <perkontevs@gmail.com>
(defpackage :ukkoclot/strings
  (:use :c2cl :iterate)
  (:import-from :cl-unicode :general-category)
  (:export :escape-xml :is-tg-whitespace-str :lisp->snake-case :snake->lisp-case :starts-with :starts-with-ignore-case))
(in-package :ukkoclot/strings)

;; These are very inefficient but I don't care until I profile

(defun escape-xml (str &optional out)
  (if out
      (escape-xml% str out)
      (with-output-to-string (out)
        (escape-xml% str out))))

(defun escape-xml% (str out)
  (loop for ch across str do
    (case ch
      (#\< (write-string "&lt;" out))
      (#\> (write-string "&gt;" out))
      (#\& (write-string "&amp;" out))
      (#\" (write-string "&quot;" out))
      (t (write-char ch out)))))

(defun is-tg-whitespace (ch)
  (let ((gc (general-category ch)))
    (or (string= gc "Zs")               ; Separator, space
        (string= gc "Zl")               ; Separator, line
        (string= gc "Zp")               ; Separator, paragraph
        (string= gc "Cc")               ; Other, control
        (= (char-code ch) #x2800)     ; BRAILLE PATTERN BLANK
        )))

(defun is-tg-whitespace-str (str)
  (iter (for ch in-string str)
    (always (is-tg-whitespace ch))))

(defun lisp->snake-case (str)
  (with-output-to-string (out)
    (loop for ch across str do
      (case ch
        (#\- (write-char #\_ out))
        (t (write-char ch out))))))

(defun snake->lisp-case (str)
  (with-output-to-string (out)
    (loop for ch across str do
      (case ch
        (#\_ (write-char #\- out))
        (t (write-char ch out))))))

(defun starts-with (str prefix)
  (and (> (length str) (length prefix))
       (string= str prefix :end1 (length prefix))))

(defun starts-with-ignore-case (str prefix)
  (and (> (length str) (length prefix))
       (string-equal str prefix :end1 (length prefix))))