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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
#![no_std]
#![deny(missing_docs)]
//! The `pbf` Rust crate provides functionalities to read and write Protocol Buffers (protobuf) messages.
//! This crate is a 0 dependency package that uses `no_std` and is intended to be used in
//! embedded systems and WASM applications. The crate is designed to be small and efficient,
//! with the cost of some features and flexibility. It is up to the user to create the necessary
//! data structures and implement the `ProtoRead` and `ProtoWrite` traits in order to use it effectively.
/// All encoding and decoding is done via u64.
/// So all types must implement this trait to be able to be encoded and decoded.
pub mod bit_cast;
extern crate alloc;
pub use bit_cast::BitCast;
use alloc::{string::String, vec::Vec};
use core::{cell::RefCell, mem::size_of};
const MAX_VARINT_LENGTH: usize = u64::BITS as usize * 8 / 7 + 1;
const BIT_SHIFT: [u64; 10] = [0, 7, 14, 21, 28, 35, 42, 49, 56, 63];
/// The `Type` enum represents the different types that a field can have in a protobuf message.
/// The `Type` enum is used to determine how to encode and decode the field.
#[derive(Debug, PartialEq)]
pub enum Type {
/// Varint may be: int32, int64, uint32, uint64, sint32, sint64, bool, enum
Varint = 0,
/// Fixed 64-bit numbers will take up exactly 64 bits of space
/// They may be u64, i64, or f64
Fixed64 = 1,
/// This includes any len-delimited tyles:
/// string, bytes, embedded messages, packed repeated fields
Bytes = 2,
/// Fixed 32-bit numbers will take up exactly 64 bits of space
/// They may be an u32, i32, or f32
Fixed32 = 5,
/// This is a null type
None = 7,
}
impl From<u8> for Type {
/// Convert a u8 to a Type
/// # Panics
/// If the value is not a valid Type
fn from(val: u8) -> Self {
match val & 0x7 {
0 => Type::Varint,
1 => Type::Fixed64,
2 => Type::Bytes,
5 => Type::Fixed32,
7 => Type::None,
_ => panic!("Invalid value for Type"),
}
}
}
impl From<Type> for u64 {
fn from(t: Type) -> Self {
match t {
Type::Varint => 0,
Type::Fixed64 => 1,
Type::Bytes => 2,
Type::Fixed32 => 5,
Type::None => 7,
}
}
}
/// The `Field` struct contains a tag and a type.
/// The tag is used to track the data type in the message for decoding.
/// The type is used to determine how to encode and decode the field.
#[derive(Debug, PartialEq)]
pub struct Field {
/// The tag is used to track the data type in the message for decoding.
pub tag: u64,
/// The type is used to determine how to encode and decode the field.
pub r#type: Type,
}
/// The `ProtoRead` trait is used to read a protobuf **message**.
/// This crate forces the user to implement this trait in order to read a protobuf message.
///
/// # Example
/// Using OSM File Format [BlobHeader](https://github.com/openstreetmap/OSM-binary/blob/65e7e976f5c8e47f057a0d921639ea8e6309ef06/osmpbf/fileformat.proto#L63) as an example:
/// ```proto
/// message BlobHeader {
/// required string type = 1;
/// optional bytes indexdata = 2;
/// required int32 datasize = 3;
/// }
/// ```
/// The user would implement the `ProtoRead` trait for the `BlobHeader` struct.
/// ```
/// use pbf::{ProtoRead, Protobuf};
///
/// struct BlobHeader {
/// r#type: String,
/// indexdata: Vec<u8>,
/// datasize: i32,
/// }
/// impl ProtoRead for BlobHeader {
/// fn read(&mut self, tag: u64, pbf: &mut Protobuf) {
/// match tag {
/// 1 => self.r#type = pbf.read_string(),
/// 2 => self.indexdata = pbf.read_bytes(),
/// 3 => self.datasize = pbf.read_varint::<i32>(),
/// _ => unreachable!(),
/// }
/// }
/// }
/// ```
pub trait ProtoRead {
/// The `read` method is used to read a field from a protobuf message.
/// The `tag` parameter is used to determine which field to read into the struct.
/// The `pbf` parameter is used to read the data in the appropriate format.
///
/// # Example
/// Using OSM File Format [BlobHeader](https://github.com/openstreetmap/OSM-binary/blob/65e7e976f5c8e47f057a0d921639ea8e6309ef06/osmpbf/fileformat.proto#L63) as an example:
/// ```proto
/// message BlobHeader {
/// required string type = 1;
/// optional bytes indexdata = 2;
/// required int32 datasize = 3;
/// }
/// ```
/// An example **read** implementation for a `BlobHeader` struct:
/// ```
/// use pbf::{ProtoRead, Protobuf};
///
/// struct BlobHeader {
/// r#type: String,
/// indexdata: Vec<u8>,
/// datasize: i32,
/// }
/// impl ProtoRead for BlobHeader {
/// fn read(&mut self, tag: u64, pbf: &mut Protobuf) {
/// match tag {
/// 1 => self.r#type = pbf.read_string(),
/// 2 => self.indexdata = pbf.read_bytes(),
/// 3 => self.datasize = pbf.read_varint::<i32>(),
/// _ => unreachable!(),
/// }
/// }
/// }
/// ```
fn read(&mut self, tag: u64, pbf: &mut Protobuf);
}
/// The `ProtoWrite` trait is used to write a protobuf **message**.
/// This crate forces the user to implement this trait in order to write a protobuf message.
///
/// # Example
/// Using OSM File Format [BlobHeader](https://github.com/openstreetmap/OSM-binary/blob/65e7e976f5c8e47f057a0d921639ea8e6309ef06/osmpbf/fileformat.proto#L63) as an example:
/// ```proto
/// message BlobHeader {
/// required string type = 1;
/// optional bytes indexdata = 2;
/// required int32 datasize = 3;
/// }
/// ```
/// The user would implement the `ProtoWrite` trait for the `BlobHeader` struct.
/// ```
/// use pbf::{ProtoWrite, Protobuf};
///
/// struct BlobHeader {
/// r#type: String,
/// indexdata: Vec<u8>,
/// datasize: i32,
/// }
/// impl ProtoWrite for BlobHeader {
/// fn write(&self, pbf: &mut Protobuf) {
/// pbf.write_string_field(1, &self.r#type);
/// pbf.write_bytes_field(2, &self.indexdata);
/// pbf.write_varint_field(3, self.datasize);
/// }
/// }
/// ```
pub trait ProtoWrite {
/// The `write` method is used to write a field to a protobuf message.
/// The `pbf` parameter is used to write the data in the appropriate format.
///
/// # Example
/// Using OSM File Format [BlobHeader](https://github.com/openstreetmap/OSM-binary/blob/65e7e976f5c8e47f057a0d921639ea8e6309ef06/osmpbf/fileformat.proto#L63) as an example:
/// ```proto
/// message BlobHeader {
/// required string type = 1;
/// optional bytes indexdata = 2;
/// required int32 datasize = 3;
/// }
/// ```
/// An example **write** implementation for a `BlobHeader` struct:
/// ```
/// use pbf::{ProtoWrite, Protobuf};
///
/// struct BlobHeader {
/// r#type: String,
/// indexdata: Vec<u8>,
/// datasize: i32,
/// }
/// impl ProtoWrite for BlobHeader {
/// fn write(&self, pbf: &mut Protobuf) {
/// pbf.write_string_field(1, &self.r#type);
/// pbf.write_bytes_field(2, &self.indexdata);
/// pbf.write_varint_field(3, self.datasize);
/// }
/// }
/// ```
fn write(&self, pbf: &mut Protobuf);
}
/// The `Protobuf` struct is used to read and write protobuf messages.
///
/// # Example
/// Create a new Protobuf instance:
/// ```
/// use pbf::Protobuf;
///
/// let mut pbf = Protobuf::new();
/// ```
/// Create a Protobuf instance from a byte buffer:
/// ```
/// use pbf::Protobuf;
/// use std::cell::RefCell; // or use core::cell::RefCell; if sticking with no_std
///
/// let mut buf = vec![0x0A, 0x03, 0x74, 0x65, 0x73, 0x74];
/// let mut pbf = Protobuf::from_input(RefCell::new(buf));
/// ```
#[derive(Clone, Debug, Default)]
pub struct Protobuf {
buf: RefCell<Vec<u8>>,
pos: usize,
}
impl From<Vec<u8>> for Protobuf {
fn from(buf: Vec<u8>) -> Protobuf {
Protobuf::from_input(RefCell::new(buf))
}
}
impl Protobuf {
/// Create a new Protobuf instance.
pub fn new() -> Protobuf {
let buf = RefCell::new(Vec::new());
Protobuf { buf, pos: 0 }
}
/// Create a Protobuf instance from a byte buffer.
pub fn from_input(buf: RefCell<Vec<u8>>) -> Protobuf {
Protobuf { buf, pos: 0 }
}
/// Set the position to read from the buffer next.
pub fn set_pos(&mut self, pos: usize) {
self.pos = pos;
}
/// get the current position
pub fn get_pos(&self) -> usize {
self.pos
}
/// get the length of the bufer
pub fn len(&self) -> usize {
self.buf.borrow().len()
}
/// check if the buffer is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
// === READING =================================================================
/// Decode a varint from the buffer at the current position.
pub fn decode_varint(&mut self) -> u64 {
if self.pos >= self.len() {
unreachable!();
}
let mut val: u64 = 0;
let buf = self.buf.borrow();
for (n, shift) in BIT_SHIFT.iter().enumerate().take(MAX_VARINT_LENGTH) {
let b = buf[self.pos] as u64;
self.pos += 1;
if n == 0 {
if b & 0x80 == 0 {
return b;
}
val = b & 0x7f;
} else {
val |= (b & 0x7f) << shift;
}
if b < 0x80 {
break;
}
}
val
}
/// AFter reading a field, you can choose to skip it's value
/// in the buffer if it is not needed.
pub fn skip(&mut self, t: Type) {
match t {
Type::Varint => _ = self.decode_varint(),
Type::Fixed64 => self.pos += 8,
Type::Fixed32 => self.pos += 4,
Type::Bytes => self.pos += self.decode_varint() as usize,
Type::None => { /* Do nothing */ }
};
}
/// Read a field from the buffer.
pub fn read_field(&mut self) -> Field {
let val = self.decode_varint();
Field {
tag: val >> 3,
r#type: Type::from((val & 0x7) as u8),
}
}
/// Read in bytes from the buffer.
pub fn read_bytes(&mut self) -> Vec<u8> {
let end = self.decode_varint() as usize + self.pos;
let buf = self.buf.borrow();
let bytes = buf[self.pos..end].to_vec();
self.pos += end - self.pos;
bytes
}
/// Read in a string from the buffer.
pub fn read_string(&mut self) -> String {
String::from_utf8(self.read_bytes()).expect("Invalid UTF-8")
}
/// Read in a fixed size value from the buffer.
pub fn read_fixed<T>(&mut self) -> T
where
T: BitCast,
{
let buf = self.buf.borrow();
let mut val: u64 = 0;
let size = size_of::<T>();
let mut n = 0;
while n < size {
val |= (buf[self.pos] as u64) << (n << 3);
self.pos += 1;
n += 1;
}
if cfg!(target_endian = "big") {
val = val.swap_bytes();
}
T::from_u64(val)
}
/// Read in a variable size value from the buffer.
pub fn read_varint<T>(&mut self) -> T
where
T: BitCast,
{
let val = self.decode_varint();
T::from_u64(val)
}
/// Read in a signed variable size value from the buffer.
///
/// # Panics
/// Panics if the conversion from `i64` to `T` fails.
pub fn read_s_varint<T>(&mut self) -> T
where
T: TryFrom<i64>,
{
T::try_from(zagzig(self.decode_varint()))
.unwrap_or_else(|_| panic!("read_s_varint: Invalid conversion"))
}
/// Read in a packed value from the buffer.
pub fn read_packed<T>(&mut self) -> Vec<T>
where
T: BitCast,
{
let end = self.decode_varint() as usize + self.pos;
let mut res: Vec<T> = Vec::new();
while self.pos < end {
res.push(self.read_varint::<T>());
}
res
}
/// Read in a signed packed value from the buffer.
pub fn read_s_packed<T>(&mut self) -> Vec<T>
where
T: TryFrom<i64>,
{
let end = self.decode_varint() as usize + self.pos;
let mut res: Vec<T> = Vec::new();
while self.pos < end {
res.push(self.read_s_varint::<T>());
}
res
}
/// Read a message from the buffer. This is the alternative to `read_message`
/// which does the same thing but you may already know the size of the message.
/// The other case is top level data may have fields but no message length.
pub fn read_fields<T: ProtoRead>(&mut self, t: &mut T, end: Option<usize>) {
let end = end.unwrap_or(self.len());
while self.pos < end {
let field = self.read_field();
let start_pos = self.pos;
t.read(field.tag, self);
if start_pos == self.pos {
self.skip(field.r#type);
}
}
}
/// Read in an entire message from the buffer.
/// This is usually used to read in a struct or enum.
pub fn read_message<T: ProtoRead>(&mut self, t: &mut T) {
let end = self.decode_varint() as usize + self.pos;
self.read_fields(t, Some(end));
}
// === WRITING =================================================================
/// Write a u64 to the buffer.
pub fn write_varint<T: BitCast>(&mut self, val: T) {
let mut buf = self.buf.borrow_mut();
let mut val = val.to_u64();
while val >= 0x80 {
buf.push((val & 0x7f) as u8 | 0x80);
val >>= 7;
}
buf.push(val as u8);
}
/// Write an i64 to the buffer.
pub fn write_s_varint(&mut self, val: i64) {
self.write_varint(zigzag(val));
}
/// Write a fixed size value to the buffer. This will not compress the value.
pub fn write_fixed<T>(&mut self, val: T)
where
T: BitCast,
{
let size = size_of::<T>();
let mut val: u64 = val.to_u64();
let mut buf = self.buf.borrow_mut();
if cfg!(target_endian = "big") {
val = val.swap_bytes();
}
let mut n = 0;
while n < size {
buf.push((val >> (n << 3)) as u8);
n += 1;
}
}
/// write a field of "tag" and "type" to the buffer.
pub fn write_field(&mut self, tag: u64, r#type: Type) {
let b: u64 = (tag << 3) | Into::<u64>::into(r#type);
self.write_varint(b);
}
/// write a tag with the size of the buffer to be appended to the internal buffer.
pub fn write_length_varint(&mut self, tag: u64, val: usize) {
self.write_field(tag, Type::Bytes);
self.write_varint(val);
}
/// write a variable sized number, bool, or enum into to the buffer.
pub fn write_varint_field<T>(&mut self, tag: u64, val: T)
where
T: BitCast,
{
self.write_field(tag, Type::Varint);
self.write_varint(val);
}
/// write a signed variable sized number into to the buffer.
pub fn write_s_varint_field<T>(&mut self, tag: u64, val: T)
where
T: Into<i64>,
{
self.write_field(tag, Type::Varint);
self.write_s_varint(val.into());
}
/// write a vector packed variable sized number, bool, or enum into to the buffer.
pub fn write_packed_varint<T>(&mut self, tag: u64, val: &[T])
where
T: BitCast + Copy,
{
let mut pbf = Protobuf::new();
for &v in val {
pbf.write_varint::<T>(v);
}
self.write_bytes_field(tag, &(pbf.take()));
}
/// write a vector packed signed variable sized number into to the buffer.
pub fn write_packed_s_varint<T>(&mut self, tag: u64, val: &[T])
where
T: Into<i64> + Copy,
{
let mut pbf = Protobuf::new();
for &v in val {
pbf.write_s_varint(v.into());
}
self.write_bytes_field(tag, &(pbf.take()));
}
/// write a fixed sized number into to the buffer. No compression is done.
/// Supports 32 and 64 bit numbers.
///
/// # Panics
/// Panics if the size of the type is not 32 or 64 bits.
pub fn write_fixed_field<T>(&mut self, tag: u64, val: T)
where
T: BitCast + Copy,
{
let type_ = match size_of::<T>() {
4 => Type::Fixed32,
8 => Type::Fixed64,
_ => panic!("Invalid fixed type"),
};
self.write_field(tag, type_);
self.write_fixed(val);
}
/// write only the string to the buffer
pub fn write_string(&mut self, val: &str) {
self.write_varint(val.len());
let mut buf = self.buf.borrow_mut();
buf.extend_from_slice(val.as_bytes());
}
/// write a string into to the buffer.
pub fn write_string_field(&mut self, tag: u64, val: &str) {
self.write_length_varint(tag, val.len());
let mut buf = self.buf.borrow_mut();
buf.extend_from_slice(val.as_bytes());
}
/// write a byte array into to the buffer.
pub fn write_bytes_field(&mut self, tag: u64, val: &[u8]) {
self.write_length_varint(tag, val.len());
let mut buf = self.buf.borrow_mut();
buf.extend_from_slice(val)
}
/// write a message into to the buffer.
/// The message must implement the ProtoWrite trait.
/// This is usually reserved for structs and enums.
pub fn write_message<T: ProtoWrite>(&mut self, tag: u64, t: &T) {
let mut pbf = Protobuf::new();
t.write(&mut pbf);
let bytes = pbf.take();
self.write_bytes_field(tag, &bytes);
}
/// When done writing to the buffer, call this function to take ownership
pub fn take(&mut self) -> Vec<u8> {
self.buf.take()
}
}
/// convert a signed integer to an unsigned integer using zigzag encoding.
pub fn zigzag(val: i64) -> u64 {
((val << 1) ^ (val >> 63)) as u64
}
/// convert an unsigned integer to a signed integer using zigzag decoding.
pub fn zagzig(val: u64) -> i64 {
(val >> 1) as i64 ^ -((val & 1) as i64)
}
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
mod tests {
use std::borrow::ToOwned;
use super::*;
#[test]
fn it_works() {
let buf = vec![];
let pb = Protobuf::from_input(RefCell::new(buf));
assert_eq!(pb.pos, 0);
}
#[test]
fn test_zigzag() {
assert_eq!(zigzag(0), 0);
assert_eq!(zagzig(0), 0);
assert_eq!(zagzig(zigzag(0)), 0);
assert_eq!(zagzig(zigzag(5)), 5);
assert_eq!(zagzig(zigzag(-5)), -5);
let max_i64 = i64::MAX;
let min_i64 = i64::MIN;
assert_eq!(zagzig(zigzag(max_i64)), max_i64);
assert_eq!(zagzig(zigzag(min_i64)), min_i64);
}
#[test]
#[should_panic(expected = "Invalid value for Type")]
fn test_write_field_panic() {
let _t: Type = Type::from(22);
}
#[test]
fn test_varint() {
let mut pb = Protobuf::new();
pb.write_varint(1);
pb.write_varint(300);
pb.write_varint(0x7fffffffffffffff_u64);
let bytes = pb.take();
assert_eq!(
bytes,
&[1, 172, 2, 255, 255, 255, 255, 255, 255, 255, 255, 127]
);
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(pb.read_varint::<u64>(), 1);
assert_eq!(pb.read_varint::<u64>(), 300);
assert_eq!(pb.read_varint::<u64>(), 0x7fffffffffffffff);
}
#[test]
fn test_varint_field() {
let mut pb = Protobuf::new();
// unsigned
pb.write_varint_field(0, 5_u8);
pb.write_varint_field(1, 1_u16);
pb.write_varint_field(2, 300_u32);
pb.write_varint_field(3, 0x7fffffffffffffff_u64);
// signed
pb.write_varint_field(4, -5_i8);
pb.write_varint_field(5, -1_i16);
pb.write_varint_field(6, -300_i32);
pb.write_varint_field(7, -94949494949_i64);
// bool
pb.write_varint_field(8, true);
pb.write_varint_field(9, false);
// enum
#[derive(Debug, PartialEq)]
enum TestEnum {
A = 1,
B = 2,
C = 3,
}
impl BitCast for TestEnum {
fn from_u64(val: u64) -> Self {
match val {
1 => TestEnum::A,
2 => TestEnum::B,
3 => TestEnum::C,
_ => panic!("Invalid enum value"),
}
}
fn to_u64(&self) -> u64 {
match self {
TestEnum::A => 1,
TestEnum::B => 2,
TestEnum::C => 3,
}
}
}
pb.write_varint_field(10, TestEnum::B);
// float
pb.write_varint_field(11, std::f32::consts::PI);
pb.write_varint_field(12, -std::f64::consts::PI);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
// unsigned
// tag 0
assert_eq!(
pb.read_field(),
Field {
tag: 0,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u8>(), 5);
// tag 1
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u16>(), 1);
// tag 2
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u32>(), 300);
// tag 3
assert_eq!(
pb.read_field(),
Field {
tag: 3,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u64>(), 0x7fffffffffffffff);
// signed
// tag 4
assert_eq!(
pb.read_field(),
Field {
tag: 4,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<i8>(), -5);
// tag 5
assert_eq!(
pb.read_field(),
Field {
tag: 5,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<i16>(), -1);
// tag 6
assert_eq!(
pb.read_field(),
Field {
tag: 6,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<i32>(), -300);
// tag 7
assert_eq!(
pb.read_field(),
Field {
tag: 7,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<i64>(), -94949494949);
// bool
// tag 8
assert_eq!(
pb.read_field(),
Field {
tag: 8,
r#type: Type::Varint
}
);
assert!(pb.read_varint::<bool>());
// tag 9
assert_eq!(
pb.read_field(),
Field {
tag: 9,
r#type: Type::Varint
}
);
assert!(!pb.read_varint::<bool>());
// enum
// tag 10
assert_eq!(
pb.read_field(),
Field {
tag: 10,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<TestEnum>(), TestEnum::B);
// float
// tag 11
assert_eq!(
pb.read_field(),
Field {
tag: 11,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<f32>(), std::f32::consts::PI);
// tag 12
assert_eq!(
pb.read_field(),
Field {
tag: 12,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<f64>(), -std::f64::consts::PI);
}
#[test]
fn test_s_varint_field() {
let mut pb = Protobuf::new();
pb.write_s_varint_field(1, 5_i8);
pb.write_s_varint_field(2, 5_i16);
pb.write_s_varint_field(3, 5_i32);
pb.write_s_varint_field(4, 5_i64);
pb.write_s_varint_field(5, -5_i8);
pb.write_s_varint_field(6, -5_i16);
pb.write_s_varint_field(7, -5_i32);
pb.write_s_varint_field(8, -5_i64);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i8>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i16>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 3,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i32>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 4,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i64>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 5,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i8>(), -5);
assert_eq!(
pb.read_field(),
Field {
tag: 6,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i16>(), -5);
assert_eq!(
pb.read_field(),
Field {
tag: 7,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i32>(), -5);
assert_eq!(
pb.read_field(),
Field {
tag: 8,
r#type: Type::Varint
}
);
assert_eq!(pb.read_s_varint::<i64>(), -5);
}
#[test]
fn test_fixed() {
let mut pb = Protobuf::new();
pb.write_fixed_field(1, 5_u32);
pb.write_fixed_field(2, -5_i32);
pb.write_fixed_field(3, 5.5_f32);
pb.write_fixed_field(4, 5_u64);
pb.write_fixed_field(5, -5_i64);
pb.write_fixed_field(6, 5.5_f64);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Fixed32
}
);
assert_eq!(pb.read_fixed::<u32>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Fixed32
}
);
assert_eq!(pb.read_fixed::<i32>(), -5);
assert_eq!(
pb.read_field(),
Field {
tag: 3,
r#type: Type::Fixed32
}
);
assert_eq!(pb.read_fixed::<f32>(), 5.5);
assert_eq!(
pb.read_field(),
Field {
tag: 4,
r#type: Type::Fixed64
}
);
assert_eq!(pb.read_fixed::<u64>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 5,
r#type: Type::Fixed64
}
);
assert_eq!(pb.read_fixed::<i64>(), -5);
assert_eq!(
pb.read_field(),
Field {
tag: 6,
r#type: Type::Fixed64
}
);
assert_eq!(pb.read_fixed::<f64>(), 5.5);
}
#[test]
#[should_panic(expected = "Invalid fixed type")]
fn test_fixed_panic() {
let mut pb = Protobuf::new();
pb.write_fixed_field(1, 1_u8);
}
#[test]
fn test_string() {
let mut pb = Protobuf::new();
pb.write_string_field(1, "hello");
pb.write_string_field(2, "world");
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_string(), "hello");
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_string(), "world");
}
#[test]
fn test_bytes() {
let mut pb = Protobuf::new();
pb.write_bytes_field(1, &[1, 2, 3]);
pb.write_bytes_field(2, &[4, 5, 6]);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_bytes(), &[1, 2, 3]);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_bytes(), &[4, 5, 6]);
}
#[test]
fn test_write_field() {
let mut pb = Protobuf::new();
pb.write_field(1, Type::Varint);
pb.write_field(2, Type::None);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Varint,
}
);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::None,
}
);
}
#[test]
fn test_set_pos() {
let mut pb = Protobuf::new();
pb.write_varint_field(1, 5);
pb.write_varint_field(2, 5);
pb.write_varint_field(3, 5);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
pb.set_pos(2);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u8>(), 5);
assert_eq!(
pb.read_field(),
Field {
tag: 3,
r#type: Type::Varint
}
);
assert_eq!(pb.read_varint::<u8>(), 5);
}
#[test]
fn test_skip() {
let mut pb = Protobuf::new();
pb.write_varint_field(1, 5_u8);
pb.write_fixed_field(2, -5_i32);
pb.write_fixed_field(3, 5.5_f64);
pb.write_packed_varint::<u16>(4, &[1, 2, 3, 4, 5]);
pb.write_field(5, Type::None);
pb.write_varint_field(6, false);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
let mut field = pb.read_field();
pb.skip(field.r#type); // skip 1 Type::Varint
field = pb.read_field();
pb.skip(field.r#type); // skip 2 Type::Fixed32
field = pb.read_field();
pb.skip(field.r#type); // skip 3 Type::Fixed64
field = pb.read_field();
pb.skip(field.r#type); // skip 4 Type::Bytes
field = pb.read_field();
pb.skip(field.r#type); // skip 5 Type::None
assert_eq!(
pb.read_field(),
Field {
tag: 6,
r#type: Type::Varint
}
);
}
#[test]
fn test_packed_and_s_packed() {
let mut pb = Protobuf::new();
pb.write_packed_varint::<u16>(1, &[1, 2, 3]);
pb.write_packed_varint::<f32>(2, &[4.4, 5.5, 6.6]);
pb.write_packed_s_varint(3, &[-1, -2, -3]);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(
pb.read_field(),
Field {
tag: 1,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_packed::<u16>(), vec![1, 2, 3]);
assert_eq!(
pb.read_field(),
Field {
tag: 2,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_packed::<f32>(), vec![4.4, 5.5, 6.6]);
assert_eq!(
pb.read_field(),
Field {
tag: 3,
r#type: Type::Bytes
}
);
assert_eq!(pb.read_s_packed::<i32>(), vec![-1, -2, -3]);
}
#[test]
fn test_message() {
#[derive(Debug, PartialEq, Default)]
struct TestMessage {
a: i32,
b: String,
}
impl TestMessage {
fn new(a: i32, b: &str) -> Self {
TestMessage { a, b: b.to_owned() }
}
}
impl ProtoWrite for TestMessage {
fn write(&self, pb: &mut Protobuf) {
pb.write_varint_field::<u64>(1, self.a as u64);
pb.write_string_field(2, &self.b);
}
}
impl ProtoRead for TestMessage {
fn read(&mut self, tag: u64, pb: &mut Protobuf) {
match tag {
1 => self.a = pb.read_varint::<i32>(),
2 => self.b = pb.read_string(),
_ => panic!("Invalid tag"),
}
}
}
let mut pb = Protobuf::new();
let msg = TestMessage::new(1, "hello");
pb.write_message(1, &msg);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
// first read in the field for the message
let field = pb.read_field();
assert_eq!(
field,
Field {
tag: 1,
r#type: Type::Bytes
}
);
let mut msg = TestMessage::default();
pb.read_message(&mut msg);
assert_eq!(msg.a, 1);
assert_eq!(msg.b, "hello");
}
#[test]
fn test_message_with_skip() {
#[derive(Debug, PartialEq, Default)]
struct TestMessage {
a: i32,
b: String,
}
impl TestMessage {
fn new(a: i32, b: &str) -> Self {
TestMessage { a, b: b.to_owned() }
}
}
impl ProtoWrite for TestMessage {
fn write(&self, pb: &mut Protobuf) {
pb.write_varint_field::<u64>(1, self.a as u64);
pb.write_string_field(2, &self.b);
}
}
impl ProtoRead for TestMessage {
fn read(&mut self, tag: u64, pb: &mut Protobuf) {
if tag == 2 {
self.b = pb.read_string()
}
}
}
let mut pb = Protobuf::new();
let msg = TestMessage::new(1, "hello");
pb.write_message(1, &msg);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
// first read in the field for the message
let field = pb.read_field();
assert_eq!(
field,
Field {
tag: 1,
r#type: Type::Bytes
}
);
let mut msg = TestMessage::default();
pb.read_message(&mut msg);
assert_eq!(msg.a, 0);
assert_eq!(msg.b, "hello");
}
#[test]
fn unicode_string() {
let mut pb = Protobuf::new();
pb.write_string("你好");
let bytes = pb.take();
let mut pb = Protobuf::from_input(From::from(bytes));
assert_eq!(pb.read_string(), "你好");
}
#[test]
fn write_float() {
let mut pb = Protobuf::new();
pb.write_varint(5.5_f32);
let bytes = pb.take();
assert_eq!(bytes, vec![128, 128, 192, 133, 4]);
let mut pb2 = Protobuf::new();
pb2.write_varint(30994030.23423423_f64);
let bytes2 = pb2.take();
assert_eq!(bytes2, vec![228, 216, 253, 157, 238, 220, 227, 190, 65]);
}
#[test]
fn is_empty() {
let mut pb = Protobuf::new();
assert!(pb.is_empty());
pb.write_varint(5.5_f32);
assert!(!pb.is_empty());
}
#[test]
fn get_pos() {
let mut pb = Protobuf::new();
pb.write_varint(5.5_f32);
let bytes = pb.take();
assert_eq!(bytes, vec![128, 128, 192, 133, 4]);
let mut pb: Protobuf = bytes.into();
let data = pb.read_varint::<f32>();
assert_eq!(data, 5.5_f32);
assert_eq!(pb.get_pos(), 5);
}
#[test]
fn bug_test() {
let mut pb = Protobuf::new();
pb.write_bytes_field(1, &[127, 55, 192, 128, 0, 0, 128, 182, 11, 129, 108, 22]);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
let _field = pb.read_field();
assert_eq!(
pb.read_bytes(),
&[127, 55, 192, 128, 0, 0, 128, 182, 11, 129, 108, 22]
);
}
#[test]
fn bug_test_packed() {
let mut pb = Protobuf::new();
let bytes: Vec<u8> = vec![127, 55, 192, 128, 0, 0, 128, 182, 11, 129, 108, 22];
pb.write_packed_varint::<u8>(1, &bytes);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
let _field = pb.read_field();
assert_eq!(
pb.read_packed::<u8>(),
&[127, 55, 192, 128, 0, 0, 128, 182, 11, 129, 108, 22]
);
}
#[test]
fn test_bug_128() {
let mut pb = Protobuf::new();
pb.write_varint::<u8>(127);
pb.write_varint(55);
pb.write_varint(192);
let bytes = pb.take();
let mut pb = Protobuf::from_input(RefCell::new(bytes));
assert_eq!(pb.read_varint::<u8>(), 127);
assert_eq!(pb.read_varint::<u8>(), 55);
}
}