root/openpgpsdk/trunk/src/memory.c

Revision 250 (checked in by ben, 8 years ago)

Add more checking, fix fallout from that.

Line 
1 /** \file
2  */
3
4 #include <openpgpsdk/create.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <assert.h>
8
9 void ops_memory_init(ops_memory_t *mem,size_t initial_size)
10     {
11     mem->length=0;
12     if(mem->buf)
13         {
14         if(mem->allocated < initial_size)
15             {
16             mem->buf=realloc(mem->buf,initial_size);
17             mem->allocated=initial_size;
18             }
19         return;
20         }
21     mem->buf=malloc(initial_size);
22     mem->allocated=initial_size;
23     }
24
25 void ops_memory_pad(ops_memory_t *mem,size_t length)
26     {
27     assert(mem->allocated >= mem->length);
28     if(mem->allocated < mem->length+length)
29         {
30         mem->allocated=mem->allocated*2+length;
31         mem->buf=realloc(mem->buf,mem->allocated);
32         }
33     assert(mem->allocated >= mem->length+length);
34     }
35
36 void ops_memory_add(ops_memory_t *mem,const unsigned char *src,size_t length)
37     {
38     ops_memory_pad(mem,length);
39     memcpy(mem->buf+mem->length,src,length);
40     mem->length+=length;
41     }
42
43 // XXX: this could be refactored via the writer, but an awful lot of
44 // hoops to jump through for 2 lines of code!
45 void ops_memory_place_int(ops_memory_t *mem,unsigned offset,unsigned n,
46                           size_t length)
47     {
48     assert(mem->allocated >= offset+length);
49    
50     while(length--)
51         mem->buf[offset++]=n >> (length*8);
52     }
53
54 void ops_memory_release(ops_memory_t *mem)
55     {
56     free(mem->buf);
57     mem->buf=NULL;
58     }
59
60 ops_writer_ret_t ops_writer_memory(const unsigned char *src,unsigned length,
61                                    ops_writer_flags_t flags,void *arg_)
62     {
63     ops_memory_t *mem=arg_;
64
65     OPS_USED(flags);
66     ops_memory_add(mem,src,length);
67     return OPS_W_OK;
68     }
69
70 void ops_memory_make_packet(ops_memory_t *out,ops_content_tag_t tag)
71     {
72     size_t extra;
73
74     if(out->length < 192)
75         extra=1;
76     else if(out->length < 8384)
77         extra=2;
78     else
79         extra=5;
80
81     ops_memory_pad(out,extra+1);
82     memmove(out->buf+extra+1,out->buf,out->length);
83
84     out->buf[0]=OPS_PTAG_ALWAYS_SET|OPS_PTAG_NEW_FORMAT|tag;
85
86     if(out->length < 192)
87         out->buf[1]=out->length;
88     else if(out->length < 8384)
89         {
90         out->buf[1]=((out->length-192) >> 8)+192;
91         out->buf[2]=out->length-192;
92         }
93     else
94         {
95         out->buf[1]=0xff;
96         out->buf[2]=out->length >> 24;
97         out->buf[3]=out->length >> 16;
98         out->buf[4]=out->length >> 8;
99         out->buf[5]=out->length;
100         }
101
102     out->length+=extra+1;
103     }
Note: See TracBrowser for help on using the browser.