• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* str.c -- strings to be used in the CoAP library
2  *
3  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #include "coap_internal.h"
10 
11 #include <stdio.h>
12 
coap_new_string(size_t size)13 coap_string_t *coap_new_string(size_t size) {
14   coap_string_t *s =
15             (coap_string_t *)coap_malloc_type(COAP_STRING, sizeof(coap_string_t) + size + 1);
16   if ( !s ) {
17     coap_log(LOG_CRIT, "coap_new_string: malloc: failed\n");
18     return NULL;
19   }
20 
21   memset(s, 0, sizeof(coap_string_t));
22   s->s = ((unsigned char *)s) + sizeof(coap_string_t);
23   s->s[size] = '\000';
24   return s;
25 }
26 
coap_delete_string(coap_string_t * s)27 void coap_delete_string(coap_string_t *s) {
28   coap_free_type(COAP_STRING, s);
29 }
30 
coap_new_str_const(const uint8_t * data,size_t size)31 coap_str_const_t *coap_new_str_const(const uint8_t *data, size_t size) {
32   coap_string_t *s = coap_new_string(size);
33   if (!s)
34     return NULL;
35   memcpy (s->s, data, size);
36   s->length = size;
37   return (coap_str_const_t *)s;
38 }
39 
coap_delete_str_const(coap_str_const_t * s)40 void coap_delete_str_const(coap_str_const_t *s) {
41   coap_free_type(COAP_STRING, s);
42 }
43 
coap_make_str_const(const char * string)44 coap_str_const_t *coap_make_str_const(const char *string)
45 {
46   static int ofs = 0;
47   static coap_str_const_t var[COAP_MAX_STR_CONST_FUNC];
48   if (++ofs == COAP_MAX_STR_CONST_FUNC) ofs = 0;
49   var[ofs].length = strlen(string);
50   var[ofs].s = (const uint8_t *)string;
51   return &var[ofs];
52 }
53 
54