New implementation for generate_test_code.FileWrapper

We get some performance benefit from the Buffered I/O.

Signed-off-by: Pengyu Lv <pengyu.lv@arm.com>
This commit is contained in:
Pengyu Lv 2023-04-19 15:03:20 +08:00
parent 8e6794ad56
commit 7a344dde0f

View file

@ -163,7 +163,6 @@ __MBEDTLS_TEST_TEMPLATE__PLATFORM_CODE
""" """
import io
import os import os
import re import re
import sys import sys
@ -208,43 +207,57 @@ class GeneratorInputError(Exception):
pass pass
class FileWrapper(io.FileIO): class FileWrapper:
""" """
This class extends built-in io.FileIO class with attribute line_no, This class extends the file object with attribute line_no,
that indicates line number for the line that is read. that indicates line number for the line that is read.
""" """
def __init__(self, file_name): def __init__(self, file_name) -> None:
""" """
Instantiate the base class and initialize the line number to 0. Instantiate the file object and initialize the line number to 0.
:param file_name: File path to open. :param file_name: File path to open.
""" """
super().__init__(file_name, 'r') # private mix-in file object
self._f = open(file_name, 'rb')
self._line_no = 0 self._line_no = 0
def __iter__(self):
return self
def __next__(self): def __next__(self):
""" """
This method overrides base class's __next__ method and extends it This method makes FileWrapper iterable.
method to count the line numbers as each line is read. It counts the line numbers as each line is read.
:return: Line read from file. :return: Line read from file.
""" """
line = super().__next__() line = self._f.__next__()
if line is not None:
self._line_no += 1 self._line_no += 1
# Convert byte array to string with correct encoding and # Convert byte array to string with correct encoding and
# strip any whitespaces added in the decoding process. # strip any whitespaces added in the decoding process.
return line.decode(sys.getdefaultencoding()).rstrip()+ '\n' return line.decode(sys.getdefaultencoding()).rstrip()+ '\n'
return None
def get_line_no(self): def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._f.__exit__(exc_type, exc_val, exc_tb)
@property
def line_no(self):
""" """
Gives current line number. Property that indicates line number for the line that is read.
""" """
return self._line_no return self._line_no
line_no = property(get_line_no) @property
def name(self):
"""
Property that indicates name of the file that is read.
"""
return self._f.name
def split_dep(dep): def split_dep(dep):