1#!/usr/bin/env python3
 2
 3class Segment:
 4    """Base class for objects representing complete RAPID blocks or header sections of blocks."""
 5    def __init__(self, buff, file_pos=0, product_id=None):
 6        if isinstance(buff, Segment):
 7            self.buff = buff.buff
 8            self.product_id = buff.product_id
 9            self.file_pos = buff.file_pos
10
11        else:
12            self.buff = buff
13            self.product_id = None
14            self.file_pos = None
15
16        if file_pos is not None:
17            self.file_pos = file_pos
18
19        if product_id is not None:
20            self.product_id = product_id
21
22    def hex_dump(self):
23        """Return a string containing our buffer in hex representation."""
24        return '0x{buff}'.format(buff=self.buff.hex())
25
26    def __len__(self):
27        return len(self.buff)
28
29    def __getitem__(self, key):
30        """Allow clients to slice us, updating `buff` and `file_pos`."""
31        if isinstance(key, slice):
32            return Segment(
33                self.buff[key.start:key.stop:key.step],
34                file_pos=self.file_pos + key.start if key.start is not None else self.file_pos,
35                product_id=self.product_id)
36
37        elif isinstance(key, int):
38            return self.buff[key]
39
40        else:
41            raise ValueError('Bad key type')
42
43    def hex(self):
44        """Pretend we're a normal `bytes` object if someone calls hex()."""
45        return self.buff.hex()
46
47    def __str__(self):
48        return 'buff:{buff} product_id:{prod} file_pos:{pos}'.format(
49            buff=type(self.buff), prod=self.product_id, pos=self.file_pos)
50
51    def decode(self, codec=None):
52        """Pretend to be a binary buffer."""
53        return self.buff.decode(codec)
54
55    def bytes(self, start, stop=None):
56        """Return a slice of our buffer as raw bytes."""
57        return self.buff[start:stop]
58
59    def read(self):
60        """Pretend we are a file handle."""
61        return self.buff