Next: , Previous: , Up: Structuring Data   [Contents][Index]

### 4.9 Functions in Structs

Further reading of the Packet Specification 1.2 reveals that each Packet has an additional `crc` field. The content of this field is derived from both the payload bytes and the control bytes.

But this is no vulgar CRC we are talking about. On the contrary, it is a special function developed by the CRC Foundation in partnership with the Packet Foundation, called superCRC (patented, TM).

Fortunately, the CRC Foundation distributes a pickle `supercrc.pk`, that provides a `calculate_crc` function with the following spec:

```fun calculate_crc = (byte[] data, byte[] control) int:
```

So let’s use the function like this in our type, after loading the supercrc pickle:

```load supercrc;

type Packet =
struct
{
byte magic = 0xab;
byte size;

var real_size = (size == 0xff ? 0 : size);

byte[real_size] control;

int crc = calculate_crc (payload, control);
};
```

However, there is a caveat: it happens that the calculation of the CRC may involve arithmetic and division, so the CRC Foundation warns us that the `calculate_crc` function may raise E_div_by_zero. However, the Packet 1.2 Specification tells us that in these situations, the `crc` field of the packet should contain zero. If we used the type above, any exception raised by `calculate_crc` would be propagated by the mapper/constructor:

```(poke) Packet @ 12#B
unhandled division by zero exception
```

A solution is to use a function that takes care of the extra needed logic, wrapping calculate_crc:

```load supercrc;

type Packet =
struct
{
byte magic = 0xab;
byte size;

var real_size = (size == 0xff ? 0 : size);

byte[real_size] control;

fun corrected_crc = int:
{
{"ft_lang_label":"__label__en","ft_lang_prob":0.77235824,"math_prob":0.97494376,"size":2277,"snap":"2023-14-2023-23","text_gpt3_token_len":525,"char_repetition_ratio":0.13462384,"word_repetition_ratio":0.16759777,"special_character_ratio":0.23012736,"punctuation_ratio":0.16267942,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9622615,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-06-08T17:35:45Z\",\"WARC-Record-ID\":\"<urn:uuid:67674eb2-cf31-4b55-a958-18832a942d72>\",\"Content-Length\":\"6550\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:f800da7a-6a45-4c0f-b064-35eec847e7a0>\",\"WARC-Concurrent-To\":\"<urn:uuid:9c82ebc5-a146-4058-b2d8-ea846fae3f7a>\",\"WARC-IP-Address\":\"87.98.247.3\",\"WARC-Target-URI\":\"https://jemarch.net/poke-2.4-manual/html_node/Functions-in-Structs.html\",\"WARC-Payload-Digest\":\"sha1:7AWOC2I5RDR7XTBLAKCGZODECJG62VPB\",\"WARC-Block-Digest\":\"sha1:T6PJUAI5BIMPDPHA5EDD3SXAVD4B7Z3C\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224655092.36_warc_CC-MAIN-20230608172023-20230608202023-00624.warc.gz\"}"}