1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use super::de::DeserializedDeck;

const CURRENT_VERSION: u8 = 2;
const ENCODED_PREFIX: &str = "ADC";
const HEADER_SIZE: u32 = 3;

pub fn encode(deck: &mut DeserializedDeck) -> Result<String, String> {
    let bytes = encode_bytes(deck).unwrap();

    Ok(encode_bytes_to_string(&bytes).unwrap())
}

fn encode_bytes_to_string(bytes: &Vec<u8>) -> Result<String, String> {
    let byte_count = bytes.len();
    if byte_count == 0 {
        return Err(String::from("Something broke in generating bytes"));
    }

    let encoded = base64::encode(&bytes);

    let mut deck_string = format!("{}{}", ENCODED_PREFIX, encoded);

    // make string url safe
    deck_string = deck_string
        .chars()
        .map(|x| match x {
            '/' => '-',
            '=' => '_',
            _ => x,
        })
        .collect();

    Ok(deck_string)
}

fn encode_bytes(deck: &mut DeserializedDeck) -> Result<Vec<u8>, String> {
    deck.cards.sort();
    deck.heroes.sort();

    let count_heroes = deck.heroes.len();

    let mut bytes: Vec<u8> = Vec::new();
    //our version and hero count
    let version = CURRENT_VERSION << 4 | extract_n_bits_with_carry(count_heroes as u32, 3);
    bytes.push(version);

    //the checksum which will be updated at the end
    let dummy_checksum = 0;
    let checksum_byte = bytes.len();
    bytes.push(dummy_checksum);

    // write the name size
    let mut safe_name = String::new();
    let mut name_len = 0;
    if deck.name.len() > 0 {
        safe_name = ammonia::clean(&deck.name);
        let mut trim_len = safe_name.len();
        while trim_len > 63 {
            let mut amount_to_trim = (trim_len - 63) / 4;
            amount_to_trim = if amount_to_trim > 1 {
                amount_to_trim
            } else {
                1
            };

            let split_len = safe_name.len() - amount_to_trim;
            safe_name.split_off(split_len);
            trim_len = safe_name.len();
        }
        name_len = safe_name.len();
    }

    bytes.push(name_len as u8);
    add_remaining_number_to_buffer(count_heroes as u32, 3, &mut bytes);

    let mut prev_card_id = 0;
    for hero in &deck.heroes {
        add_card_to_buffer(hero.turn, hero.id - prev_card_id, &mut bytes);
        prev_card_id = hero.id;
    }

    // reset our card offset
    prev_card_id = 0;

    for card in &deck.cards {
        add_card_to_buffer(card.count, card.id - prev_card_id, &mut bytes);
        prev_card_id = card.id;
    }

    // save off pre string bytes for checksum
    let pre_string_byte_count = bytes.len();

    // write the string
    let name_bytes = safe_name.as_bytes();
    for byte in name_bytes {
        bytes.push(*byte);
    }

    let full_checksum = compute_checksum(&bytes, pre_string_byte_count as u32 - HEADER_SIZE);
    let small_checksum = full_checksum & 0x0FF;

    // borrow checksum index and overwrite value with real checksum
    {
        let checksum_ref = &mut bytes[checksum_byte];
        *checksum_ref = small_checksum as u8;
    }

    Ok(bytes)
}

fn extract_n_bits_with_carry(value: u32, num_bits: u8) -> u8 {
    let limit_bit = 1 << num_bits;
    let mut result = value & (limit_bit - 1);
    if value >= limit_bit {
        result |= limit_bit;
    }
    if result > 255 {
        panic!("Something broke in extract_n_bits_with_carry: {}", result);
    }
    result as u8
}

// Utility to write the rest of a number into a buffer.
// This will first strip the specified N bits off, and then write a series
// of bytes of the structure of 1 overflow bit and 7 data bits
fn add_remaining_number_to_buffer(value: u32, already_written_bits: u8, bytes: &mut Vec<u8>) {
    let mut curr_value = value;
    curr_value >>= already_written_bits;
    let mut num_bytes = 0;
    while curr_value > 0 {
        let next_byte = extract_n_bits_with_carry(curr_value, 7);
        curr_value >>= 7;
        bytes.push(next_byte);
        num_bytes = num_bytes + 1;
    }
}

fn add_card_to_buffer(count: u32, value: u32, bytes: &mut Vec<u8>) {
    let count_start = bytes.len();

    // Determine our count. We can only store 2 bits, and we know the value
    // is at least one, so we can encode values 1-5. However,
    // we set both bits to indicate an extended count encodin
    let first_byte_max_count: u8 = 0x03;
    let extended_count = (count - 1) as u8 >= first_byte_max_count;

    // Determine our first byte, which contains our count, a continue flag,
    // and the first few bits of our value
    let first_byte_count: u8 = if extended_count {
        first_byte_max_count
    } else {
        count as u8 - 1
    };

    let mut first_byte: u8 = first_byte_count << 6;
    first_byte |= extract_n_bits_with_carry(value, 5);

    bytes.push(first_byte);

    // Now continue writing out the rest of the number with a carry flag
    add_remaining_number_to_buffer(value, 5, bytes);

    // Now if we overflowed on the count, encode the remaining count
    if extended_count {
        add_remaining_number_to_buffer(count, 0, bytes);
    }

    let count_end = bytes.len();

    if count_end - count_start > 11 {
        panic!("something went horribly wrong, per reference");
    }
}

fn compute_checksum(bytes: &Vec<u8>, num_bytes: u32) -> u32 {
    let mut checksum = 0;

    for add_check in HEADER_SIZE..num_bytes + HEADER_SIZE {
        checksum = checksum + *bytes.get(add_check as usize).unwrap() as u32;
    }

    checksum
}