00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #include <string>
00019 #include <limits.h>
00020 #include <stdio.h>
00021 #include <netdb.h>
00022 #include <sys/types.h>
00023 #include <netinet/in.h>
00024 #include <arpa/inet.h>
00025 #include <sys/socket.h>
00026 #include <sys/param.h>
00027 #include "netutil.h"
00028
00029 int Encoder::varint32_length(uint32 v) {
00030 return Varint::Length32(v);
00031 }
00032
00033 int Encoder::varint64_length(uint64 v) {
00034 return Varint::Length64(v);
00035 }
00036
00037
00038 bool Decoder::get_varint32(uint32* v) {
00039 uint32 result;
00040 unsigned char byte;
00041 const unsigned char* ptr = buf_;
00042 const unsigned char* limit = limit_;
00043 if (Encoder::kVarintMax32 == 5 && ptr + Encoder::kVarintMax32 < limit) {
00044
00045 result = *(ptr++);
00046 if (result < 128) { buf_ = ptr; *v = result; return true; }
00047 result &= 127;
00048
00049
00050 byte = *(ptr++);
00051 result |= static_cast<uint32>(byte & 127) << 7;
00052 if ((byte & 128) == 0) { buf_ = ptr; *v = result; return true; }
00053
00054
00055 byte = *(ptr++);
00056 result |= static_cast<uint32>(byte & 127) << 14;
00057 if ((byte & 128) == 0) { buf_ = ptr; *v = result; return true; }
00058
00059
00060 byte = *(ptr++);
00061 result |= static_cast<uint32>(byte & 127) << 21;
00062 if ((byte & 128) == 0) { buf_ = ptr; *v = result; return true; }
00063
00064
00065 byte = *(ptr++);
00066 result |= static_cast<uint32>(byte & 127) << 28;
00067 buf_ = ptr;
00068 *v = result;
00069 return ((byte & 128) == 0);
00070
00071 } else {
00072
00073 int shift = 0;
00074 result = 0;
00075 do {
00076 if ((shift >= 32) || (ptr >= limit_)) {
00077
00078 return false;
00079 }
00080
00081
00082 byte = *(ptr++);
00083 result |= static_cast<uint32>(byte & 127) << shift;
00084 shift += 7;
00085 } while ((byte & 128) != 0);
00086 buf_ = ptr;
00087 *v = result;
00088 return true;
00089 }
00090 }
00091
00092
00093 bool Decoder::get_varint64(uint64* v) {
00094 uint64 result = 0;
00095 int shift = 0;
00096 unsigned char byte;
00097 do {
00098 if ((shift >= 64) || (buf_ >= limit_)) {
00099
00100 return false;
00101 }
00102
00103
00104 byte = *(buf_++);
00105 result |= static_cast<uint64>(byte & 127) << shift;
00106 shift += 7;
00107 } while ((byte & 128) != 0);
00108 *v = result;
00109 return true;
00110 }