Signature package (Ada)

From LiteratePrograms

Jump to: navigation, search

This is a simple signature package. Using the signature package we can write code that will work with any component which provides the interface specified by the signature package.

<<Any_Structure.ada>>=
generic
   type Structure is limited private;
   type Element is private;
   with procedure Init(S:out Structure) is <>;
   with procedure Insert(S:in out Structure;E:in Element) is <>;
   with procedure Remove(S:in out Structure;E:out Element) is <>;
package Any_Structure is
end;

We now use the signature package to write a package that will be able to create a concurrent version of any structure mathing the signature. The concurrent version makes use of Ada's protected types.

<<Protect_Structure.ada>>=
with Any_Structure;
generic
   with package Base_Structure is new Any_Structure(<>);
package Protect_Structure is
   protected type Structure is 
      procedure Init;
      entry Insert(E:in Base_Structure.Element);
      entry Remove(E:out Base_Structure.Element);
   private
      Initialized:Boolean:=FALSE;
      Data:Base_Structure.Structure;
   end;
end;  

The implementation of the protected structure simply wraps around the operations provided by the structure passed as an argument to the package Protetected_Structure.

<<Protect_Structure.ada>>=
package body Protect_Structure is
   ---------------
   -- Structure --
   ---------------
   protected body Structure is
      ----------
      -- Init --
      ----------
      procedure Init is
      begin
         Base_Structure.Init(Data);
         Initialized:=TRUE;
      end Init;
      ------------
      -- Insert --
      ------------
      entry Insert (E:in Base_Structure.Element) when Initialized is
      begin
         Base_Structure.Insert(Data,E);
      end Insert;
      ------------
      -- Remove --
      ------------
      entry Remove (E:out Base_Structure.Element) when Initialized is
      begin
         Base_Structure.Remove(Data,E);
      end Remove;
   end Structure;
end Protect_Structure;
Download code
Views