9 Associative Arrays +1
A continuing introduction to associative arrays, reviewing setting default values and using some built-in methods (exists(), first(), next()).
If a non-initialized index is read the default value for the data type will be returned.
A default may be specified in the structure literal
which is used to initialize the associative array.
bc. integer aa [bit [15:0]];
aa = '{2:5, 6:55, 7:3, 16'hFFFE:-6, default:0};
Some methods that can be used for traversing associative arrays.
//returns 1 if it element at index exists, else 0
function int exists(input index);
//returns 1 if it there is a first index (i.e. any existent index means there is a first), else 0
//sets index to the value of the first element (where first is the smallest index)
function int first(ref index);
//returns 1 if it there is a next index (where the next index is greater than value of index when function is called, i.e. passed in as the ref index
), else 0
//updates index to the value of the next element
function int next(ref index);
//returns 1 if it there is a previous index (less than the passed in ref index
), else 0
//updates index to the value of the previous element (next smallest index, starting from the input ref index
)
function int prev(ref index);
//returns 1 if it there is a last index (i.e. any existent index means there is a last), else 0
//sets index to the value of the last element (where last is the largest index)
function int last(ref index);
example code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
module aa;
integer aa [bit [15:0]];
bit [15:0] ii,iii;
initial begin
aa = '{2:5, 6:55, 7:3, 16'hFFFE:-6, default:0};
show();
$display(" >>%0d",aa[88]);
show();
if (aa.exists(6)) begin
aa[6] = 6;
show();
end // if (aa.exists(6))
// first, last, next, prev
if (aa.first(ii)) begin
void'(aa.next(iii));
void'(aa.next(iii));
$display(" aa[%0d]=%0d, aa[%0d]=%0d", ii, aa[ii], iii, aa[iii]);
aa[ii] = aa[iii];
show();
end
end
function void show();
foreach (aa[i]) begin
$write("aa[%4h]=%0d, ",i,aa[i]);
end
$display("");
$display(" aa size =%0d",aa.size());
endfunction
endmodule // aa
.
//run command
1
irun -sv aa.sv
NOTA BENE: See Comments section for an explanation of my mistake in using next() in two consecutive calls to reach the second value.