Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // We use a vector of binary keys on a key-valute store, we need a separator for partial key searches.
- // We convert the vector of keys to 7 bit and use the unused bit as a separator.
- // convert_to_7_bit: Converts a field to 7-bit representation.
- // get_binary_key: Creates a binary key from an array of byte fields.
- // convert_from_7_bit: Converts a 7-bit representation back to the original field.
- // get_fields_from_key: Extracts the original fields from a binary key.
- fn convert_to_7_bit(field: &[u8]) -> Vec<u8> {
- let mut result = Vec::new();
- let mut carry = 0;
- let mut carry_bits = 0;
- for byte in field {
- let bits = ((byte as u16) << carry_bits) | carry;
- carry = (bits >> 7) as u8;
- carry_bits += 1;
- result.push((bits & 0x7F) as u8);
- if carry_bits == 7 {
- result.push(carry);
- carry = 0;
- carry_bits = 0;
- }
- }
- if carry_bits > 0 {
- result.push(carry);
- }
- result
- }
- fn get_binary_key(fields: &[&[u8]]) -> Vec<u8> {
- let delimiter = 0b10000000u8; // Delimiter byte (0x80)
- let mut key = Vec::new();
- for field in fields {
- let converted_field = convert_to_7_bit(field);
- key.extend_from_slice(&converted_field);
- key.push(delimiter);
- }
- // key.pop(); // Not removing enables partial key search for all cases
- key
- }
- fn convert_from_7_bit(encoded: &[u8]) -> Vec<u8> {
- let mut result = Vec::new();
- let mut carry = 0;
- let mut carry_bits = 0;
- for byte in encoded {
- let bits = (u16::from(byte) << carry_bits) | carry;
- carry = bits & ((1 << carry_bits) - 1);
- carry_bits += 1;
- result.push((bits >> carry_bits) as u8);
- if carry_bits == 7 {
- carry_bits = 0;
- }
- }
- result
- }
- fn get_fields_from_key(key: &[u8]) -> Vec<Vec<u8>> {
- let delimiter = 0b10000000u8;
- let mut fields = Vec::new();
- let mut start = 0;
- for (i, byte) in key.iter().enumerate() {
- if *byte == delimiter {
- let field = convert_from_7_bit(&key[start..i]);
- fields.push(field);
- start = i + 1;
- }
- }
- fields
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement