Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / shell / streamer.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2019 Apache Software Foundation (ASF)
5  *
6  *    Licensed under the Apache License, Version 2.0 (the "License");
7  *    you may not use this file except in compliance with the License.
8  *    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, software
13  *    distributed under the License is distributed on an "AS IS" BASIS,
14  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *    See the License for the specific language governing permissions and
16  *    limitations under the License.
17  */
18
19 /**
20  *    @file
21  *      Source implementation for an input / output stream abstraction.
22  */
23
24 #include "streamer.h"
25
26 #include <limits.h>
27 #include <stdio.h>
28
29 #ifndef CONSOLE_DEFAULT_MAX_LINE
30 #define CONSOLE_DEFAULT_MAX_LINE 256
31 #endif
32
33 namespace chip {
34 namespace Shell {
35
36 int streamer_init(streamer_t * self)
37 {
38     return self->init_cb(self);
39 }
40
41 ssize_t streamer_read(streamer_t * self, char * buf, size_t len)
42 {
43     return self->read_cb(self, buf, len);
44 }
45
46 ssize_t streamer_write(streamer_t * self, const char * buf, size_t len)
47 {
48     return self->write_cb(self, buf, len);
49 }
50
51 ssize_t streamer_vprintf(streamer_t * self, const char * fmt, va_list ap)
52 {
53     char buf[CONSOLE_DEFAULT_MAX_LINE];
54     unsigned len;
55
56     // vsnprintf doesn't return negative numbers as long as the length it's
57     // passed fits in INT_MAX.
58     static_assert(sizeof(buf) <= INT_MAX, "Return value cast not valid");
59     len = static_cast<unsigned int>(vsnprintf(buf, sizeof(buf), fmt, ap));
60     if (len >= sizeof(buf))
61     {
62         len = sizeof(buf) - 1;
63     }
64     return streamer_write(self, buf, len);
65 }
66
67 ssize_t streamer_printf(streamer_t * self, const char * fmt, ...)
68 {
69     va_list ap;
70     ssize_t rc;
71
72     va_start(ap, fmt);
73     rc = streamer_vprintf(self, fmt, ap);
74     va_end(ap);
75
76     return rc;
77 }
78
79 void streamer_print_hex(streamer_t * self, const uint8_t * bytes, int len)
80 {
81     for (int i = 0; i < len; i++)
82     {
83         streamer_printf(streamer_get(), "%02x", bytes[i]);
84     }
85 }
86
87 } // namespace Shell
88 } // namespace chip