DiskExtentsHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Copyright (C) 2014-2016 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. namespace DiskAccessLibrary
  11. {
  12. public class DiskExtentsHelper
  13. {
  14. /// <param name="dataRegionSize">In bytes</param>
  15. internal static List<DiskExtent> GetUnallocatedExtents(Disk disk, long dataRegionStartSector, long dataRegionSize, List<DiskExtent> usedExtents)
  16. {
  17. List<DiskExtent> result = new List<DiskExtent>();
  18. long startSector = dataRegionStartSector;
  19. SortExtentsByFirstSector(usedExtents);
  20. // see if there is room before each extent
  21. foreach (DiskExtent extent in usedExtents)
  22. {
  23. long extentStartSector = extent.FirstSector;
  24. long nextStartSector = extent.FirstSector + extent.Size / disk.BytesPerSector;
  25. long freeSpaceInBytes = (extentStartSector - startSector) * disk.BytesPerSector;
  26. if (freeSpaceInBytes > 0)
  27. {
  28. result.Add(new DiskExtent(disk, startSector, freeSpaceInBytes));
  29. }
  30. startSector = nextStartSector;
  31. }
  32. // see if there is room after the last extent
  33. long spaceInBytes = dataRegionSize - (startSector - dataRegionStartSector) * disk.BytesPerSector;
  34. if (spaceInBytes > 0)
  35. {
  36. result.Add(new DiskExtent(disk, startSector, spaceInBytes));
  37. }
  38. return result;
  39. }
  40. /// <summary>
  41. /// Sort (in-place) extents by first sector
  42. /// </summary>
  43. public static void SortExtentsByFirstSector(List<DiskExtent> extents)
  44. {
  45. SortedList<long, DiskExtent> list = new SortedList<long, DiskExtent>();
  46. foreach (DiskExtent extent in extents)
  47. {
  48. list.Add(extent.FirstSector, extent);
  49. }
  50. extents.Clear();
  51. extents.AddRange(list.Values);
  52. }
  53. }
  54. }