buffer.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  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 <stdarg.h>
  17. #include <stdio.h>
  18. #include "buffer.h"
  19. void CreateBuff(int inlen, int &len, char **buff)
  20. {
  21. if (*buff == NULL) {
  22. *buff = (char *)CALLOC(inlen, sizeof(char));
  23. if (*buff == NULL)
  24. len = 0;
  25. else
  26. len = inlen;
  27. } else {
  28. if (len < inlen) {
  29. FREE_IF(*buff);
  30. *buff = (char *)CALLOC(inlen, sizeof(char));
  31. if (*buff == NULL)
  32. len = 0;
  33. else
  34. len = inlen;
  35. } else {
  36. memset(*buff, 0x0, len);
  37. }
  38. }
  39. }
  40. int buffer::bprintf(const char *format, ...)
  41. {
  42. va_list ap;
  43. long len;
  44. va_start(ap, format);
  45. len = bprintf(format, ap);
  46. va_end(ap);
  47. return len;
  48. }
  49. int buffer::vbprintf(const char *format, va_list ap)
  50. {
  51. long len;
  52. va_list ap2;
  53. #ifdef __va_copy
  54. __va_copy(ap2, ap);
  55. #else
  56. va_copy(ap2, ap);
  57. #endif
  58. len = vsnprintf(cursor(), remain(), format, ap);
  59. if (len < 0)
  60. return len;
  61. if ((unsigned long)len >= remain()) {
  62. if (expand(len) < 0)
  63. return -1;
  64. len = vsnprintf(cursor(), remain(), format, ap2);
  65. if (len < 0)
  66. return len;
  67. }
  68. dataSize += len;
  69. return len;
  70. }