Import Upstream version 20180207
[hcoop/debian/mlton.git] / lib / mlton / basic / string1.sml
CommitLineData
7f918cf1
CE
1(* Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
2 * Jagannathan, and Stephen Weeks.
3 *
4 * MLton is released under a BSD-style license.
5 * See the file MLton-LICENSE for details.
6 *)
7
8structure String1 =
9struct
10
11open String0
12
13structure F = Fold (type 'a t = string
14 type 'a elt = char
15 val fold = fold)
16open F
17
18type t = string
19
20val last = String0.last
21
22val layout = Layout.str
23
24fun forall (s, f) =
25 let
26 val n = length s
27 fun loop i =
28 i = n
29 orelse (f (sub (s, i)) andalso loop (i + 1))
30 in
31 loop 0
32 end
33
34(* This hash function is taken from pages 56-57 of
35 * The Practice of Programming by Kernighan and Pike.
36 *)
37fun hash (s: t): Word.t =
38 fold (s, 0w0, fn (c, h) => Word.fromChar c + Word.* (h, 0w31))
39
40fun peek (v, f) =
41 let
42 val n = length v
43 fun loop i =
44 if i = n
45 then NONE
46 else let
47 val x = sub (v, i)
48 in
49 if f x
50 then SOME x
51 else loop (i + 1)
52 end
53 in
54 loop 0
55 end
56
57fun peeki (v, f) =
58 let
59 val n = length v
60 fun loop i =
61 if i = n
62 then NONE
63 else let
64 val x = sub (v, i)
65 in
66 if f (i, x)
67 then SOME (i, x)
68 else loop (i + 1)
69 end
70 in
71 loop 0
72 end
73
74fun dropl (s, p) =
75 case peeki (s, fn (_, c) => not (p c)) of
76 NONE => ""
77 | SOME (i, _) => extract (s, i, NONE)
78
79fun deleteSurroundingWhitespace (s: t): t =
80 let
81 val n = size s
82 fun loop (i: int) =
83 if PInt.>= (i, n)
84 then s
85 else
86 if Char.isSpace (sub (s, i))
87 then loop (i + 1)
88 else
89 let
90 fun loop (j: int) =
91 let
92 val c = sub (s, j)
93 in
94 if PInt.<= (j, i)
95 then fromChar c
96 else
97 if Char.isSpace c
98 then loop (j - 1)
99 else extract (s, i, SOME (j - i + 1))
100 end
101 in
102 loop (n - 1)
103 end
104 in loop 0
105 end
106
107end