Skip to content

Commit 3f6e951

Browse files
XXIN0XXIN
andauthored
Improve the "ASCReader" read performance. (#1717)
* Update asc.py improve the "ASCReader" performance. * Update asc.py Fix: the test error "error: Item "None" of "Optional[Match[str]]" has no attribute "group" [union-attr]" * Update asc.py style: format code with "Black Code Formatter" * improvement: make regular expression compile result as module constants. * style:format import --------- Co-authored-by: XXIN <[email protected]>
1 parent 35eef6e commit 3f6e951

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

can/io/asc.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import re
1010
import time
1111
from datetime import datetime
12-
from typing import Any, Dict, Generator, List, Optional, TextIO, Union
12+
from typing import Any, Dict, Final, Generator, List, Optional, TextIO, Union
1313

1414
from ..message import Message
1515
from ..typechecking import StringPathLike
@@ -20,6 +20,14 @@
2020
CAN_ID_MASK = 0x1FFFFFFF
2121
BASE_HEX = 16
2222
BASE_DEC = 10
23+
ASC_TRIGGER_REGEX: Final = re.compile(
24+
r"begin\s+triggerblock\s+\w+\s+(?P<datetime_string>.+)", re.IGNORECASE
25+
)
26+
ASC_MESSAGE_REGEX: Final = re.compile(
27+
r"\d+\.\d+\s+(\d+\s+(\w+\s+(Tx|Rx)|ErrorFrame)|CANFD)",
28+
re.ASCII | re.IGNORECASE,
29+
)
30+
2331

2432
logger = logging.getLogger("can.io.asc")
2533

@@ -258,12 +266,7 @@ def __iter__(self) -> Generator[Message, None, None]:
258266
for _line in self.file:
259267
line = _line.strip()
260268

261-
trigger_match = re.match(
262-
r"begin\s+triggerblock\s+\w+\s+(?P<datetime_string>.+)",
263-
line,
264-
re.IGNORECASE,
265-
)
266-
if trigger_match:
269+
if trigger_match := ASC_TRIGGER_REGEX.match(line):
267270
datetime_str = trigger_match.group("datetime_string")
268271
self.start_time = (
269272
0.0
@@ -272,11 +275,7 @@ def __iter__(self) -> Generator[Message, None, None]:
272275
)
273276
continue
274277

275-
if not re.match(
276-
r"\d+\.\d+\s+(\d+\s+(\w+\s+(Tx|Rx)|ErrorFrame)|CANFD)",
277-
line,
278-
re.ASCII | re.IGNORECASE,
279-
):
278+
if not ASC_MESSAGE_REGEX.match(line):
280279
# line might be a comment, chip status,
281280
# J1939 message or some other unsupported event
282281
continue

0 commit comments

Comments
 (0)