MCPcopy Create free account
hub / github.com/apache/fory / _encode_generic

Method _encode_generic

python/pyfory/meta/metastring.py:502–528  ·  view source on GitHub ↗

Generic encoding function for encoding characters into bytes. Args: chars (list): The characters to encode. bits_per_char (int): The number of bits per character. Returns: bytes: The encoded data.

(self, chars: List[str], bits_per_char: int)

Source from the content-addressed store, hash-verified

500 return self._encode_generic(new_chars, 5)
501
502 def _encode_generic(self, chars: List[str], bits_per_char: int) -> bytes:
503 """
504 Generic encoding function for encoding characters into bytes.
505
506 Args:
507 chars (list): The characters to encode.
508 bits_per_char (int): The number of bits per character.
509
510 Returns:
511 bytes: The encoded data.
512 """
513 total_bits = len(chars) * bits_per_char + 1
514 byte_length = (total_bits + 7) // 8
515 bytes_array = bytearray(byte_length)
516 current_bit = 1
517 for c in chars:
518 value = self._char_to_value(c, bits_per_char)
519 for i in range(bits_per_char - 1, -1, -1):
520 if (value & (1 << i)) != 0:
521 byte_pos = current_bit // 8
522 bit_pos = current_bit % 8
523 bytes_array[byte_pos] |= 1 << (7 - bit_pos)
524 current_bit += 1
525 strip_last_char = len(bytes_array) * 8 >= total_bits + bits_per_char
526 if strip_last_char:
527 bytes_array[0] = bytes_array[0] | 0x80
528 return bytes(bytes_array)
529
530 def _char_to_value(self, c: str, bits_per_char: int) -> int:
531 """

Calls 1

_char_to_valueMethod · 0.95

Tested by

no test coverage detected