OpenCBM
libstring.c
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version
5  * 2 of the License, or (at your option) any later version.
6  *
7  * Copyright 2007,2008 Spiro Trikaliotis
8  *
9 */
10 
19 #include "arch.h"
20 
21 #include <stdlib.h>
22 
40 char *
41 cbmlibmisc_stralloc(unsigned int Length)
42 {
43  char * buffer = NULL;
44 
45  do {
46  buffer = malloc(Length + 1);
47 
48  if (buffer == NULL) {
49  break;
50  }
51 
52  /* make sure the string is empty, and that the byte after
53  * the "usable" space is an end marker, too.
54  */
55  buffer[0] = 0;
56  buffer[Length] = 0;
57 
58  } while (0);
59 
60  return buffer;
61 }
62 
83 char *
84 cbmlibmisc_strdup(const char * const OldString)
85 {
86  const char * oldString = "";
87  char * newString = NULL;
88  int len;
89 
90  if (OldString) {
91  oldString = OldString;
92  }
93 
94  len = strlen(oldString) + 1;
95 
96  newString = malloc(len);
97 
98  if (newString) {
99  memcpy(newString, oldString, len);
100  }
101  return newString;
102 }
103 
135 char *
136 cbmlibmisc_strndup(const char * const OldString, size_t Length)
137 {
138  char * newString = NULL;
139 
140  if (OldString)
141  {
142  size_t len = strlen(OldString);
143 
144  len = len < Length ? len : Length;
145 
146  newString = malloc(len + 1);
147 
148  if (newString)
149  {
150  memcpy(newString, OldString, len);
151  newString[len] = 0;
152  }
153  }
154  else
155  {
156  newString = cbmlibmisc_strdup(NULL);
157  }
158 
159  return newString;
160 }
161 
171 void
172 cbmlibmisc_strfree(const char * String)
173 {
174  void * p = (void *) String;
175 
176  if (String) {
177  free(p);
178  }
179 }
180 
201 char *
202 cbmlibmisc_strcat(const char * First, const char * Second)
203 {
204  char * ret = NULL;
205  const char * string1 = "";
206  const char * string2 = "";
207 
208  do {
209  if (First) {
210  string1 = First;
211  }
212 
213  if (Second) {
214  string2 = Second;
215  }
216 
217  ret = malloc(strlen(string1) + strlen(string2) + 1);
218 
219  if (ret == NULL)
220  break;
221 
222  strcpy(ret, string1);
223  strcat(ret, string2);
224 
225  } while(0);
226 
227  return ret;
228 }
char * cbmlibmisc_strdup(const char *const OldString)
Duplicate a given string.
Definition: libstring.c:84
void cbmlibmisc_strfree(const char *String)
Free a string.
Definition: libstring.c:172
char * cbmlibmisc_stralloc(unsigned int Length)
allocate memory for a string of a given size
Definition: libstring.c:41
char * cbmlibmisc_strcat(const char *First, const char *Second)
Concatenate two strings.
Definition: libstring.c:202
char * cbmlibmisc_strndup(const char *const OldString, size_t Length)
Duplicate a prefix of a given string.
Definition: libstring.c:136
Define makros and functions which account for differences between the different architectures.