1 /*
2 * cook - file construction tool
3 * Copyright (C) 1997, 1998, 2006, 2007 Peter Miller;
4 * All rights reserved.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see
18 * <http://www.gnu.org/licenses/>.
19 */
20
21 #include <common/mem.h>
22 #include <common/str.h>
23 #include <common/sub/private.h>
24 #include <common/sub/zero_pad.h>
25 #include <common/trace.h>
26 #include <common/wstr_list.h>
27
28
29 wstring_ty *
sub_zero_pad(sub_context_ty * scp,wstring_list_ty * arg)30 sub_zero_pad(sub_context_ty *scp, wstring_list_ty *arg)
31 {
32 wstring_ty *result;
33 string_ty *s;
34 size_t n;
35
36 trace(("sub_zero_pad()\n{\n"));
37 if (arg->nitems != 3)
38 {
39 sub_context_error_set(scp, i18n("requires two arguments"));
40 trace(("return NULL;\n"));
41 trace(("}\n"));
42 return 0;
43 }
44 s = wstr_to_str(arg->item[2]);
45 n = atol(s->str_text);
46 trace(("n = %ld;\n", n));
47 str_free(s);
48
49 if (n <= arg->item[1]->wstr_length)
50 result = wstr_copy(arg->item[1]);
51 else
52 {
53 size_t len;
54 char *buffer;
55 string_ty *s2;
56 size_t j;
57
58 len = n - arg->item[1]->wstr_length;
59 s = wstr_to_str(arg->item[1]);
60 buffer = mem_alloc(len + 1);
61 for (j = 0; j < len; ++j)
62 buffer[j] = '0';
63 buffer[len] = 0;
64 s2 = str_format("%s%s", buffer, s->str_text);
65 trace(("result = \"%s\";\n", s2->str_text));
66 mem_free(buffer);
67 str_free(s);
68 result = str_to_wstr(s2);
69 str_free(s2);
70 }
71 trace(("return %8.8lX;\n", (long)result));
72 trace(("}\n"));
73 return result;
74 }
75