2012-02-24

Unbounded_Stack Without Garbage Collection

Let's consider a version of Unbounded_Stack that will work without garbage collection. First, we remove the pragma Garbage_Collection from the module specification (or change it to Required => False). Otherwise, the module specification remains the same.

The module body becomes:

Unbounded_Stack : module body is
   Stack : module body is
      type Node;
      type Node_Ptr is reference Node;
      type Node is record
         Value : Element;
         Next  : Node_Ptr;
      end Node;

      Top : Node_Ptr;

      Push : procedure body (Item : in Element) is
         null;
      Push : begin
         Top <- new Node'(Value => Item, Next => Top);
      Push : exception
      when others =>
         raise;
      Push : end;

      Pop : function body return Element is
         Temp   : constant Node_Ptr is Top;
         Result : constant Element is Top.Value;
      Pop : begin
         Top <- Top.Next;
         Temp'Free;

         return Result;
      Pop : exception
      when others =>
         raise;
      Pop : end;

      Length : function body return General_Count_Value is
         Result : General_Count_Value is 0;
         Temp   : Node_Ptr is Top;
      Length : begin
         Count : loop
            exit Count when Temp = null;

            Result <- Result + 1;
            Temp <- Temp.Next;
         Count : end loop;

         return Result;
      Length : exception
      when others =>
         raise;
      Length : end;

      Is_Empty : function body return Boolean is
         null;
      Is_Empty : begin
         return Top = null;
      Is_Empty : exception
      when others =>
         raise;
      Is_Empty : end;
   Stack : end;
Unbounded_Stack : end;

The only thing that changes is the body of Pop. The reason for the change should be clear.

No comments:

Post a Comment

Blog Archive