3 * Copyright (c) 2020 Project CHIP Authors
4 * Copyright (c) 2019 Apache Software Foundation (ASF)
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * Source implementation for an input / output stream abstraction.
29 #ifndef CONSOLE_DEFAULT_MAX_LINE
30 #define CONSOLE_DEFAULT_MAX_LINE 256
36 int streamer_init(streamer_t * self)
38 return self->init_cb(self);
41 ssize_t streamer_read(streamer_t * self, char * buf, size_t len)
43 return self->read_cb(self, buf, len);
46 ssize_t streamer_write(streamer_t * self, const char * buf, size_t len)
48 return self->write_cb(self, buf, len);
51 ssize_t streamer_vprintf(streamer_t * self, const char * fmt, va_list ap)
53 char buf[CONSOLE_DEFAULT_MAX_LINE];
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))
62 len = sizeof(buf) - 1;
64 return streamer_write(self, buf, len);
67 ssize_t streamer_printf(streamer_t * self, const char * fmt, ...)
73 rc = streamer_vprintf(self, fmt, ap);
79 void streamer_print_hex(streamer_t * self, const uint8_t * bytes, int len)
81 for (int i = 0; i < len; i++)
83 streamer_printf(streamer_get(), "%02x", bytes[i]);