ipo_hex.html


001| """IPO Implementation -- Hex Dump Process.
001| 
001| Classes:
001|     ipo_proc_hexdump (ipo_process)              ~HexDump Process subclass
001| 
001| """

002| ####################################################################################################
003| from logger import logger
004| from goodies import typename, KWARG
005| from files import EOL
006| from ipo_defs import ipo_token, ipo_process, EOL_TAG
007| ####################################################################################################
008| Log = logger('Hex')
009| 
010| 
011| ##================================================================================================##
012| def every_nth_item (alist:list, step=2, start=0):
013|     '''Return every Nth item from a list.'''
014|     for ix in range(start, len(alist), step):
015|         yield alist[ix]
016| 
017| 
018| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
019| class ipo_proc_hexout (ipo_process):
020|     """HexOutput Process subclass."""
021|     tag = 'any'
022| 
023|     def __init__ (self, **kwargs):
024|         """New HexOut Process instance."""
025|         super().__init__('HexOut')
026|         self.row_size  = KWARG('row', 16, int, kwargs)
027|         self.line_ctr = 0
028|         self.char_ctr = 0
029|         self.row = []
030|         self.buf = []
031| 
032|     def __call__ (self, datum):
033|         """Process next chunk of data."""
034|         self.buf = [] # default return is IGNORE signal
035| 
036|         if datum is None:
037|             # Handle last row...
038|             if 0 < len(self.row):
039|                 # Move row to output buffer...
040|                 self._move_row_to_buf()
041|                 return self.buf
042| 
043|             # EOD and row is empty now...
044|             self.status = -1
045|             return None
046| 
047|         super().__call__(datum)
048|         for d in datum:
049|             # If row is full...
050|             if self.row_size <= len(self.row):
051|                 # Move row to output buffer...
052|                 self._move_row_to_buf()
053|             # Add char to row...
054|             self.row.append(ord(d()))
055| 
056|         # Return empty or filled buffer...
057|         return self.buf
058| 
059|     def _move_row_to_buf (self):
060|         """Create output row."""
061|         row = ''.join(f'{b:02x}' for b in self.row)
062|         self.char_ctr += 1
063|         self.buf = [ipo_token(ch,self.char_ctr,ix,str(ix)) for ix,ch in enumerate(row,start=1)]
064|         self.buf.append(ipo_token(EOL, self.char_ctr,0, EOL_TAG))
065|         self.row = []
066|         self.line_ctr += self.row_size
067| 
068| 
069| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
070| class ipo_proc_hexdump (ipo_process):
071|     """HexDump Process subclass."""
072|     tag = 'any'
073|     Modes = ['dec', 'hex', 'oct']
074|     SPCX = ord(' ')
075| 
076|     def __init__ (self, **kwargs):
077|         """New HexDump Process instance."""
078|         super().__init__('HexDump')
079|         self.row_size  = KWARG('row', 16, int, kwargs)
080|         self.data_size = KWARG('size', 1, int, kwargs)
081|         self.le_or_be  = KWARG('bo'  , 'LE', str, kwargs)
082|         self.addr_mode = KWARG('addr', 'hex', str, kwargs)
083|         self.data_mode = KWARG('data', 'hex', str, kwargs)
084|         self.char_mode = KWARG('char', '.', str, kwargs)
085|         self.line_ctr = 0
086|         self.char_ctr = 0
087|         self.row = []
088|         self.buf = []
089| 
090|         # Vet the Byte Order argument...
091|         self.le_or_be = self.le_or_be.upper()
092|         if not self.le_or_be in ['LE', 'BE']:
093|             raise ValueError(f'Byte Order (BO) must be "LE" or "BE", not "{self.le_or_be}".')
094| 
095|         # Vet the Address Mode argument...
096|         self.addr_mode = self.addr_mode.lower()
097|         if not self.addr_mode in self.Modes:
098|             raise ValueError(f'Address Mode must be "dec", "hex", or "oct", not "{self.addr_mode}".')
099| 
100|         # Vet the Data Mode argument...
101|         self.data_mode = self.data_mode.lower()
102|         if not self.data_mode in self.Modes:
103|             raise ValueError(f'Data Mode must be "dec", "hex", or "oct", not "{self.data_mode}".')
104| 
105|         # Check row-size/data-size combo...
106|         self.words_per_row = self.row_size / self.data_size
107|         if self.words_per_row != int(self.words_per_row):
108|             raise ValueError(f'Illegal row-size ({self.row_size}) for data-size=2. Must be even.')
109|         self.words_per_row = int(self.words_per_row)
110| 
111|     def __call__ (self, datum):
112|         """Process next chunk of data."""
113|         self.buf = [] # default return is IGNORE signal
114| 
115|         if datum is None:
116|             # Handle last row...
117|             if 0 < len(self.row):
118|                 # Move row to output buffer...
119|                 self._move_row_to_buf()
120|                 return self.buf
121| 
122|             # EOD and row is empty now...
123|             self.status = -1
124|             return None
125| 
126|         super().__call__(datum)
127|         for d in datum:
128|             # If row is full...
129|             if self.row_size <= len(self.row):
130|                 # Move row to output buffer...
131|                 self._move_row_to_buf()
132|             # Add char to row...
133|             self.row.append(ord(d()))
134| 
135|         # Return empty or filled buffer...
136|         return self.buf
137| 
138|     def _move_row_to_buf (self):
139|         def cx2ch (char_index):
140|             if char_index < self.SPCX:
141|                 return '.'
142|             if self.SPCX <= char_index < 0x7f:
143|                 return chr(char_index)
144|             if char_index == 0x7f:
145|                 return '^'
146|             return '_'
147| 
148|         match self.addr_mode:
149|             case 'hex': addr = f'{self.line_ctr:06x}'
150|             case 'dec': addr = f'{self.line_ctr:06d}'
151|             case 'oct': addr = f'{self.line_ctr:06o}'
152|             case _:
153|                 raise ValueError(f'Unknown address mode: "{self.addr_mode}"')
154| 
155|         match self.data_size:
156|             case 1:
157|                 # Build output line...
158|                 data = ' '.join(f'{cx:02x}' for cx in self.row)
159|                 # Handle short row...
160|                 missing = self.row_size - len(self.row)
161|                 if 0 < missing:
162|                     data += (' '*3)*missing
163|             case 2:
164|                 evens = list(every_nth_item(self.row, step=2, start=0))
165|                 odds  = list(every_nth_item(self.row, step=2, start=1))
166|                 if len(evens) != len(odds):
167|                     raise RuntimeError(f'File is not a DWORD file!')
168|                 # Load multiple bytes (in specified order)...
169|                 if self.le_or_be == 'LE':
170|                     pairs = [(a*256)+b for a,b in zip(evens, odds)]
171|                 else:
172|                     pairs = [(a*256)+b for a,b in zip(odds, evens)]
173|                 # Build output line...
174|                 data = ' '.join(f'{cx:04x}' for cx in pairs)
175|                 # Handle short row...
176|                 missing = (self.row_size - len(self.row)) // 2
177|                 if 0 < missing:
178|                     data += (' '*5)*missing
179|             case 4:
180|                 b0 = list(every_nth_item(self.row, step=4, start=0))
181|                 b1 = list(every_nth_item(self.row, step=4, start=1))
182|                 b2 = list(every_nth_item(self.row, step=4, start=2))
183|                 b3 = list(every_nth_item(self.row, step=4, start=3))
184|                 if not ((len(b0)==len(b1)) and (len(b0)==len(b2)) and (len(b0)==len(b3))):
185|                     raise RuntimeError(f'File is not a QWORD file!')
186|                 # Load multiple bytes (in specified order)...
187|                 if self.le_or_be == 'LE':
188|                     quads = [(a<<24)+(b<<16)+(c<<8)+d for a,b,c,d in zip(b0,b1,b2,b3)]
189|                 else:
190|                     quads = [(a<<24)+(b<<16)+(c<<8)+d for a,b,c,d in zip(b3,b2,b1,b0)]
191|                 # Build output line...
192|                 data = ' '.join(f'{cx:08x}' for cx in quads)
193|                 # Handle short row...
194|                 missing = (self.row_size - len(self.row)) // 4
195|                 if 0 < missing:
196|                     data += (' '*9)*missing
197|             case _:
198|                 raise ValueError(f'Illegal data size: {self.data_size} (must be 1,2, or 4)')
199| 
200|         # Generate character output...
201|         chrs = ''.join([cx2ch(cx) for cx in self.row])
202|         missing = self.row_size - len(self.row)
203|         chrs += ' '*missing
204| 
205|         # Create output row...
206|         row = f'{addr}: {data} |{chrs}|\n'
207|         self.char_ctr += 1
208|         self.buf = [ipo_token(ch,self.char_ctr,ix,str(ix)) for ix,ch in enumerate(row,start=1)]
209|         self.row = []
210|         self.line_ctr += self.row_size
211| 
212| 
213| ####################################################################################################
214| if __name__ == '__main__':
215|     print()
216|     ipos = []
217| 
218|     ipos.append(ipo_proc_hexout())
219|     ipos.append(ipo_proc_hexdump())
220|     ipos.append(None)
221| 
222|     for ix,obj in enumerate(ipos):
223|         if obj is None:
224|             print()
225|             continue
226|         print(f'{ix:2d}: {obj!s}')
227|         obj.start(None)
228|     print()
229| ####################################################################################################
230| """eof"""
231|