1// Copyright (c) 2017 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
89use std::io::{self};
1011pub mod raw;
1213/// Returns length of length-encoded-integer representation of `x`.
14pub fn lenenc_int_len(x: u64) -> u64 {
15if x < 251 {
161
17} else if x < 65_536 {
183
19} else if x < 16_777_216 {
204
21} else {
229
23}
24}
2526/// Returns length of lenght-encoded-string representation of `s`.
27pub fn lenenc_str_len(s: &[u8]) -> u64 {
28let len = s.len() as u64;
29 lenenc_int_len(len) + len
30}
3132pub(crate) fn unexpected_buf_eof() -> io::Error {
33 io::Error::new(
34 io::ErrorKind::UnexpectedEof,
35"can't parse: buf doesn't have enough data",
36 )
37}
3839/// Splits server 'version' string into three numeric pieces.
40///
41/// It'll return `(0, 0, 0)` in case of error.
42pub fn split_version<T: AsRef<[u8]>>(version_str: T) -> (u8, u8, u8) {
43let bytes = version_str.as_ref();
44 split_version_inner(bytes).unwrap_or((0, 0, 0))
45}
4647// Split into its own function for two reasons:
48// 1. Generic function will be instantiated for every type, increasing code size
49// 2. It allows using Option and ? operator without breaking public API
50fn split_version_inner(input: &[u8]) -> Option<(u8, u8, u8)> {
51let mut nums = [0_u8; 3];
52let mut iter = input.split(|c| *c == b'.');
53for (i, chunk) in (&mut iter).take(2).enumerate() {
54 nums[i] = btoi::btoi(chunk).ok()?;
55 }
56// allow junk at the end of the final part of the version
57let chunk_with_junk = iter.next()?;
58let end_of_digits = chunk_with_junk.iter().position(|c| *c < b'0' || *c > b'9');
59let chunk = match end_of_digits {
60Some(pos) => &chunk_with_junk[..pos],
61None => chunk_with_junk,
62 };
63 nums[2] = btoi::btoi(chunk).ok()?;
6465Some((nums[0], nums[1], nums[2]))
66}
6768#[cfg(test)]
69mod tests {
70use super::*;
7172#[test]
73fn should_split_version() {
74assert_eq!((1, 2, 3), split_version("1.2.3"));
75assert_eq!((10, 20, 30), split_version("10.20.30foo"));
76assert_eq!((0, 0, 0), split_version("100.200.300foo"));
77assert_eq!((0, 0, 0), split_version("100.200foo"));
78assert_eq!((0, 0, 0), split_version("1,2.3"));
79assert_eq!((0, 0, 0), split_version("1"));
80assert_eq!((0, 0, 0), split_version("1.2"));
81 }
82}