2 * Copyright (C) ARM Limited 2013-2014. All rights reserved.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
19 // Pick an aggressive size as buffer is primarily used for disk IO
20 #define MIN_BUFFER_FREE (1 << 12)
22 int DynBuf::resize(const size_t minCapacity) {
23 size_t scaledCapacity = 2 * capacity;
24 if (scaledCapacity < minCapacity) {
25 scaledCapacity = minCapacity;
27 if (scaledCapacity < 2 * MIN_BUFFER_FREE) {
28 scaledCapacity = 2 * MIN_BUFFER_FREE;
30 capacity = scaledCapacity;
32 buf = static_cast<char *>(realloc(buf, capacity));
40 bool DynBuf::read(const char *const path) {
43 const int fd = open(path, O_RDONLY);
45 logg->logMessage("%s(%s:%i): open failed", __FUNCTION__, __FILE__, __LINE__);
52 const size_t minCapacity = length + MIN_BUFFER_FREE + 1;
53 if (capacity < minCapacity) {
54 if (resize(minCapacity) != 0) {
55 logg->logMessage("%s(%s:%i): DynBuf::resize failed", __FUNCTION__, __FILE__, __LINE__);
60 const ssize_t bytes = ::read(fd, buf + length, capacity - length - 1);
62 logg->logMessage("%s(%s:%i): read failed", __FUNCTION__, __FILE__, __LINE__);
64 } else if (bytes == 0) {
79 int DynBuf::readlink(const char *const path) {
80 ssize_t bytes = MIN_BUFFER_FREE;
83 if (static_cast<size_t>(bytes) >= capacity) {
84 const int err = resize(2 * bytes);
89 bytes = ::readlink(path, buf, capacity);
92 } else if (static_cast<size_t>(bytes) < capacity) {
103 bool DynBuf::printf(const char *format, ...) {
107 if (resize(2 * MIN_BUFFER_FREE) != 0) {
108 logg->logMessage("%s(%s:%i): DynBuf::resize failed", __FUNCTION__, __FILE__, __LINE__);
113 va_start(ap, format);
114 int bytes = vsnprintf(buf, capacity, format, ap);
117 logg->logMessage("%s(%s:%i): fsnprintf failed", __FUNCTION__, __FILE__, __LINE__);
121 if (static_cast<size_t>(bytes) > capacity) {
122 if (resize(bytes + 1) != 0) {
123 logg->logMessage("%s(%s:%i): DynBuf::resize failed", __FUNCTION__, __FILE__, __LINE__);
127 va_start(ap, format);
128 bytes = vsnprintf(buf, capacity, format, ap);
131 logg->logMessage("%s(%s:%i): fsnprintf failed", __FUNCTION__, __FILE__, __LINE__);