1
1
from contextlib import asynccontextmanager
2
- from typing import Optional , List
2
+ from typing import Optional , List , Union
3
3
4
4
from .base import BaseSubAPI
5
+ from ..errors import LuaException
5
6
from ..lua import lua_args
6
- from ..rproc import boolean , string , integer , nil , array_string , option_string , fact_scheme_dict
7
+ from ..rproc import boolean , string , integer , nil , array_string , option_string , option_integer , fact_scheme_dict
7
8
8
9
9
10
attribute = fact_scheme_dict ({
14
15
}, {})
15
16
16
17
18
+ class SeekMixin :
19
+ async def seek (self , whence : str = None , offset : int = None ) -> int :
20
+ # whence: set, cur, end
21
+ r = await self ._send ('seek' , whence , offset )
22
+ if isinstance (r , list ):
23
+ assert r [0 ] is False
24
+ raise LuaException (r [1 ])
25
+ return integer (r )
26
+
27
+
17
28
class ReadHandle (BaseSubAPI ):
18
- async def read (self , count : int ) -> Optional [str ]:
19
- return option_string (await self ._send ('read' , count ))
29
+ async def read (self , count : int = None ) -> Optional [Union [str , int ]]:
30
+ r = await self ._send ('read' , count )
31
+ return option_integer (r ) if count is None else option_string (r )
20
32
21
33
async def readLine (self ) -> Optional [str ]:
22
34
return option_string (await self ._send ('readLine' ))
@@ -34,6 +46,10 @@ async def __anext__(self):
34
46
return line
35
47
36
48
49
+ class BinaryReadHandle (ReadHandle , SeekMixin ):
50
+ pass
51
+
52
+
37
53
class WriteHandle (BaseSubAPI ):
38
54
async def write (self , text : str ):
39
55
return nil (await self ._send ('write' , text ))
@@ -45,6 +61,10 @@ async def flush(self):
45
61
return nil (await self ._send ('flush' ))
46
62
47
63
64
+ class BinaryWriteHandle (WriteHandle , SeekMixin ):
65
+ pass
66
+
67
+
48
68
class FSAPI (BaseSubAPI ):
49
69
async def list (self , path : str ) -> List [str ]:
50
70
return array_string (await self ._send ('list' , path ))
@@ -103,7 +123,11 @@ async def open(self, path: str, mode: str):
103
123
)
104
124
fin_tpl = '{e}.close()'
105
125
async with self ._cc ._create_temp_object (create_expr , fin_tpl ) as var :
106
- yield (ReadHandle if 'r' in mode else WriteHandle )(self ._cc , var )
126
+ if 'b' in mode :
127
+ hcls = BinaryReadHandle if 'r' in mode else BinaryWriteHandle
128
+ else :
129
+ hcls = ReadHandle if 'r' in mode else WriteHandle
130
+ yield hcls (self ._cc , var )
107
131
108
132
async def find (self , wildcard : str ) -> List [str ]:
109
133
return array_string (await self ._send ('find' , wildcard ))
0 commit comments