added index_of_with_escape function

This commit is contained in:
2024-11-11 06:06:22 +08:00
parent 37591f78d9
commit 36f7031fea
3 changed files with 65 additions and 2 deletions

View File

@@ -9,6 +9,7 @@ from .private import (
classproperty, classproperty,
AsyncQueueIterator, AsyncQueueIterator,
aenumerate, aenumerate,
index_of_with_escape
) )
from .maybe import Maybe from .maybe import Maybe
from .notification import TopicManager, Subscriber from .notification import TopicManager, Subscriber
@@ -28,5 +29,6 @@ __all__ = [
'Subscriber', 'Subscriber',
'AsyncQueueIterator', 'AsyncQueueIterator',
'aenumerate', 'aenumerate',
'Try' 'Try',
'index_of_with_escape'
] ]

View File

@@ -252,3 +252,32 @@ class aenumerate[T](AsyncIterator[Tuple[int, T]]):
val = await self._ait.__anext__() val = await self._ait.__anext__()
self._i += 1 self._i += 1
return self._i, val return self._i, val
def index_of_with_escape(haystack: str, needle: str, escape: str, begin: int, end: int = 0) -> int:
result = -1
cursor = begin
if end == 0:
end = len(haystack)
escape_count = 0
while cursor < end:
c = haystack[cursor]
if escape_count > 0:
escape_count -= 1
if c == escape:
result = -1
elif escape_count == 0:
if c == escape:
escape_count += 1
if c == needle:
result = cursor
if result >= 0 and escape_count == 0:
break
cursor += 1
return result

View File

@@ -1,6 +1,6 @@
import unittest import unittest
from pwo import retry, async_retry, async_test, AsyncQueueIterator, aenumerate from pwo import retry, async_retry, async_test, AsyncQueueIterator, aenumerate, index_of_with_escape
from asyncio import Queue from asyncio import Queue
@@ -93,3 +93,35 @@ class PrivateTest(unittest.TestCase):
self.assertEqual(queue_size, processed) self.assertEqual(queue_size, processed)
class TestIndexOfWithEscape(unittest.TestCase):
def run_test_case(self, haystack, needle, escape, expected_solution):
solution = []
i = 0
while True:
i = index_of_with_escape(haystack, needle, escape, i, len(haystack))
if i < 0:
break
solution.append(i)
i += 1
self.assertEqual(solution, expected_solution)
def test_simple(self):
self.run_test_case(" dsds $sdsa \\$dfivbdsf \\\\$sdgsga", '$', '\\', [6, 25])
def test_simple2(self):
self.run_test_case("asdasd$$vdfv$", '$', '$', [12])
def test_no_needle(self):
self.run_test_case("asdasd$$vdfv$", '#', '\\', [])
def test_escaped_needle(self):
self.run_test_case("asdasd$$vdfv$#sdfs", '#', '$', [])
def test_not_escaped_needle(self):
self.run_test_case("asdasd$$#vdfv$#sdfs", '#', '$', [8])
def test_special_case(self):
self.run_test_case("\n${sys:user.home}${env:HOME}", ':', '\\', [6, 22])