syslog_ng_common/
cfg.rs

1// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
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.
8
9use syslog_ng_sys::cfg;
10use std::ffi::CStr;
11
12pub struct GlobalConfig(*const cfg::GlobalConfig);
13
14impl GlobalConfig {
15    pub fn get_user_version(&self) -> (u8, u8) {
16        let mut version = unsafe { cfg::cfg_get_user_version(self.0) };
17
18        if version < 0 {
19            error!("User config version must be greater than 0, using 0 as version");
20            version = 0;
21        }
22
23        convert_version(version as u16)
24    }
25
26    pub fn get_parsed_version(&self) -> (u8, u8) {
27        let mut version = unsafe { cfg::cfg_get_parsed_version(self.0) };
28
29        if version < 0 {
30            error!("Parsed config version must be greater than 0, using 0 as version");
31            version = 0;
32        }
33
34        convert_version(version as u16)
35    }
36
37    pub fn get_filename(&self) -> &CStr {
38        unsafe { CStr::from_ptr(cfg::cfg_get_filename(self.0)) }
39    }
40}
41
42fn hex_to_dec(hex: u8) -> u8 {
43    let mut dec = 0;
44    let mut shifted_hex = hex;
45
46    for i in 0..2 {
47        dec += (shifted_hex % 16) * 10u8.pow(i);
48        shifted_hex >>= 4;
49    }
50
51    dec
52}
53
54fn convert_version(version: u16) -> (u8, u8) {
55    let minor = hex_to_dec(version as u8);
56    let major = hex_to_dec((version >> 8) as u8);
57    (major, minor)
58}
59
60#[test]
61fn one_digit_hex_number_when_converted_to_decimal_works() {
62    let dec = hex_to_dec(0x3);
63    assert_eq!(dec, 3);
64}
65
66#[test]
67fn more_digits_hex_number_when_converted_to_decimal_works() {
68    let dec = hex_to_dec(0x22);
69    assert_eq!(dec, 22);
70}
71
72#[test]
73fn hex_version_when_converted_to_minor_version_works() {
74    let version = 0x0316;
75
76    let (_, minor) = convert_version(version);
77    assert_eq!(minor, 16);
78}
79
80#[test]
81fn hex_version_when_converted_to_major_version_works() {
82    let version = 0x0316;
83
84    let (major, _) = convert_version(version);
85    assert_eq!(major, 3);
86}