C++ with (implicit) casts, no separators.


  • 0
    M

    The protocol roughly uses TLV (type-length-value) encoding, but without the 'type' since we know the items are strings. It uses 4 bytes for the number of strings, then each string is 4 bytes for a length followed by the string data. Taking advantage of C++/C, the lengths are cast to 4-byte values.

    If the transfer is between machines w/differing endianness there could be problems, but it seems okay for LC toy code.

    
            // convert to/from uint32_t and str/buff[4]
            union fudge
            {
                fudge(uint32_t num) : num(num) {}
                fudge(const string& s, int pos)
                { copy_n(s.data() + pos, 4, buf + 0); }
    
                char buf[4];
                uint32_t num;
            };
    
            static_assert(sizeof(fudge) == 4, "");
    
            // Encodes a list of strings to a single string.
            string encode(vector<string>& strs)
            {
                string enc;
                
                // reserve some memory (optional)
                auto len = 0u;
                for (const auto& str : strs) len += str.size();
                enc.reserve(len + 4 + 4 * strs.size());
    
                // add number of strings
                fudge f(static_cast<uint32_t>(strs.size()));
                enc.append(f.buf + 0, f.buf + 4);
    
                for (const auto& str : strs)
                {
                    // add string length
                    fudge f(static_cast<uint32_t>(str.size()));
                    enc.append(f.buf + 0, f.buf + 4);
    
                    // add string value
                    enc.append(str);
                }
    
                return enc;
            }
    
            // Decodes a single string to a list of strings.
            vector<string> decode(string s)
            {
                // get number of strings
                fudge f(s, 0);
                auto N = f.num;
                auto pos = 4;
    
                vector<string> strs(N);
                for (auto i = 0u; i < N; ++i)
                {
                    // get str length N
                    fudge f(s, pos);
                    auto N = f.num;
                    pos += 4;
                    
                    // read N chars
                    strs[i].assign(s, pos, N);
                    pos += N;
                }
    
                return strs;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.