range.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * QEMU 64-bit address ranges
  3. *
  4. * Copyright (c) 2015-2016 Red Hat, Inc.
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "qemu/osdep.h"
  20. #include "qemu/range.h"
  21. /*
  22. * Return -1 if @a < @b, 1 @a > @b, and 0 if they touch or overlap.
  23. * Both @a and @b must not be empty.
  24. */
  25. static inline int range_compare(Range *a, Range *b)
  26. {
  27. assert(!range_is_empty(a) && !range_is_empty(b));
  28. /* Careful, avoid wraparound */
  29. if (b->lob && b->lob - 1 > a->upb) {
  30. return -1;
  31. }
  32. if (a->lob && a->lob - 1 > b->upb) {
  33. return 1;
  34. }
  35. return 0;
  36. }
  37. /* Insert @data into @list of ranges; caller no longer owns @data */
  38. GList *range_list_insert(GList *list, Range *data)
  39. {
  40. GList *l;
  41. assert(!range_is_empty(data));
  42. /* Skip all list elements strictly less than data */
  43. for (l = list; l && range_compare(l->data, data) < 0; l = l->next) {
  44. }
  45. if (!l || range_compare(l->data, data) > 0) {
  46. /* Rest of the list (if any) is strictly greater than @data */
  47. return g_list_insert_before(list, l, data);
  48. }
  49. /* Current list element overlaps @data, merge the two */
  50. range_extend(l->data, data);
  51. g_free(data);
  52. /* Merge any subsequent list elements that now also overlap */
  53. while (l->next && range_compare(l->data, l->next->data) == 0) {
  54. GList *new_l;
  55. range_extend(l->data, l->next->data);
  56. g_free(l->next->data);
  57. new_l = g_list_delete_link(list, l->next);
  58. assert(new_l == list);
  59. }
  60. return list;
  61. }