summaryrefslogtreecommitdiff
path: root/src/strings.lisp
blob: b11c31cc8f965dbbb5d49ed5518c9f3c704eb1f4 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
;; 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
   :ends-with
   :escape-xml
   :is-tg-whitespace-str
   :lisp->camel-case
   :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 ends-with (str suffix)
  (and (> (length str) (length suffix))
       (string= str suffix :start1 (- (length str) (length suffix)))))

(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->camel-case (str)
  (with-output-to-string (out)
    (let ((should-caps nil))
      (iter (for ch in-string str)
            (cond ((char= ch #\-)
                   (setf should-caps t))
                  (should-caps
                   (write-char (char-upcase ch) out)
                   (setf should-caps nil))
                  (t
                   (write-char (char-downcase ch) out)))))))

(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))))