I am still learning to use the language, so these are all newbie questions, that I hope may also be useful for other:
In an example by Dale Stanbrough from rmit.edu.au: Link
generic
type Item is private;
Maximum_Buffer_Size : in Positive;
package Bounded_Buffer_Package is
subtype Buffer_Index is Positive range 1..Maximum_Buffer_Size;
subtype Buffer_Count is Natural range 0..Maximum_Buffer_Size;
type Buffer_Array is array (Buffer_Index) of Item;
protected type Bounded_Buffer is
entry Get (X : out Item);
entry Put (X : in Item);
private
Get_Index : Buffer_Index := 1;
Put_Index : Buffer_Index := 1;
Count : Buffer_Count := 0;
Data : Buffer_Array;
end Bounded_Buffer;
end Bounded_Buffer_Package;
-------------------------------------------------------------
package body Bounded_Buffer_Package is
protected body Bounded_Buffer is
entry Get (X : out Item) when Count > 0 is
begin
X := Data(Get_Index);
Get_Index := (Get_Index mod Maximum_Buffer_Size) + 1;
Count := Count - 1;
end Get;
entry Put (X : in Item) when Count < Maximum_Buffer_Size is
begin
Data(Put_Index) := X;
Put_Index := (Put_Index mod Maximum_Buffer_Size) + 1;
Count := Count + 1;
end Put;
end Bounded_Buffer;
end Bounded_Buffer_Package;
I have used the package as follows:
with Text_IO; use Text_IO;
with Bounded_Buffer_Package;
procedure test_buffer is
package my_buffer_instance is new Bounded_Buffer_Package(Item => Integer, Maximum_Buffer_Size =>100);
my_buffer : my_buffer_instance.Bounded_Buffer;
val : Integer;
begin
my_buffer.Put(17);
my_buffer.Get(val);
Put_line(Integer'Image(val));
end test_buffer;
==== EDITED ===
The code works, but I have the following question:
Is this the correct way to use generic package with a protected object? If not, what is the right way to instantiate the bounded buffer object?
=== EDIT 2 - clarification ===
What I want to ask is: Am I unintentionally allocating all the data (including the buffer that can be big) twice? Once in the instantiation of package my_buffer_instance
, and second time in my_buffer
definition?
Is my understanding that new Bounded_Buffer_Package
only defines the type, Bounded_Buffer
but does not allocate memory until the type is used correct?