Logging in and logging out.
[cocanwiki.git] / scripts / cocanwiki_strings.ml
1 (* Basic string functions.
2  * Copyright (C) 2004 Merjis Ltd.
3  * Written By Richard W.M. Jones (rich@merjis.com)
4  * $Id: cocanwiki_strings.ml,v 1.1 2004/09/07 14:58:34 rich Exp $
5  *)
6
7 open ExtString
8
9 let string_contains substr str =
10   try String.find str substr; true
11   with String.Invalid_string -> false
12
13 let string_of_char = String.make 1
14
15 let truncate n str =
16   if String.length str < n then str else String.sub str 0 (n-1)
17
18 (* These versions only work in the C locale for 7-bit characters. *)
19 let isspace c =
20   c = ' '
21   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
22
23 let isalpha c =
24   c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
25
26 let isdigit c =
27   c >= '0' && c <= '9'
28
29 let isalnum c =
30   c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
31
32 let islower c =
33   c >= 'a' && c <= 'z'
34
35 let isupper c =
36   c >= 'A' && c <= 'Z'
37
38 let isxdigit c =
39   c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'
40
41 let triml ?(test = isspace) str =
42   let i = ref 0 in
43   let n = ref (String.length str) in
44   while !n > 0 && test str.[!i]; do
45     decr n;
46     incr i
47   done;
48   if !i = 0 then str
49   else String.sub str !i !n
50
51 let trimr ?(test = isspace) str =
52   let n = ref (String.length str) in
53   while !n > 0 && test str.[!n-1]; do
54     decr n
55   done;
56   if !n = String.length str then str
57   else String.sub str 0 !n
58
59 let trim ?(test = isspace) str =
60   trimr (triml str)
61
62 let string_for_all f str =
63   let len = String.length str in
64   let rec loop i =
65     if i = len then true
66     else (
67       let c = str.[i] in
68       if not (f c) then false
69       else loop (i+1)
70     )
71   in
72   loop 0
73
74 let string_exists f str =
75   let len = String.length str in
76   let rec loop i =
77     if i = len then false
78     else (
79       let c = str.[i] in
80       if f c then true
81       else loop (i+1)
82     )
83   in
84   loop 0
85
86 let string_is_whitespace = string_for_all isspace