utils.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #ifndef _ADB_UTILS_H
  17. #define _ADB_UTILS_H
  18. /* bounded buffer functions */
  19. /* all these functions are used to append data to a bounded buffer.
  20. *
  21. * after each operation, the buffer is guaranteed to be zero-terminated,
  22. * even in the case of an overflow. they all return the new buffer position
  23. * which allows one to use them in succession, only checking for overflows
  24. * at the end. For example:
  25. *
  26. * BUFF_DECL(temp,p,end,1024);
  27. * char* p;
  28. *
  29. * p = buff_addc(temp, end, '"');
  30. * p = buff_adds(temp, end, string);
  31. * p = buff_addc(temp, end, '"');
  32. *
  33. * if (p >= end) {
  34. * overflow detected. note that 'temp' is
  35. * zero-terminated for safety.
  36. * }
  37. * return strdup(temp);
  38. */
  39. /* tries to add a character to the buffer, in case of overflow
  40. * this will only write a terminating zero and return buffEnd.
  41. */
  42. char* buff_addc (char* buff, char* buffEnd, int c);
  43. /* tries to add a string to the buffer */
  44. char* buff_adds (char* buff, char* buffEnd, const char* s);
  45. /* tries to add a bytes to the buffer. the input can contain zero bytes,
  46. * but a terminating zero will always be appended at the end anyway
  47. */
  48. char* buff_addb (char* buff, char* buffEnd, const void* data, int len);
  49. /* tries to add a formatted string to a bounded buffer */
  50. char* buff_add (char* buff, char* buffEnd, const char* format, ... );
  51. /* convenience macro used to define a bounded buffer, as well as
  52. * a 'cursor' and 'end' variables all in one go.
  53. *
  54. * note: this doesn't place an initial terminating zero in the buffer,
  55. * you need to use one of the buff_ functions for this. or simply
  56. * do _cursor[0] = 0 manually.
  57. */
  58. #define BUFF_DECL(_buff,_cursor,_end,_size) \
  59. char _buff[_size], *_cursor=_buff, *_end = _cursor + (_size)
  60. #endif /* _ADB_UTILS_H */