block.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. use std::{ops, cmp};
  2. use std::ptr::Unique;
  3. pub struct Block {
  4. pub size: usize,
  5. pub ptr: Unique<u8>,
  6. }
  7. impl Block {
  8. pub unsafe fn end(&self) -> Unique<u8> {
  9. Unique::new((self.size + *self.ptr as usize) as *mut _)
  10. }
  11. pub fn left_to(&self, to: &Block) -> bool {
  12. self.size + *self.ptr as usize == *to.ptr as usize
  13. }
  14. }
  15. impl PartialOrd for Block {
  16. fn partial_cmp(&self, other: &Block) -> Option<cmp::Ordering> {
  17. self.ptr.partial_cmp(&other.ptr)
  18. }
  19. }
  20. impl Ord for Block {
  21. fn cmp(&self, other: &Block) -> cmp::Ordering {
  22. self.ptr.cmp(&other.ptr)
  23. }
  24. }
  25. impl cmp::PartialEq for Block {
  26. fn eq(&self, _: &Block) -> bool {
  27. false
  28. }
  29. }
  30. impl cmp::Eq for Block {}
  31. #[derive(PartialEq, Eq)]
  32. pub struct BlockEntry {
  33. block: Block,
  34. pub free: bool,
  35. }
  36. impl ops::Deref for BlockEntry {
  37. type Target = Block;
  38. fn deref(&self) -> &Block {
  39. &self.block
  40. }
  41. }
  42. impl ops::DerefMut for BlockEntry {
  43. fn deref_mut(&mut self) -> &mut Block {
  44. &mut self.block
  45. }
  46. }
  47. impl PartialOrd for BlockEntry {
  48. fn partial_cmp(&self, other: &BlockEntry) -> Option<cmp::Ordering> {
  49. self.block.partial_cmp(other)
  50. }
  51. }
  52. impl Ord for BlockEntry {
  53. fn cmp(&self, other: &BlockEntry) -> cmp::Ordering {
  54. self.block.cmp(other)
  55. }
  56. }
  57. impl<'a> ops::AddAssign<&'a mut BlockEntry> for BlockEntry {
  58. fn add_assign(&mut self, rhs: &mut BlockEntry) {
  59. self.size += rhs.size;
  60. // Free the other block.
  61. rhs.free = false;
  62. debug_assert!(self.left_to(&rhs));
  63. }
  64. }
  65. impl From<Block> for BlockEntry {
  66. fn from(block: Block) -> BlockEntry {
  67. BlockEntry {
  68. block: block,
  69. free: true,
  70. }
  71. }
  72. }