[Bro] nested &defaults
Siwek, Jonathan Luke
jsiwek at illinois.edu
Mon Mar 25 11:32:54 PDT 2013
On Mar 25, 2013, at 12:51 PM, David Mandelberg <dmandelb at bbn.com> wrote:
> I have a record with a field like this:
>
> type Histogram: record {
> histogram: vector of count;
> };
>
> I'd like histogram field to default to an empty vector and the
> individual counts in the vector to default to 0. I.e., I want the below
> code to print "42".
>
> global foo: Histogram;
> foo$histogram[5] += 42;
> print(foo$histogram[5]);
>
> Is that possible to set defaults for both $histogram and $histogram[N]?
I didn't think vectors supported a &default attribute very well, so I didn't try too hard to make that work, but here's what I came up with using a table indexed by counts and yielding counts (which is pretty much equivalent to a vector of count):
type HistogramType: table[count] of count;
function histogram_default(index: count): count
{
return 0;
}
const new_histogram: HistogramType = table() &default=histogram_default;
type HistogramRecord: record {
histogram: HistogramType &default=copy(new_histogram);
other_stuff: string &optional;
};
global foo: HistogramRecord;
global foo2: HistogramRecord;
foo$histogram[5] += 42;
print(foo$histogram[5]);
foo2$histogram[5] += 13;
print(foo2$histogram[5]);
The big trick there is that attributes don't currently propagate from types to values, so instead of setting a &default function on the HistogramType, I had to apply it to a constant, empty table and clone that for every new histogram instance.
- Jon
More information about the Bro
mailing list