best_fit_on_freelist.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2011 Institute of Communication and Computer Systems (ICCS)
  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. */
  17. #include "sll/best_fit_on_freelist.h"
  18. #include "block_header.h"
  19. /**
  20. * \details In order to remove a block from a singly linked list, we need to
  21. * keep track of the previous block as well: The previous block must point to
  22. * the current block's next block once the current one is removed.
  23. * Normally the best fit search alogrithm would have to traverse the whole list
  24. * in order to find the best block. However, a check is being performed each
  25. * time a new best candidate is found, so that we stop once a perfect block is
  26. * found.
  27. */
  28. void * best_fit_on_freelist(heap_t *heap, size_t requested_size) {
  29. void *current_block, *previous_block, *ptr;
  30. void *best_block, *best_previous_block;
  31. size_t best_size;
  32. ptr = NULL;
  33. best_block = NULL;
  34. best_size = (size_t) -1; /* SIZE_MAX */
  35. for(current_block = heap->free_list_head; current_block != NULL;
  36. current_block = get_next(current_block)) {
  37. if(get_size(current_block) >= requested_size) {
  38. if(get_size(current_block) < best_size) {
  39. best_block = current_block;
  40. best_size = get_size(current_block);
  41. best_previous_block = previous_block;
  42. if(best_size == requested_size) {
  43. break;
  44. }
  45. }
  46. }
  47. previous_block = current_block;
  48. }
  49. /* Remove the block from the list */
  50. if(best_block != NULL) {
  51. if(best_block == heap->free_list_head) {
  52. heap->free_list_head = get_next(best_block);
  53. } else {
  54. set_next(best_previous_block, get_next(best_block));
  55. }
  56. ptr = best_block;
  57. }
  58. return ptr;
  59. }