From: Eli Bendersky Date: Sun, 27 Nov 2011 04:34:47 +0000 (+0200) Subject: some performance improvements X-Git-Tag: v0.10~65 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=4a48975ea779af405fe919db7a5f2d7b815e8c69;p=pyelftools.git some performance improvements --- diff --git a/elftools/common/utils.py b/elftools/common/utils.py index 2b55e5e..2ce6746 100644 --- a/elftools/common/utils.py +++ b/elftools/common/utils.py @@ -32,6 +32,20 @@ def struct_parse(struct, stream, stream_pos=None): raise ELFParseError(e.message) +def parse_cstring_from_stream(stream, stream_pos=None): + """ Parse a C-string from the given stream. The string is returned without + the terminating \x00 byte. + If stream_pos is provided, the stream is seeked to this position before + the parsing is done. Otherwise, the current position of the stream is + used. + """ + # I could've just used construct.CString, but this function is 4x faster. + # Since it's needed a lot, I created it as an optimization. + if stream_pos is not None: + stream.seek(stream_pos) + return ''.join(iter(lambda: stream.read(1), '\x00')) + + def elf_assert(cond, msg=''): """ Assert that cond is True, otherwise raise ELFError(msg) """ diff --git a/elftools/dwarf/dwarfinfo.py b/elftools/dwarf/dwarfinfo.py index bfbba8d..db42017 100644 --- a/elftools/dwarf/dwarfinfo.py +++ b/elftools/dwarf/dwarfinfo.py @@ -10,7 +10,8 @@ from collections import namedtuple from ..construct import CString from ..common.exceptions import DWARFError -from ..common.utils import struct_parse, dwarf_assert +from ..common.utils import (struct_parse, dwarf_assert, + parse_cstring_from_stream) from .structs import DWARFStructs from .compileunit import CompileUnit from .abbrevtable import AbbrevTable @@ -115,10 +116,7 @@ class DWARFInfo(object): """ Obtain a string from the string table section, given an offset relative to the section. """ - return struct_parse( - CString(''), - self.debug_str_sec.stream, - stream_pos=offset) + return parse_cstring_from_stream(self.debug_str_sec.stream, offset) #------ PRIVATE ------#