blob: 00728f1fa83f28f7b0ab48235278e1158c4133d3 [file] [log] [blame]
Benny Prijono9033e312005-11-21 02:08:39 +00001/* $Id$ */
2/*
3 * Copyright (C)2003-2006 Benny Prijono <benny@prijono.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19#include <pj/string.h>
20#include <pj/pool.h>
21#include <pj/ctype.h>
22#include <pj/rand.h>
23#include <pj/os.h>
24
25#if PJ_FUNCTIONS_ARE_INLINED==0
26# include <pj/string_i.h>
27#endif
28
29
30PJ_DEF(pj_str_t*) pj_strltrim( pj_str_t *str )
31{
32 register char *p = str->ptr;
33 while (pj_isspace(*p))
34 ++p;
35 str->slen -= (p - str->ptr);
36 str->ptr = p;
37 return str;
38}
39
40PJ_DEF(pj_str_t*) pj_strrtrim( pj_str_t *str )
41{
42 char *end = str->ptr + str->slen;
43 register char *p = end - 1;
44 while (p >= str->ptr && pj_isspace(*p))
45 --p;
46 str->slen -= ((end - p) - 1);
47 return str;
48}
49
50PJ_DEF(char*) pj_create_random_string(char *str, pj_size_t len)
51{
52 unsigned i;
53 char *p = str;
54
55 PJ_CHECK_STACK();
56
57 for (i=0; i<len/8; ++i) {
58 unsigned val = pj_rand();
59 pj_val_to_hex_digit( (val & 0xFF000000) >> 24, p+0 );
60 pj_val_to_hex_digit( (val & 0x00FF0000) >> 16, p+2 );
61 pj_val_to_hex_digit( (val & 0x0000FF00) >> 8, p+4 );
62 pj_val_to_hex_digit( (val & 0x000000FF) >> 0, p+6 );
63 p += 8;
64 }
65 for (i=i * 8; i<len; ++i) {
66 *p++ = pj_hex_digits[ pj_rand() & 0x0F ];
67 }
68 return str;
69}
70
71
72PJ_DEF(unsigned long) pj_strtoul(const pj_str_t *str)
73{
74 unsigned long value;
75 unsigned i;
76
77 PJ_CHECK_STACK();
78
79 value = 0;
80 for (i=0; i<(unsigned)str->slen; ++i) {
81 value = value * 10 + (str->ptr[i] - '0');
82 }
83 return value;
84}
85
86PJ_DEF(int) pj_utoa(unsigned long val, char *buf)
87{
88 return pj_utoa_pad(val, buf, 0, 0);
89}
90
91PJ_DEF(int) pj_utoa_pad( unsigned long val, char *buf, int min_dig, int pad)
92{
93 char *p;
94 int len;
95
96 PJ_CHECK_STACK();
97
98 p = buf;
99 do {
100 unsigned long digval = (unsigned long) (val % 10);
101 val /= 10;
102 *p++ = (char) (digval + '0');
103 } while (val > 0);
104
105 len = p-buf;
106 while (len < min_dig) {
107 *p++ = (char)pad;
108 ++len;
109 }
110 *p-- = '\0';
111
112 do {
113 char temp = *p;
114 *p = *buf;
115 *buf = temp;
116 --p;
117 ++buf;
118 } while (buf < p);
119
120 return len;
121}
122
123