"""Convert data into raw bytes."""from__future__importannotationsimporttypingfromcable_club.constantsimportUTF8iftyping.TYPE_CHECKING:fromsocketimportsocketfromcable_club.networkimportClient
[docs]classWriter:"""Format some data to be sent."""def__init__(self)->None:"""Initialize an instance."""self.fields:list[str]=[]
[docs]defsend_now(self,socket:socket)->int:"""Send variable over the wire."""line=",".join(Writer.escape(f)forfinself.fields)line+="\n"returnsocket.send(line.encode(UTF8))
[docs]defsend(self,client:Client)->None:"""Get data into buffer to be later sent."""line=",".join(Writer.escape(f)forfinself.fields)line+="\n"client.send_buffer+=line.encode(UTF8)
[docs]@staticmethoddefescape(raw:str)->str:"""Escape special symbols in a raw string."""returnraw.replace("\\","\\\\").replace(",","\\,")
[docs]defadd(self,f:object)->None:"""Add a field to the writer."""self.fields.append(str(f))
[docs]defadd_raw(self,fs:list[str])->None:"""Add raw fields to the writer."""self.fields.extend(fs)