3 SLj~o@sdZdZddlZddlZddlmZdZe ZddZdd Z d d Z d d Z ddZ ddZ e e ZZZe eZZe e ejZZe dZZZe dZZZe dZddZddZddZddZ ddZ!dd Z"d!d"Z#d#d$Z$e#Z%e$Z&d%d&Z'd'd(Z(d)d*Z)d+d,Z*d-d.Z+d/d0Z,e)ej-e&e Z.Z/Z0e)ej-e%eZ1Z2e*ej-e%eejZ3Z4e+ej5d1Z6e+ej7d2Z8e+ej5d3Z9e+ej7d4Z:e,ej5d5Z;e,ej7d6Zd;d<Z?d=d>Z@d?d@ZAdAdBZBdCdDZCdS)EaCode for encoding protocol message primitives. Contains the logic for encoding every logical protocol field type into one of the 5 physical wire types. This code is designed to push the Python interpreter's performance to the limits. The basic idea is that at startup time, for every field (i.e. every FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The sizer takes a value of this field's type and computes its byte size. The encoder takes a writer function and a value. It encodes the value into byte strings and invokes the writer function to write those strings. Typically the writer function is the write() method of a BytesIO. We try to do as much work as possible when constructing the writer and the sizer rather than when calling them. In particular: * We copy any needed global functions to local variables, so that we do not need to do costly global table lookups at runtime. * Similarly, we try to do any attribute lookups at startup time if possible. * Every field's tag is encoded to bytes at startup, since it can't change at runtime. * Whatever component of the field size we can compute at startup, we do. * We *avoid* sharing code if doing so would make the code slower and not sharing does not burden us too much. For example, encoders for repeated fields do not just call the encoders for singular fields in a loop because this would add an extra function call overhead for every loop iteration; instead, we manually inline the single-value encoder into the loop. * If a Python function lacks a return statement, Python actually generates instructions to pop the result of the last statement off the stack, push None onto the stack, and then return that. If we really don't care what value is returned, then we can save two instructions by returning the result of the last statement. It looks funny but it helps. * We assume that type and bounds checking has happened at a higher level. z kenton@google.com (Kenton Varda)N) wire_formatgcCsp|dkr dS|dkrdS|dkr$dS|dkr0dS|d kr.SpecificSizer..PackedFieldSizecs*t|}x|D]}||7}qW|S)N)len)rrr)rrrrRepeatedFieldSizes  z>_SimpleSizer..SpecificSizer..RepeatedFieldSizecs |S)Nr)r)rrrr FieldSizesz6_SimpleSizer..SpecificSizer..FieldSize)rr)r is_repeated is_packedrrr)r)rrr SpecificSizersz#_SimpleSizer..SpecificSizerr)rr!r)rr _SimpleSizer~s r"csfdd}|S)zLike SimpleSizer, but modify_value is invoked on each value before it is passed to compute_value_size. modify_value is typically ZigZagEncode.csVt||r&tfdd}|S|r>fdd}|Sfdd}|SdS)Ncs2d}x|D]}||7}q W||S)Nrr)rrr)rr modify_valuerrrrs z>_ModifiedSizer..SpecificSizer..PackedFieldSizecs.t|}x|D]}||7}qW|S)N)r)rrr)rr#rrrrs  z@_ModifiedSizer..SpecificSizer..RepeatedFieldSizecs|S)Nr)r)rr#rrrrsz8_ModifiedSizer..SpecificSizer..FieldSize)rr)rrr rrr)rr#)rrrr!sz%_ModifiedSizer..SpecificSizerr)rr#r!r)rr#r_ModifiedSizersr$csfdd}|S)zWLike _SimpleSizer except for a fixed-size field. The input is the size of one value.cs\t||r$tfdd}|S|r@fdd}|Sfdd}|SdS)Ncst|}||S)N)r)rr)rr value_sizerrrs z;_FixedSizer..SpecificSizer..PackedFieldSizecs t|S)N)r)r) element_sizerrrsz=_FixedSizer..SpecificSizer..RepeatedFieldSizecsS)Nr)r) field_sizerrrsz5_FixedSizer..SpecificSizer..FieldSize)rr)rrr rrr)r%)r&r'rrrr!s  z"_FixedSizer..SpecificSizerr)r%r!r)r%r _FixedSizers r(rr rcsJt|tt| st|r2fdd}|Sfdd}|SdS)z#Returns a sizer for a string field.cs<t|}x*|D]"}|jd}|||7}qW|S)Nzutf-8)rencode)rrrl)r local_lenrrrrs   z&StringSizer..RepeatedFieldSizecs|jd}||S)Nzutf-8)r))rr*)rr+rrrrszStringSizer..FieldSizeN)rrrAssertionError)rrr rrr)rr+rr StringSizers r-csJt|tt| st|r2fdd}|Sfdd}|SdS)z"Returns a sizer for a bytes field.cs6t|}x$|D]}|}|||7}qW|S)N)r)rrrr*)rr+rrrrs   z%BytesSizer..RepeatedFieldSizecs|}||S)Nr)rr*)rr+rrrr szBytesSizer..FieldSizeN)rrrr,)rrr rrr)rr+rr BytesSizers r.cs>t|d| st|r*fdd}|Sfdd}|SdS)z"Returns a sizer for a group field.rcs*t|}x|D]}||j7}qW|S)N)rByteSize)rrr)rrrrs  z%GroupSizer..RepeatedFieldSizecs |jS)N)r/)r)rrrrszGroupSizer..FieldSizeN)rr,)rrr rrr)rr GroupSizers    r0csBt|t| st|r,fdd}|Sfdd}|SdS)z$Returns a sizer for a message field.cs6t|}x$|D]}|j}|||7}qW|S)N)rr/)rrrr*)rrrrr+s   z'MessageSizer..RepeatedFieldSizecs|j}||S)N)r/)rr*)rrrrr3szMessageSizer..FieldSizeN)rrr,)rrr rrr)rrr MessageSizer$s r1cs:tddtdt|tdtfdd}|S)zReturns a sizer for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } rrrcs|j}||S)N)r/)rr*)r static_sizerrrLsz&MessageSetItemSizer..FieldSize)rr)rrr)rr2rMessageSetItemSizer=s  r3cs(|jt|jddfdd}|S)z Returns a sizer for a map field.FcsDd}x:|D]2}||}j||d}||7}r |jq W|S)Nr)keyr)_concrete_classr/)Z map_valueZtotalr4r entry_msg)is_message_map message_sizer message_typerrr_s   zMapSizer..FieldSize)r9r1number)field_descriptorr7rr)r7r8r9rMapSizerWsr<cCs dd}|S)zBReturn an encoder for a basic varint value (does not include tag).cSsJ|d@}|dL}x*|r:|tjd|B|d@}|dL}qW|tj|S)Nrr )sixint2byte)writerunused_deterministicbitsrrr EncodeVarintws z$_VarintEncoder..EncodeVarintr)rCrrr_VarintEncoderts rDcCs dd}|S)zKReturn an encoder for a basic signed varint value (does not include tag).cSsZ|dkr|d7}|d@}|dL}x*|rJ|tjd|B|d@}|dL}q"W|tj|S)Nrr@rr r=l)r>r?)r@rrArBrrrEncodeSignedVarints z0_SignedVarintEncoder..EncodeSignedVarintr)rFrrr_SignedVarintEncoders rGcCsg}t|j|ddj|S)zEncode the given integer as a varint and return the bytes. This is only called at startup time so it doesn't need to be fast.T) _EncodeVarintappendjoin)rpiecesrrr _VarintBytessrMcCstjttj||S)zCEncode the given tag and return the bytes. Only called at startup.)r>Z binary_typerMrr)r wire_typerrrTagBytessrOcsfdd}|S)a_Return a constructor for an encoder for fields of a particular type. Args: wire_type: The field's wire type, for encoding tags. encode_value: A function which encodes an individual value, e.g. _EncodeVarint(). compute_value_size: A function which computes the size of an individual value, e.g. _VarintSize(). csj|r*t|tjtfdd}|S|rJt|fdd}|St|fdd}|SdS)NcsP|d}x|D]}||7}qW|||x|D]}|||q8WdS)Nrr)r@r deterministicsizer)r encode_valuelocal_EncodeVarint tag_bytesrrEncodePackedFields   zB_SimpleEncoder..SpecificEncoder..EncodePackedFieldcs&x |D]}||||qWdS)Nr)r@rrPr)rRrTrrEncodeRepeatedFields zD_SimpleEncoder..SpecificEncoder..EncodeRepeatedFieldcs||||S)Nr)r@rrP)rRrTrr EncodeFieldsz<_SimpleEncoder..SpecificEncoder..EncodeField)rOrWIRETYPE_LENGTH_DELIMITEDrI)rrr rUrVrW)rrRrN)rSrTrSpecificEncoders   z'_SimpleEncoder..SpecificEncoderr)rNrRrrYr)rrRrNr_SimpleEncoders rZcsfdd}|S)zLike SimpleEncoder but additionally invokes modify_value on every value before passing it to encode_value. Usually modify_value is ZigZagEncode.csp|r,t|tjtfdd}|S|rNt|fdd}|St|fdd}|SdS)NcsX|d}x|D]}||7}qW|||x|D]}|||q.SpecificEncoder..EncodePackedFieldcs*x$|D]}||||qWdS)Nr)r@rrPr)rRr#rTrrrVs zF_ModifiedEncoder..SpecificEncoder..EncodeRepeatedFieldcs||||S)Nr)r@rrP)rRr#rTrrrWsz>_ModifiedEncoder..SpecificEncoder..EncodeField)rOrrXrI)rrr rUrVrW)rrRr#rN)rSrTrrYs   z)_ModifiedEncoder..SpecificEncoderr)rNrRrr#rYr)rrRr#rNr_ModifiedEncodersr[cstjfdd}|S)zReturn a constructor for an encoder for a fixed-width field. Args: wire_type: The field's wire type, for encoding tags. format: The format string to pass to struct.pack(). csvtj|r2t|tjtfdd}|S|rTt|fdd}|St|fdd}|SdS)Ncs<||t||x|D]}||q"WdS)N)r)r@rrPr)formatrSlocal_struct_packrTr%rrrUs zF_StructPackEncoder..SpecificEncoder..EncodePackedFieldcs(x"|D]}|||qWdS)Nr)r@rrAr)r\r]rTrrrVs zH_StructPackEncoder..SpecificEncoder..EncodeRepeatedFieldcs|||S)Nr)r@rrA)r\r]rTrrrWsz@_StructPackEncoder..SpecificEncoder..EncodeField)structpackrOrrXrI)rrr rUrVrW)r\r%rN)rSr]rTrrYs   z+_StructPackEncoder..SpecificEncoder)r^calcsize)rNr\rYr)r\r%rNr_StructPackEncoders racsPtjdkrddndkr.ddn tdfdd}|S) aqReturn a constructor for an encoder for float fields. This is like StructPackEncoder, but catches errors that may be due to passing non-finite floating-point values to struct.pack, and makes a second attempt to encode those values. Args: wire_type: The field's wire type, for encoding tags. format: The format string to pass to struct.pack(). rcSs<|tkr|dn&|tkr$|dn||kr6|dndS)Nsss)_POS_INF_NEG_INF)r@rrrrEncodeNonFiniteOrRaise+s   z5_FloatingPointEncoder..EncodeNonFiniteOrRaiser cSs<|tkr|dn&|tkr$|dn||kr6|dndS)Nsss)rbrc)r@rrrrrd6s   zGCan't encode floating-point values that are %d bytes long (only 4 or 8)cs|tj|r4t|tjtfdd}|S|rXt|fdd}|St|fdd}|SdS)Nc s`||t||x>|D]6}y||Wq"tk rV||Yq"Xq"WdS)N)r SystemError)r@rrPr)rdr\rSr]rTr%rrrUHs zI_FloatingPointEncoder..SpecificEncoder..EncodePackedFieldc sLxF|D]>}|y||Wqtk rB||YqXqWdS)N)re)r@rrAr)rdr\r]rTrrrVUs  zK_FloatingPointEncoder..SpecificEncoder..EncodeRepeatedFieldc s>|y||Wntk r8||YnXdS)N)re)r@rrA)rdr\r]rTrrrW_s zC_FloatingPointEncoder..SpecificEncoder..EncodeField)r^r_rOrrXrI)rrr rUrVrW)rdr\r%rN)rSr]rTrrYCs    z._FloatingPointEncoder..SpecificEncoder)r^r` ValueError)rNr\rYr)rdr\r%rNr_FloatingPointEncoders   $rgz.EncodePackedFieldcs0x*|D]"}||r |q|qWdS)Nr)r@rrAr)rjrTrkrrrVs   z(BoolEncoder..EncodeRepeatedFieldcs||r|S|S)Nr)r@rrA)rjrTrkrrrWsz BoolEncoder..EncodeFieldN)rOrrXrIWIRETYPE_VARINT)rrr rUrVrWr)rjrSrTrkr BoolEncoders   rmcsNt|tjtt| st|r6fdd}|Sfdd}|SdS)z&Returns an encoder for a string field.cs<x6|D].}|jd}||||||qWdS)Nzutf-8)r))r@rrPrencoded)rSr+tagrrrVs   z*StringEncoder..EncodeRepeatedFieldcs*|jd}||||||S)Nzutf-8)r))r@rrPrn)rSr+rorrrWs z"StringEncoder..EncodeFieldN)rOrrXrIrr,)rrr rVrWr)rSr+ror StringEncoders  rpcsNt|tjtt| st|r6fdd}|Sfdd}|SdS)z%Returns an encoder for a bytes field.cs2x,|D]$}||||||qWdS)Nr)r@rrPr)rSr+rorrrVs z)BytesEncoder..EncodeRepeatedFieldcs ||||||S)Nr)r@rrP)rSr+rorrrWsz!BytesEncoder..EncodeFieldN)rOrrXrIrr,)rrr rVrWr)rSr+ror BytesEncoders  rqcsNt|tjt|tj| s"t|r8fdd}|Sfdd}|SdS)z%Returns an encoder for a group field.cs.x(|D] }||j|||qWdS)N)_InternalSerialize)r@rrPr)end_tag start_tagrrrVs  z)GroupEncoder..EncodeRepeatedFieldcs||j|||S)N)rr)r@rrP)rsrtrrrWs z!GroupEncoder..EncodeFieldN)rOrWIRETYPE_START_GROUPWIRETYPE_END_GROUPr,)rrr rVrWr)rsrtr GroupEncoders   rwcsFt|tjt| st|r0fdd}|Sfdd}|SdS)z'Returns an encoder for a message field.cs6x0|D](}|||j||j||qWdS)N)r/rr)r@rrPr)rSrorrrVs z+MessageEncoder..EncodeRepeatedFieldcs$|||j||j||S)N)r/rr)r@rrP)rSrorrrWsz#MessageEncoder..EncodeFieldN)rOrrXrIr,)rrr rVrWr)rSrorMessageEncoders  rxcsRdjtdtjtdtjt|tdtjgtdtjtfdd}|S)zEncoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } rHrrrcs,|||j||j|||S)N)r/rr)r@rrP) end_bytesrS start_bytesrrrWs z*MessageSetItemEncoder..EncodeField) rKrOrrurlrMrXrvrI)rrWr)ryrSrzrMessageSetItemEncoders    r{cs&|jt|jddfdd}|S)zEncoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N; FcsD|rt|jn|}x*|D]"}j|||d}|||qWdS)N)r4r)sortedkeysr5)r@rrPZ value_keysr4r6)encode_messager9rrrW5s zMapEncoder..EncodeField)r9rxr:)r;rWr)r~r9r MapEncoder&s r)D__doc__ __author__r^r>Zgoogle.protobuf.internalrrbrcrrrr"r$r(Z Int32SizerZ Int64SizerZ EnumSizerZ UInt32SizerZ UInt64SizerZ ZigZagEncodeZ SInt32SizerZ SInt64SizerZ Fixed32SizerZ SFixed32SizerZ FloatSizerZ Fixed64SizerZ SFixed64SizerZ DoubleSizerZ BoolSizerr-r.r0r1r3r<rDrGrIZ_EncodeSignedVarintrMrOrZr[rargrlZ Int32EncoderZ Int64EncoderZ EnumEncoderZ UInt32EncoderZ UInt64EncoderZ SInt32EncoderZ SInt64EncoderZWIRETYPE_FIXED32ZFixed32EncoderZWIRETYPE_FIXED64ZFixed64EncoderZSFixed32EncoderZSFixed64EncoderZ FloatEncoderZ DoubleEncoderrmrprqrwrxr{rrrrrAsn !   )"&R       %