COMPDEMO.MOD 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. MODULE CompDemo;
  2. (* This module demonstrates the use of virtual pointers and the Compact
  3. module to implement a heap the does not suffer from fragmentation.
  4. Note however that the heap is very slow *)
  5. (*%F _fptr *)
  6. This demo program will only work in memory models with far data pointers
  7. (*%E *)
  8. IMPORT Compact,IO,Str;
  9. TYPE
  10. SString=ARRAY[0..63] OF CHAR;
  11. LString=ARRAY[0..255] OF CHAR;
  12. StrP=POINTER TO LString;
  13. INLINE PROCEDURE StrDeref(x:Compact.HandleType):StrP;
  14. BEGIN
  15. RETURN StrP(Compact.DerefHandle(x))
  16. END StrDeref;
  17. TYPE
  18. MovableStrP=VIRTUAL POINTER StrDeref;
  19. VAR
  20. StrArray:ARRAY[1..1000] OF MovableStrP;
  21. OK:BOOLEAN;
  22. I,TotDone:CARDINAL;
  23. BEGIN
  24. IO.WrStr('First to allocate as many strings of length 64 as possible');
  25. IO.WrLn;
  26. I:=1;
  27. LOOP
  28. StrArray[I]:=MovableStrP(Compact.Allocate(64));
  29. IF StrArray[I]=MovableStrP(Compact.NotAHandle) THEN EXIT END;
  30. Str.CardToStr(LONGCARD(I),StrArray[I]^,10,OK);
  31. I:=I+1
  32. END;
  33. TotDone:=I-1;
  34. IO.WrStr('Able to create ');
  35. IO.WrCard(TotDone,5);
  36. IO.WrStr(' such strings. ');
  37. IO.WrLn;
  38. IO.WrStr('Each contains the string form of the index number');
  39. IO.WrLn;
  40. IO.WrStr('For example Value[100]=');
  41. IO.WrStr(StrArray[100]^);
  42. IO.WrLn;
  43. IO.WrStr('Now release every OTHER string leaving lots of 64 byte holes in heap');
  44. IO.WrLn;
  45. I:=1;
  46. WHILE (I<TotDone) DO
  47. Compact.Deallocate(Compact.HandleType(StrArray[I]));
  48. I:=I+2;
  49. END;
  50. IO.WrStr('With a normal heap manager the largest element you could allocate would');
  51. IO.WrLn;
  52. IO.WrStr('be 64 bytes. But with this heap manager a request for >64 bytes will');
  53. IO.WrLn;
  54. IO.WrStr('result in a heap compaction freeing up all space to be allocated in');
  55. IO.WrLn;
  56. IO.WrStr('one block. Now to allocate some 256 byte strings.');
  57. I:=1;
  58. LOOP
  59. StrArray[I]:=MovableStrP(Compact.Allocate(256));
  60. IF StrArray[I]=MovableStrP(Compact.NotAHandle) THEN EXIT END;
  61. I:=I+2
  62. END;
  63. IO.WrLn;
  64. IO.WrStr('Managed ');
  65. IO.WrCard((I-1) DIV 2,5);
  66. IO.WrLn;
  67. IO.WrStr('Just to prove the old values have not been lost as a result here is Value[100]');
  68. IO.WrLn;
  69. IO.WrStr('again :');
  70. IO.WrStr(StrArray[100]^);
  71. IO.WrLn;
  72. IO.WrStr('And the really clever thing is that these pointers are dereferenced');
  73. IO.WrLn;
  74. IO.WrStr('using the usual syntax as examining the code will show.');
  75. END CompDemo.