utils.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (C) 2008 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "utils.h"
  17. #include <stdarg.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. char*
  21. buff_addc (char* buff, char* buffEnd, int c)
  22. {
  23. int avail = buffEnd - buff;
  24. if (avail <= 0) /* already in overflow mode */
  25. return buff;
  26. if (avail == 1) { /* overflowing, the last byte is reserved for zero */
  27. buff[0] = 0;
  28. return buff + 1;
  29. }
  30. buff[0] = (char) c; /* add char and terminating zero */
  31. buff[1] = 0;
  32. return buff + 1;
  33. }
  34. char*
  35. buff_adds (char* buff, char* buffEnd, const char* s)
  36. {
  37. int slen = strlen(s);
  38. return buff_addb(buff, buffEnd, s, slen);
  39. }
  40. char*
  41. buff_addb (char* buff, char* buffEnd, const void* data, int len)
  42. {
  43. int avail = (buffEnd - buff);
  44. if (avail <= 0 || len <= 0) /* already overflowing */
  45. return buff;
  46. if (len > avail)
  47. len = avail;
  48. memcpy(buff, data, len);
  49. buff += len;
  50. /* ensure there is a terminating zero */
  51. if (buff >= buffEnd) { /* overflow */
  52. buff[-1] = 0;
  53. } else
  54. buff[0] = 0;
  55. return buff;
  56. }
  57. char*
  58. buff_add (char* buff, char* buffEnd, const char* format, ... )
  59. {
  60. int avail;
  61. avail = (buffEnd - buff);
  62. if (avail > 0) {
  63. va_list args;
  64. int nn;
  65. va_start(args, format);
  66. nn = vsnprintf( buff, avail, format, args);
  67. va_end(args);
  68. if (nn < 0) {
  69. /* some C libraries return -1 in case of overflow,
  70. * but they will also do that if the format spec is
  71. * invalid. We assume ADB is not buggy enough to
  72. * trigger that last case. */
  73. nn = avail;
  74. }
  75. else if (nn > avail) {
  76. nn = avail;
  77. }
  78. buff += nn;
  79. /* ensure that there is a terminating zero */
  80. if (buff >= buffEnd)
  81. buff[-1] = 0;
  82. else
  83. buff[0] = 0;
  84. }
  85. return buff;
  86. }