1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <tinycbor/cbor.h>
21 #include <tinycbor/cbor_buf_writer.h>
22 
23 static inline int
would_overflow(struct cbor_buf_writer * cb,size_t len)24 would_overflow(struct cbor_buf_writer *cb, size_t len)
25 {
26     ptrdiff_t remaining = (ptrdiff_t)cb->end;
27     remaining -= (ptrdiff_t)cb->ptr;
28     remaining -= (ptrdiff_t)len;
29     return (remaining < 0);
30 }
31 
32 int
cbor_buf_writer(struct cbor_encoder_writer * arg,const char * data,int len)33 cbor_buf_writer(struct cbor_encoder_writer *arg, const char *data, int len)
34 {
35     struct cbor_buf_writer *cb = (struct cbor_buf_writer *) arg;
36 
37     if (would_overflow(cb, len)) {
38         return CborErrorOutOfMemory;
39     }
40 
41     memcpy(cb->ptr, data, len);
42     cb->ptr += len;
43     cb->enc.bytes_written += len;
44     return CborNoError;
45 }
46 
47 void
cbor_buf_writer_init(struct cbor_buf_writer * cb,uint8_t * buffer,size_t size)48 cbor_buf_writer_init(struct cbor_buf_writer *cb, uint8_t *buffer, size_t size)
49 {
50     cb->ptr = buffer;
51     cb->end = buffer + size;
52     cb->enc.bytes_written = 0;
53     cb->enc.write = cbor_buf_writer;
54 }
55 
56 size_t
cbor_buf_writer_buffer_size(struct cbor_buf_writer * cb,const uint8_t * buffer)57 cbor_buf_writer_buffer_size(struct cbor_buf_writer *cb, const uint8_t *buffer)
58 {
59     return (size_t)(cb->ptr - buffer);
60 }
61