/********************************************************************************* * MIT License * * Copyright (c) 2020-2023 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ********************************************************************************/ #include "TLV8.h" ///////////////////////////////////// TLV8_it TLV8::add(uint8_t tag, size_t len, const uint8_t* val){ if(!empty() && back().tag==tag) back().update(len,val); else emplace_back(tag,len,val); return(end()-1); } ///////////////////////////////////// TLV8_it TLV8::find(uint8_t tag, TLV8_it it1, TLV8_it it2){ auto it=it1; while(it!=it2 && (*it).tag!=tag) it++; return(it); } ///////////////////////////////////// size_t TLV8::pack_size(TLV8_it it1, TLV8_it it2){ size_t nBytes=0; while(it1!=it2){ nBytes+=2+(*it1).len; if((*it1).len>255) nBytes+=2*(((*it1).len-1)/255); it1++; } return(nBytes); } ///////////////////////////////////// size_t TLV8::pack(uint8_t *buf, size_t bufSize){ size_t nBytes=0; while(nBytes255) currentPackLen=255; *buf++=currentPackLen; nBytes++; currentPackPhase=3; break; case 3: if(currentPackLen==0){ if(endPackBuf==currentPackBuf){ currentPackIt++; currentPackPhase=0; } else { currentPackPhase=1; } break; } size_t copyBytes=(currentPackLen<(bufSize-nBytes)) ? currentPackLen : (bufSize-nBytes); memcpy(buf,currentPackBuf,copyBytes); buf+=copyBytes; currentPackBuf+=copyBytes; currentPackLen-=copyBytes; nBytes+=copyBytes; break; } } return(nBytes); } ///////////////////////////////////// void TLV8::unpack(uint8_t *buf, size_t bufSize){ if(empty()) unpackPhase=0; while(bufSize>0){ switch(unpackPhase){ case 0: unpackTag=*buf++; bufSize--; unpackPhase=1; break; case 1: unpackBytes=*buf++; bufSize--; if(unpackBytes==0){ add(unpackTag); unpackPhase=0; } else { unpackPhase=2; } break; case 2: size_t copyBytes=unpackBytes