• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * String utility functions that need to be built as part of the firmware.
6  */
7 
8 #include "sysincludes.h"
9 
10 #include "utility.h"
11 
12 
Uint64ToString(char * buf,uint32_t bufsize,uint64_t value,uint32_t radix,uint32_t zero_pad_width)13 uint32_t Uint64ToString(char *buf, uint32_t bufsize, uint64_t value,
14 			uint32_t radix, uint32_t zero_pad_width)
15 {
16 	char ibuf[UINT64_TO_STRING_MAX];
17 	char *s;
18 	uint32_t usedsize = 1;
19 
20 	if (!buf)
21 		return 0;
22 
23 	/* Clear output buffer in case of error */
24 	*buf = '\0';
25 
26 	/* Sanity-check input args */
27 	if (radix < 2 || radix > 36 || zero_pad_width >= UINT64_TO_STRING_MAX)
28 		return 0;
29 
30 	/* Start at end of string and work backwards */
31 	s = ibuf + UINT64_TO_STRING_MAX - 1;
32 	*(s) = '\0';
33 	do {
34 		int v = value % radix;
35 		value /= radix;
36 
37 		*(--s) = (char)(v < 10 ? v + '0' : v + 'a' - 10);
38 		if (++usedsize > bufsize)
39 			return 0;  /* Result won't fit in buffer */
40 	} while (value);
41 
42 	/* Zero-pad if necessary */
43 	while (usedsize <= zero_pad_width) {
44 		*(--s) = '0';
45 		if (++usedsize > bufsize)
46 			return 0;  /* Result won't fit in buffer */
47 	}
48 
49 	/* Now copy the string back to the input buffer. */
50 	Memcpy(buf, s, usedsize);
51 
52 	/* Don't count the terminating null in the bytes used */
53 	return usedsize - 1;
54 }
55 
StrnAppend(char * dest,const char * src,uint32_t destlen)56 uint32_t StrnAppend(char *dest, const char *src, uint32_t destlen)
57 {
58 	uint32_t used = 0;
59 
60 	if (!dest || !src || !destlen)
61 		return 0;
62 
63 	/* Skip past existing string in destination.*/
64 	while (dest[used] && used < destlen - 1)
65 		used++;
66 
67 	/* Now copy source */
68 	while (*src && used < destlen - 1)
69 		dest[used++] = *src++;
70 
71 	/* Terminate destination and return count of non-null characters */
72 	dest[used] = 0;
73 	return used;
74 }
75