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
use std::io::{Cursor, Read};
use byteorder::{ReadBytesExt, BigEndian};
use {Error, Result};
const INFORMATION_ELEMENT_HEADER_LENGTH: u16 = 3;
enum_from_primitive! {
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SessionStatus {
Ok = 0,
OkMobileTerminatedTooLarge = 1,
OkLocationUnacceptableQuality = 2,
Timeout = 10,
MobileOriginatedTooLarge = 12,
RFLinkLoss = 13,
IMEIProtocolAnomaly = 14,
Prohibited = 15,
Unknown,
}
}
#[derive(Debug, Default)]
pub struct InformationElement {
id: u8,
length: u16,
contents: Vec<u8>,
}
impl InformationElement {
pub fn read_from<R: Read>(mut readable: R) -> Result<InformationElement> {
let mut information_element: InformationElement = Default::default();
information_element.id = try!(readable.read_u8());
information_element.length = try!(readable.read_u16::<BigEndian>());
let bytes_read = try!(readable.take(information_element.length as u64)
.read_to_end(&mut information_element.contents));
assert!(!(bytes_read > information_element.length as usize));
if bytes_read < information_element.length as usize {
return Err(Error::Undersized(bytes_read + 3));
}
Ok(information_element)
}
pub fn len(&self) -> u16 {
self.length + INFORMATION_ELEMENT_HEADER_LENGTH
}
pub fn id(&self) -> u8 {
self.id
}
pub fn as_contents_reader<'a>(&self) -> Cursor<&[u8]> {
Cursor::new(&self.contents[..])
}
pub fn contents_ref(&self) -> &Vec<u8> {
&self.contents
}
pub fn into_contents(self) -> Vec<u8> {
self.contents
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Seek, SeekFrom};
use std::fs::File;
#[test]
fn read_from() {
let mut file = File::open("data/0-mo.sbd").unwrap();
file.seek(SeekFrom::Start(3)).unwrap();
let readable = file.take(31);
InformationElement::read_from(readable).unwrap();
}
#[test]
fn len() {
let mut file = File::open("data/0-mo.sbd").unwrap();
file.seek(SeekFrom::Start(3)).unwrap();
let readable = file.take(31);
let ie = InformationElement::read_from(readable).unwrap();
assert_eq!(31, ie.len());
}
#[test]
fn undersized() {
let mut file = File::open("data/0-mo.sbd").unwrap();
file.seek(SeekFrom::Start(3)).unwrap();
let readable = file.take(30);
assert!(InformationElement::read_from(readable).is_err());
}
}