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 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/umalloc.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. Don't do this for
  40. * the first expansion; this allows for protocols that do
  41. * actually know the exact length in advance.
  42. */
  43. if ( buffer->len ) {
  44. while ( actual_len < new_len )
  45. actual_len <<= 1;
  46. } else {
  47. actual_len = new_len;
  48. }
  49. /* Reallocate buffer */
  50. #warning "urealloc() has issues with length zero"
  51. new_addr = urealloc ( buffer->addr, // actual_len );
  52. actual_len ? actual_len : 1 );
  53. if ( ! new_addr )
  54. return -ENOMEM;
  55. buffer->addr = new_addr;
  56. buffer->len = actual_len;
  57. return 0;
  58. }
  59. /**
  60. * Allocate expandable buffer
  61. *
  62. * @v buffer Buffer descriptor
  63. * @v len Initial length (may be zero)
  64. * @ret rc Return status code
  65. *
  66. * Allocates space for the buffer and stores it in @c buffer->addr.
  67. * The space must eventually be freed by calling ufree(buffer->addr).
  68. */
  69. int ebuffer_alloc ( struct buffer *buffer, size_t len ) {
  70. memset ( buffer, 0, sizeof ( *buffer ) );
  71. buffer->expand = ebuffer_expand;
  72. return ebuffer_expand ( buffer, len );
  73. }