Encode packet helpers for binary types
3949
function encodeArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var data = packet.data;
  var contentArray = new Uint8Array(data);
  var resultBuffer = new Uint8Array(1 + data.byteLength);

  resultBuffer[0] = packets[packet.type];
  for (var i = 0; i < contentArray.length; i++) {
    resultBuffer[i+1] = contentArray[i];
  }

  return callback(resultBuffer.buffer);
}
80427
def binary_encode_if_any_high_ascii(string)
      string = ensure_utf8(string)
      string.force_encoding('BINARY') if string.bytes.detect { |byte| byte > 127 }
      string
    end
64186
def encode_ber(value, ber_length=0):
    
    if not ber_length:
        if value < 127: # 1 byte case
            return bytearray([value])
        ber_length = 1
        while value >= pow(2, 8*ber_length):
            ber_length += 1
        ber_length += 1


    ber = bytearray(ber_length)
    ber[0] = 127 + ber_length #ber length byte
    for i in range(1, ber_length):
        ber[i] = (value >> (8 * (ber_length - 1 - i))) & 255
    return ber
715527
def encode_packet(packet: dict) -> str:
    
    if packet['protocol'] == 'rfdebug':
        return '10;RFDEBUG=' + packet['command'] + ';'
    elif packet['protocol'] == 'rfudebug':
        return '10;RFDEBUG=' + packet['command'] + ';'
    else:
        return SWITCH_COMMAND_TEMPLATE.format(
            node=PacketHeader.master.value,
            **packet
        )
550701
def decodepackbits(encoded):
    
    func = ord if sys.version[0] == '2' else lambda x: x
    result = []
    i = 0
    try:
        while True:
            n = func(encoded[i]) + 1
            i += 1
            if n < 129:
                result.extend(encoded[i:i+n])
                i += n
            elif n > 129:
                result.extend(encoded[i:i+1] * (258-n))
                i += 1
    except IndexError:
        pass
    return b''.join(result) if sys.version[0] == '2' else bytes(result)
278187
def encode(self, value):
        '''
        
        '''
        packed = pack(self.fmt, value)
        return Bits(bytes=packed)
1364700
def to_binary_string(obj, encoding=None):
    """"""
    if PY2:
        # Python 2
        if encoding is None:
            return str(obj)
        else:
            return obj.encode(encoding)
    else:
        # Python 3
        return bytes(obj, 'utf-8' if encoding is None else encoding)
53275
def Binary(x):
    """"""
    if isinstance(x, text_type) and not (JYTHON or IRONPYTHON):
        return x.encode()
    return bytes(x)
1312805
def encode_payload(cls, payload):
        ''''''
        try:
            return json.dumps(payload).encode()
        except TypeError:
            msg = f'JSON payload encoding error: {payload}'
            raise ProtocolError(cls.INTERNAL_ERROR, msg) from None
1078168
function bufferToTuples (buf) {
  const tuples = []
  let i = 0
  while (i < buf.length) {
    const code = varint.decode(buf, i)
    const n = varint.decode.bytes

    const p = protocols(code)

    const size = sizeForAddr(p, buf.slice(i + n))

    if (size === 0) {
      tuples.push([code])
      i += n
      continue
    }

    const addr = buf.slice(i + n, i + n + size)

    i += (size + n)

    if (i > buf.length) { // did not end _exactly_ at buffer.length
      throw ParseError('Invalid address buffer: ' + buf.toString('hex'))
    }

    // ok, tuple seems good.
    tuples.push([code, addr])
  }

  return tuples
}
1157578
function encodeEmbeddedBlobBuffer( encoder, buffer_type, buffer, mime_type ) {
	// Get MIME And payload
	var mime_id = encoder.stringID( mime_type );

	// Write buffer header
	encoder.log(LOG.EMB,"file=[blob]', mime="+mime+", len="+buffer.length);
	encodeBuffer( encoder, buffer_type, mime_id, buffer );

}
1318627
def encode(cls, value):
        
        try:
            coerced = bytes(value)
            if coerced == value:
                return coerced
        except (TypeError, UnicodeError):
            pass

        raise InvalidValue('not binary')
909157
function encode(buf) {
	if (buf.length != 8) {
		throw new TypeError("Buffer must be length 8");
	}

	var num = new UInt64(buf.readUInt32BE(4), buf.readUInt32BE(0));
	var str = "";
	do {
		num.div(SIXTY_TWO);
		str = CHARS[num.remainder] + str;
	} while (num.greaterThan(ZERO));

	return str;
}
971747
function makeDecoder(chunkType) {
	if (chunkType === BUFFER) {
		return function (buf) {
			return buf.toString('utf8');
		};
	}
	if (isnode) {
		return function (a) {
			return new Buffer(a).toString('utf8');
		};
	}
	var decoder = null;
	return function (buf) {
		if (!decoder) {
			decoder = new TextDecoder();
		}
		return decoder.decode(buf);
	};
}
49115
def _encode_buffer(string, f):
	""""""
	if isinstance(string, str):
		string = string.encode()
	f.write(str(len(string)).encode())
	f.write(_TYPE_SEP)
	f.write(string)
188615
def to_bytes(s, encoding="utf-8"):
    """"""
    if isinstance(s, six.binary_type):
        return s
    if six.PY3:
        return bytes(s, encoding)
    return s.encode(encoding)
475210
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):
		""""""

		timestamp = int(time())
		print("timestamp: " + str(timestamp))
		self.header = bytearray(HEADER_SIZE)
		#--------------
		# TO COMPLETE
		#--------------
		# Fill the header bytearray with RTP header fields

		#RTP-version filed(V), must set to 2
		#padding(P),extension(X),number of contributing sources(CC) and marker(M) fields all set to zero in this lab

		#Because we have no other contributing sources(field CC == 0),the CSRC-field does not exist
		#Thus the length of the packet header is therefore 12 bytes


			#Above all done in ServerWorker.py

		# ...
		#header[] =

		#header[0] = version + padding + extension + cc + seqnum + marker + pt + ssrc
		self.header[0] = version << 6
		self.header[0] = self.header[0] | padding << 5
		self.header[0] = self.header[0] | extension << 4
		self.header[0] = self.header[0] | cc
		self.header[1] = marker << 7
		self.header[1] = self.header[1] | pt

		self.header[2] = seqnum >> 8
		self.header[3] = seqnum

		self.header[4] = (timestamp >> 24) & 0xFF
		self.header[5] = (timestamp >> 16) & 0xFF
		self.header[6] = (timestamp >> 8) & 0xFF
		self.header[7] = timestamp & 0xFF

		self.header[8] = ssrc >> 24
		self.header[9] = ssrc >> 16
		self.header[10] = ssrc >> 8
		self.header[11] = ssrc


		# Get the payload from the argument
		# self.payload = ...
		self.payload = payload