Skip to content

Commit 49f4537

Browse files
committed
feat(core): trim strings to specific bytes' limit
[no changelog]
1 parent 3dca4d8 commit 49f4537

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

core/src/trezor/strings.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,16 @@ def format_autolock_duration(auto_lock_ms: int) -> str:
153153
auto_lock_label = TR.plurals__lock_after_x_seconds
154154

155155
return format_plural("{count} {plural}", auto_lock_num, auto_lock_label)
156+
157+
158+
def trim_str(s: str, max_bytes: int) -> str:
159+
"""
160+
Trim a string, so the result's byte size will be less or equal to `max_bytes`.
161+
"""
162+
assert max_bytes >= 0
163+
for i, char in enumerate(s):
164+
char_size = len(char.encode())
165+
if max_bytes < char_size:
166+
return s[:i]
167+
max_bytes -= char_size
168+
return s

core/tests/test_trezor.strings.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,27 @@ def test_format_timestamp(self):
222222

223223
strings.format_timestamp(1616057224)
224224

225+
def test_trim_str(self):
226+
# test ASCII
227+
self.assertEqual(strings.trim_str("123", 4), "123")
228+
self.assertEqual(strings.trim_str("123", 3), "123")
229+
self.assertEqual(strings.trim_str("123", 2), "12")
230+
self.assertEqual(strings.trim_str("123", 1), "1")
231+
self.assertEqual(strings.trim_str("123", 0), "")
232+
233+
# test non-ASCII
234+
self.assertEqual(strings.trim_str("➀➁➂", 10), "➀➁➂")
235+
self.assertEqual(strings.trim_str("➀➁➂", 9), "➀➁➂")
236+
self.assertEqual(strings.trim_str("➀➁➂", 8), "➀➁")
237+
self.assertEqual(strings.trim_str("➀➁➂", 7), "➀➁")
238+
self.assertEqual(strings.trim_str("➀➁➂", 6), "➀➁")
239+
self.assertEqual(strings.trim_str("➀➁➂", 5), "➀")
240+
self.assertEqual(strings.trim_str("➀➁➂", 4), "➀")
241+
self.assertEqual(strings.trim_str("➀➁➂", 3), "➀")
242+
self.assertEqual(strings.trim_str("➀➁➂", 2), "")
243+
self.assertEqual(strings.trim_str("➀➁➂", 1), "")
244+
self.assertEqual(strings.trim_str("➀➁➂", 0), "")
245+
225246

226247
if __name__ == "__main__":
227248
unittest.main()

0 commit comments

Comments
 (0)