You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ebuffer.c 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. /**
  19. * @file
  20. *
  21. * Automatically expanding buffers
  22. *
  23. */
  24. #include <errno.h>
  25. #include <gpxe/buffer.h>
  26. #include <gpxe/emalloc.h>
  27. #include <gpxe/ebuffer.h>
  28. /**
  29. * Expand expandable buffer
  30. *
  31. * @v buffer Buffer descriptor
  32. * @v new_len Required new size
  33. * @ret rc Return status code
  34. */
  35. static int ebuffer_expand ( struct buffer *buffer, size_t new_len ) {
  36. size_t actual_len = 1;
  37. userptr_t new_addr;
  38. /* Round new_len up to the nearest power of two, to reduce
  39. * total number of reallocations required.
  40. */
  41. while ( actual_len < new_len )
  42. actual_len <<= 1;
  43. /* Reallocate buffer */
  44. new_addr = erealloc ( buffer->addr, actual_len );
  45. if ( ! new_addr )
  46. return -ENOMEM;
  47. buffer->addr = new_addr;
  48. buffer->len = actual_len;
  49. return 0;
  50. }
  51. /**
  52. * Allocate expandable buffer
  53. *
  54. * @v buffer Buffer descriptor
  55. * @v len Initial length (may be zero)
  56. * @ret rc Return status code
  57. *
  58. * Allocates space for the buffer and stores it in @c buffer->addr.
  59. * The space must eventually be freed by calling efree(buffer->addr).
  60. */
  61. int ebuffer_alloc ( struct buffer *buffer, size_t len ) {
  62. memset ( buffer, 0, sizeof ( *buffer ) );
  63. buffer->expand = ebuffer_expand;
  64. return ebuffer_expand ( buffer, len );
  65. }