/*----------------------------------------------------------------------------- * protocol.cpp - Code to deal with packing and unpacking of the data * Copyright (C) 2003, 2004, 2005 Akito Nozaki * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include #include #include #include #include #include #include #include using namespace std; NAMESPACE_TANOSHI { Protocol::Protocol() { } Protocol::~Protocol() { for(std::map< string, ByteArray * >::iterator f = buffer.begin(); f != buffer.end();) { std::map::iterator del = f++; delete (*del).second; buffer.erase(del); } } void Protocol::add(const string &name, const ByteArray &data) { ByteArray *a = new ByteArray; *a = data; buffer[name] = a; } ByteArray Protocol::getInfo(const string &nameinfo) const { return *(*(buffer.find(nameinfo))).second; } bool Protocol::exists(const string &nameinfo) const { std::map< string, ByteArray *>::const_iterator f = buffer.find(nameinfo); std::map< string, ByteArray *>::const_iterator e = buffer.end(); return f != e; } int Protocol::unpack(const ByteArray &data) { if(data.size() < 4) return -1; unsigned int size = ntohl(*(unsigned int *)&data[0]); if(data.size()-4 < size) return -2; char packnum = data[4]; unsigned int loc = 5; if(data.size() <= loc) return -1; for(char i=0; iappend(data[loc++]); buffer[tn.data()] = tv; } return 0; } ByteArray Protocol::pack() { ByteArray pack((unsigned int)4); ByteArray data; char num = 0; for(map::iterator i=buffer.begin(); i != buffer.end(); i++) { ByteArray temp; temp.clear(); temp.append(" ", 2); *(unsigned short *)&temp[0] = htons(i->first.size()); temp.append(i->first.data(), i->first.size()); data.append(temp); temp.clear(); temp.append(" ", 2); *(unsigned short *)&temp[0] = htons(i->second->size()); temp.append(i->second->data(), i->second->size()); data.append(temp); num++; } pack.append(" ", 4); *(unsigned int *)&pack[0] = htonl(data.size()); pack.append(" ", 1); pack[4] = num; pack.append(data); return pack; } }