data.cc 24.1 KB
Newer Older
Jelte Jansen's avatar
Jelte Jansen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

// $Id$
16 17 18 19 20 21 22 23 24 25

#include "data.h"

#include <cstdio>
#include <iostream>
#include <sstream>

#include <boost/algorithm/string.hpp>

using namespace std;
Jelte Jansen's avatar
Jelte Jansen committed
26
using namespace isc::data;
27 28 29

const unsigned char PROTOCOL_VERSION[4] = { 0x53, 0x6b, 0x61, 0x6e };

30
const unsigned char ITEM_BLOB = 0x01;
31 32 33
const unsigned char ITEM_HASH = 0x02;
const unsigned char ITEM_LIST = 0x03;
const unsigned char ITEM_NULL = 0x04;
Jelte Jansen's avatar
Jelte Jansen committed
34
const unsigned char ITEM_BOOL = 0x05;
35
const unsigned char ITEM_INT  = 0x06;
36
const unsigned char ITEM_REAL = 0x07;
37
const unsigned char ITEM_UTF8 = 0x08;
38 39 40 41 42 43 44
const unsigned char ITEM_MASK = 0x0f;

const unsigned char ITEM_LENGTH_32   = 0x00;
const unsigned char ITEM_LENGTH_16   = 0x10;
const unsigned char ITEM_LENGTH_8    = 0x20;
const unsigned char ITEM_LENGTH_MASK = 0x30;

Jelte Jansen's avatar
Jelte Jansen committed
45
static inline void
46
throwParseError(const std::string& error, const std::string& file, int line = 0, int pos = 0)
Jelte Jansen's avatar
Jelte Jansen committed
47 48 49
{
    if (line != 0 || pos != 0) {
        std::stringstream ss;
50
        ss << error << " in " + file + ":" << line << ":" << pos;
Jelte Jansen's avatar
Jelte Jansen committed
51 52 53 54
        throw ParseError(ss.str());
    } else {
        throw ParseError(error);
    }
55 56
}

Jelte Jansen's avatar
Jelte Jansen committed
57 58
std::ostream& operator <<(std::ostream &out, const isc::data::ElementPtr& e) {
    return out << e->str();
59 60
}

61 62 63 64 65
bool operator==(const isc::data::ElementPtr a, const isc::data::ElementPtr b)
{
    return a->equals(b);
};

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
//
// factory functions
//
ElementPtr
Element::create(const int i)
{
    try {
        return ElementPtr(new IntElement(i));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const double d)
{
    try {
        return ElementPtr(new DoubleElement(d));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::string& s)
{
    try {
        return ElementPtr(new StringElement(s));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const bool b)
{
    try {
        return ElementPtr(new BoolElement(b));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::vector<ElementPtr>& v)
{
    try {
        return ElementPtr(new ListElement(v));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}

ElementPtr
Element::create(const std::map<std::string, ElementPtr>& m)
{
    try {
        return ElementPtr(new MapElement(m));
    } catch (std::bad_alloc) {
        return ElementPtr();
    }
}


//
131
// helper functions for createFromString factory
132 133 134 135 136 137 138 139 140 141 142 143 144 145
//

static bool
char_in(char c, const char *chars)
{
    for (size_t i = 0; i < strlen(chars); i++) {
        if (chars[i] == c) {
            return true;
        }
    }
    return false;
}

static void
146
skip_chars(std::istream &in, const char *chars, int& line, int& pos)
147 148 149
{
    char c = in.peek();
    while (char_in(c, chars) && c != EOF) {
150 151 152 153 154 155
        if (c == '\n') {
            line++;
            pos = 1;
        } else {
            pos++;
        }
156 157 158 159 160 161 162
        in.get();
        c = in.peek();
    }
}

// skip on the input stream to one of the characters in chars
// if another character is found this function returns false
163
// unless that character is specified in the optional may_skip
164 165
//
// the character found is left on the stream
166
static void
Jelte Jansen's avatar
Jelte Jansen committed
167 168
skip_to(std::istream &in, const std::string& file, int& line,
        int& pos, const char* chars, const char* may_skip="")
169 170
{
    char c = in.get();
171
    pos++;
172
    while (c != EOF) {
173 174 175 176
        if (c == '\n') {
            pos = 1;
            line++;
        }
177 178
        if (char_in(c, may_skip)) {
            c = in.get();
179
            pos++;
180 181
        } else if (char_in(c, chars)) {
            while(char_in(in.peek(), may_skip)) {
182 183 184 185
                if (in.peek() == '\n') {
                    pos = 1;
                    line++;
                }
186
                in.get();
187
                pos++;
188 189
            }
            in.putback(c);
190 191
            pos--;
            return;
192
        } else {
Jelte Jansen's avatar
Jelte Jansen committed
193
            throwParseError(std::string("'") + c + "' read, one of \"" + chars + "\" expected", file, line, pos);
194 195
        }
    }
Jelte Jansen's avatar
Jelte Jansen committed
196
    throwParseError(std::string("EOF read, one of \"") + chars + "\" expected", file, line, pos);
197 198 199
}

static std::string
Jelte Jansen's avatar
Jelte Jansen committed
200
str_from_stringstream(std::istream &in, const std::string& file, int& line, int& pos) throw (ParseError)
201 202 203 204
{
    char c = 0;
    std::stringstream ss;
    c = in.get();
205
    pos++;
206 207
    if (c == '"') {
        c = in.get();
208
        pos++;
209
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
210
        throwParseError("String expected", file, line, pos);
211 212 213 214 215
    }
    while (c != EOF && c != '"') {
        ss << c;
        if (c == '\\' && in.peek() == '"') {
            ss << in.get();
216
            pos++;
217 218
        }
        c = in.get();
219
        pos++;
220 221 222 223 224
    }
    return ss.str();
}

static std::string
225
word_from_stringstream(std::istream &in, int& line, int& pos)
226 227 228 229 230
{
    std::stringstream ss;
    while (isalpha(in.peek())) {
        ss << (char) in.get();
    }
231
    pos += ss.str().size();
232 233 234
    return ss.str();
}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
static inline int
count_chars_i(int i)
{
    int result = 1;
    while (i > 10) {
        result++;
        i=i/10;
    }
    return result;
}

static inline int
count_chars_d(double d)
{
    int result = 1;
    while(d < 1.0) {
        result++;
        d = d * 10;
    }
    return result;
}
256 257

static ElementPtr
258
from_stringstream_int_or_double(std::istream &in, int &line, int &pos)
259 260 261
{
    int i;
    in >> i;
262
    pos += count_chars_i(i);
263 264 265
    if (in.peek() == '.') {
        double d;
        in >> d;
266
        pos += count_chars_d(i);
267 268 269 270 271 272 273 274
        d += i;
        return Element::create(d);
    } else {
        return Element::create(i);
    }
}

static ElementPtr
Jelte Jansen's avatar
Jelte Jansen committed
275
from_stringstream_bool(std::istream &in, const std::string& file, int& line, int& pos)
276
{
277
    std::string word = word_from_stringstream(in, line, pos);
278 279 280 281 282
    if (boost::iequals(word, "True")) {
        return Element::create(true);
    } else if (boost::iequals(word, "False")) {
        return Element::create(false);
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
283 284 285
        throwParseError(std::string("Bad boolean value: ") + word, file, line, pos);
        // above is a throw shortcur, return empty is never reached
        return ElementPtr();
286 287 288 289
    }
}

static ElementPtr
Jelte Jansen's avatar
Jelte Jansen committed
290
from_stringstream_string(std::istream &in, const std::string& file, int& line, int& pos)
291
{
Jelte Jansen's avatar
Jelte Jansen committed
292
    return Element::create(str_from_stringstream(in, file, line, pos));
293 294 295
}

static ElementPtr
Jelte Jansen's avatar
Jelte Jansen committed
296
from_stringstream_list(std::istream &in, const std::string& file, int& line, int& pos)
297 298 299 300 301
{
    char c = 0;
    std::vector<ElementPtr> v;
    ElementPtr cur_list_element;

302
    skip_chars(in, " \t\n", line, pos);
303
    while (c != EOF && c != ']') {
304
        if (in.peek() != ']') {
Jelte Jansen's avatar
Jelte Jansen committed
305
            cur_list_element = Element::createFromString(in, file, line, pos);
306
            v.push_back(cur_list_element);
Jelte Jansen's avatar
Jelte Jansen committed
307
            skip_to(in, file, line, pos, ",]", " \t\n");
308 309
        }
        c = in.get();
310
        pos++;
311 312 313 314 315
    }
    return Element::create(v);
}

static ElementPtr
Jelte Jansen's avatar
Jelte Jansen committed
316
from_stringstream_map(std::istream &in, const std::string& file, int& line, int& pos)
317 318 319 320 321 322
{
    char c = 0;
    std::map<std::string, ElementPtr> m;
    std::pair<std::string, ElementPtr> p;
    std::string cur_map_key;
    ElementPtr cur_map_element;
323
    skip_chars(in, " \t\n", line, pos);
324 325 326
    c = in.peek();
    if (c == '}') {
        // empty map, skip closing curly
327
        c = in.get();
328 329 330 331 332 333 334 335 336 337 338 339 340
    } else {
        while (c != EOF && c != '}') {
            p.first = str_from_stringstream(in, file, line, pos);
            skip_to(in, file, line, pos, ":", " \t\n");
            // skip the :
            in.get();
            pos++;
            p.second = Element::createFromString(in, file, line, pos);
            m.insert(p);
            skip_to(in, file, line, pos, ",}", " \t\n");
            c = in.get();
            pos++;
        }
341 342 343 344 345
    }
    return Element::create(m);
}

ElementPtr
346
Element::createFromString(std::istream &in) throw(ParseError)
347 348
{
    int line = 1, pos = 1;
349 350 351 352 353 354 355 356
    return createFromString(in, "<istream>", line, pos);
}

ElementPtr
Element::createFromString(std::istream &in, const std::string& file_name) throw(ParseError)
{
    int line = 1, pos = 1;
    return createFromString(in, file_name, line, pos);
357 358 359
}

ElementPtr
Jelte Jansen's avatar
Jelte Jansen committed
360
Element::createFromString(std::istream &in, const std::string& file, int& line, int& pos) throw(ParseError)
361 362 363 364
{
    char c = 0;
    ElementPtr element;
    bool el_read = false;
365
    skip_chars(in, " \n\t", line, pos);
366 367
    while (c != EOF && !el_read) {
        c = in.get();
368
        pos++;
369 370 371 372 373 374 375 376 377 378 379 380
        switch(c) {
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                in.putback(c);
381
                element = from_stringstream_int_or_double(in, line, pos);
382 383 384 385 386 387 388
                el_read = true;
                break;
            case 't':
            case 'T':
            case 'f':
            case 'F':
                in.putback(c);
Jelte Jansen's avatar
Jelte Jansen committed
389
                element = from_stringstream_bool(in, file, line, pos);
390 391 392 393
                el_read = true;
                break;
            case '"':
                in.putback('"');
Jelte Jansen's avatar
Jelte Jansen committed
394
                element = from_stringstream_string(in, file, line, pos);
395 396 397
                el_read = true;
                break;
            case '[':
Jelte Jansen's avatar
Jelte Jansen committed
398
                element = from_stringstream_list(in, file, line, pos);
399 400 401
                el_read = true;
                break;
            case '{':
Jelte Jansen's avatar
Jelte Jansen committed
402
                element = from_stringstream_map(in, file, line, pos);
403 404
                el_read = true;
                break;
405 406
            case EOF:
                break;
407
            default:
Jelte Jansen's avatar
Jelte Jansen committed
408
                throwParseError(std::string("error: unexpected character ") + c, file, line, pos);
409 410 411 412 413 414
                break;
        }
    }
    if (el_read) {
        return element;
    } else {
415
        throw ParseError("nothing read");
416 417 418
    }
}

419
ElementPtr
420
Element::createFromString(const std::string &in)
421 422 423
{
    std::stringstream ss;
    ss << in;
424
    return createFromString(ss, "<string>");
425
}
426

427 428 429 430 431 432 433
//
// a general to_str() function
//
std::string
IntElement::str()
{
    std::stringstream ss;
434
    ss << intValue();
435 436 437 438 439 440 441
    return ss.str();
}

std::string
DoubleElement::str()
{
    std::stringstream ss;
442
    ss << doubleValue();
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    return ss.str();
}

std::string
BoolElement::str()
{
    if (b) {
        return "True";
    } else {
        return "False";
    }
}

std::string
StringElement::str()
{
    std::stringstream ss;
    ss << "\"";
461
    ss << stringValue();
462 463 464 465 466 467 468 469 470 471
    ss << "\"";
    return ss.str();
}

std::string
ListElement::str()
{
    std::stringstream ss;
    std::vector<ElementPtr> v;
    ss << "[ ";
472
    v = listValue();
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    for (std::vector<ElementPtr>::iterator it = v.begin(); it != v.end(); ++it) {
        if (it != v.begin()) {
            ss << ", ";
        }
        ss << (*it)->str();
    }
    ss << " ]";
    return ss.str();
}

std::string
MapElement::str()
{
    std::stringstream ss;
    std::map<std::string, ElementPtr> m;
    ss << "{";
489
    m = mapValue();
490 491 492 493 494
    for (std::map<std::string, ElementPtr>::iterator it = m.begin(); it != m.end(); ++it) {
        if (it != m.begin()) {
            ss << ", ";
        }
        ss << "\"" << (*it).first << "\": ";
495 496 497 498 499
        if ((*it).second) {
            ss << (*it).second->str();
        } else {
            ss << "None";
        }
500 501 502 503 504
    }
    ss << "}";
    return ss.str();
}

505
// throws when one of the types in the path (except the one
506 507 508 509 510 511 512 513 514 515 516 517
// we're looking for) is not a MapElement
// returns 0 if it could simply not be found
// should that also be an exception?
ElementPtr
MapElement::find(const std::string& id)
{
    size_t sep = id.find('/');
    if (sep == std::string::npos) {
        return get(id);
    } else {
        ElementPtr ce = get(id.substr(0, sep));
        if (ce) {
518 519 520 521 522 523
            // ignore trailing slash
            if  (sep+1 != id.size()) {
                return ce->find(id.substr(sep+1));
            } else {
                return ce;
            }
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
        } else {
            return ElementPtr();
        }
    }
}

//
// Decode from wire format.
//

ElementPtr decode_element(std::stringstream& in, int& in_length);

static unsigned char
get_byte(std::stringstream& in)
{
    int c = in.get();
    if (c == EOF) {
        throw DecodeError("End of data while decoding wire format message");
    }

    return c;
}

std::string
decode_tag(std::stringstream& in, int& item_length)
{
    char buf[256];

    int len = get_byte(in);
    item_length--;

    in.read(buf, len);
    if (in.fail()) {
        throw DecodeError();
    }
    buf[len] = 0;
    item_length -= len;

    return std::string(buf, len);
}

Jelte Jansen's avatar
Jelte Jansen committed
565 566 567 568 569
ElementPtr
decode_bool(std::stringstream& in, int& item_length)
{
    char c;
    c = in.get();
570 571
    
    if (c == '1') {
Jelte Jansen's avatar
Jelte Jansen committed
572 573 574 575 576 577
        return Element::create(true);
    } else {
        return Element::create(false);
    }
}

578 579 580
ElementPtr
decode_int(std::stringstream& in, int& item_length)
{
581 582
    int skip, me;
    return from_stringstream_int_or_double(in, skip, me);
583 584
}

585 586 587 588 589 590 591
ElementPtr
decode_real(std::stringstream& in, int& item_length)
{
    int skip, me;
    return from_stringstream_int_or_double(in, skip, me);
}

592
ElementPtr
593 594 595 596 597 598
decode_blob(std::stringstream& in, int& item_length)
{
    char *buf = new char[item_length + 1];

    in.read(buf, item_length);
    if (in.fail()) {
599
        delete[] buf;
600 601 602 603 604 605 606 607 608 609 610 611 612 613
        throw DecodeError();
    }
    buf[item_length] = 0;

    std::string s = std::string(buf, item_length);
    item_length -= item_length;

    delete [] buf;
    return Element::create(s);
}

// XXXMLG currently identical to decode_blob
ElementPtr
decode_utf8(std::stringstream& in, int& item_length)
614 615 616 617 618
{
    char *buf = new char[item_length + 1];

    in.read(buf, item_length);
    if (in.fail()) {
619
        delete[] buf;
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
        throw DecodeError();
    }
    buf[item_length] = 0;

    std::string s = std::string(buf, item_length);
    item_length -= item_length;

    delete [] buf;
    return Element::create(s);
}

ElementPtr
decode_hash(std::stringstream& in, int& item_length)
{
    std::map<std::string, ElementPtr> m;
    std::pair<std::string, ElementPtr> p;

    while (item_length > 0) {
        p.first = decode_tag(in, item_length);
        p.second = decode_element(in, item_length);
        m.insert(p);
    }

    return Element::create(m);
}

ElementPtr
decode_list(std::stringstream& in, int& item_length)
{
    std::vector<ElementPtr> v;

    while (item_length > 0) {
        v.push_back(decode_element(in, item_length));
    }
    return Element::create(v);
}

ElementPtr
decode_null(std::stringstream& in, int& item_length)
{
    return Element::create("NULL");
}

ElementPtr
decode_element(std::stringstream& in, int& in_length)
{
    ElementPtr element;

    unsigned char type_and_length = get_byte(in);
    unsigned char type = type_and_length & ITEM_MASK;
    unsigned char lenbytes = type_and_length & ITEM_LENGTH_MASK;
    in_length--;

    int item_length = 0;
    switch (lenbytes) {
    case ITEM_LENGTH_32:
        item_length |= get_byte(in);
        item_length <<= 8;
        item_length |= get_byte(in);
        item_length <<= 8;
        in_length -= 2;  // only 2 here, we will get more later
    case ITEM_LENGTH_16:
        item_length |= get_byte(in);
        item_length <<= 8;
        in_length--;  // only 1 here
    case ITEM_LENGTH_8:
        item_length |= get_byte(in);
        in_length--;
    }

    in_length -= item_length;

    switch (type) {
Jelte Jansen's avatar
Jelte Jansen committed
693 694 695
    case ITEM_BOOL:
        element = decode_bool(in, item_length);
        break;
696 697 698
    case ITEM_INT:
        element = decode_int(in, item_length);
        break;
699 700 701
    case ITEM_REAL:
        element = decode_real(in, item_length);
        break;
702 703 704 705 706
    case ITEM_BLOB:
        element = decode_blob(in, item_length);
        break;
    case ITEM_UTF8:
        element = decode_utf8(in, item_length);
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
        break;
    case ITEM_HASH:
        element = decode_hash(in, item_length);
        break;
    case ITEM_LIST:
        element = decode_list(in, item_length);
        break;
    case ITEM_NULL:
        element = decode_null(in, item_length);
        break;
    }

    return (element);
}

ElementPtr
723
Element::fromWire(const std::string& s)
724 725 726
{
    std::stringstream ss;
    ss << s;
727
    return fromWire(ss, s.length());
728 729 730
}

ElementPtr
731
Element::fromWire(std::stringstream& in, int length)
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
{
    //
    // Check protocol version
    //
    for (int i = 0 ; i < 4 ; i++) {
        unsigned char version_byte = get_byte(in);
        if (PROTOCOL_VERSION[i] != version_byte) {
            throw DecodeError("Protocol version incorrect");
        }
    }
    length -= 4;

    ElementPtr element;
    element = decode_hash(in, length);
    return (element);
}

//
// Encode into wire format.
//

std::string
encode_length(unsigned int length, unsigned char type)
{
    std::stringstream ss;

    if (length <= 0x000000ff) {
        unsigned char val = (length & 0x000000ff);
        type |= ITEM_LENGTH_8;
        ss << type << val;
    } else if (length <= 0x0000ffff) {
763
        unsigned char val[2];
764 765 766
        val[0] = (length & 0x0000ff00) >> 8;
        val[1] = (length & 0x000000ff);
        type |= ITEM_LENGTH_16;
767
        ss << type << val[0] << val[1];
768
    } else {
769
        unsigned char val[4];
770 771 772 773 774
        val[0] = (length & 0xff000000) >> 24;
        val[1] = (length & 0x00ff0000) >> 16;
        val[2] = (length & 0x0000ff00) >> 8;
        val[3] = (length & 0x000000ff);
        type |= ITEM_LENGTH_32;
775
        ss << type << val[0] << val[1] << val[2] << val[3];
776 777 778 779 780
    }
    return ss.str();
}

std::string
Jelte Jansen's avatar
Jelte Jansen committed
781
Element::toWire(int omit_length)
782 783
{
    std::stringstream ss;
Jelte Jansen's avatar
Jelte Jansen committed
784 785 786
    toWire(ss, omit_length);
    return ss.str();
}
787

Jelte Jansen's avatar
Jelte Jansen committed
788 789 790
void
StringElement::toWire(std::stringstream& ss, int omit_length)
{
791
    unsigned int length = stringValue().length();
792
    ss << encode_length(length, ITEM_UTF8) << stringValue();
793 794
}

Jelte Jansen's avatar
Jelte Jansen committed
795 796
void
IntElement::toWire(std::stringstream& ss, int omit_length)
797 798 799 800 801
{
    std::stringstream text;

    text << str();
    int length = text.str().length();
802
    ss << encode_length(length, ITEM_INT) << text.str();
803 804
}

Jelte Jansen's avatar
Jelte Jansen committed
805 806
void
BoolElement::toWire(std::stringstream& ss, int omit_length)
807 808 809 810
{
    std::stringstream text;

    text << str();
Jelte Jansen's avatar
Jelte Jansen committed
811 812
    int length = 1;
    ss << encode_length(length, ITEM_BOOL);
813
    if (boolValue()) {
Jelte Jansen's avatar
Jelte Jansen committed
814 815 816 817
        ss << 0x01;
    } else {
        ss << 0x00;
    }
818 819
}

Jelte Jansen's avatar
Jelte Jansen committed
820 821
void
DoubleElement::toWire(std::stringstream& ss, int omit_length)
822 823 824 825 826
{
    std::stringstream text;

    text << str();
    int length = text.str().length();
827
    ss << encode_length(length, ITEM_REAL) << text.str();
828 829
}

Jelte Jansen's avatar
Jelte Jansen committed
830 831
void
ListElement::toWire(std::stringstream& ss, int omit_length)
832
{
Jelte Jansen's avatar
Jelte Jansen committed
833
    std::stringstream ss2;
834
    std::vector<ElementPtr> v;
835
    v = listValue();
836 837
    for (std::vector<ElementPtr>::iterator it = v.begin() ;
         it != v.end() ; ++it) {
Jelte Jansen's avatar
Jelte Jansen committed
838
        (*it)->toWire(ss2, 0);
839 840
    }

841

842
    if (omit_length) {
843 844 845 846
        stringbuf *ss2_buf = ss2.rdbuf();
        if (ss2_buf->in_avail() > 0) {
            ss << ss2_buf;
        }
847
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
848 849 850
        stringbuf *ss2_buf = ss2.rdbuf();
        ss2_buf->pubseekpos(0);
        ss << encode_length(ss2_buf->in_avail(), ITEM_LIST);
851 852 853
        if (ss2_buf->in_avail() > 0) {
            ss << ss2_buf;
        }
854 855 856
    }
}

Jelte Jansen's avatar
Jelte Jansen committed
857 858
void
encode_tag(std::stringstream& ss, const std::string &s)
859 860 861 862 863 864 865
{
    int length = s.length();
    unsigned char val = length & 0x000000ff;

    ss << val << s;
}

Jelte Jansen's avatar
Jelte Jansen committed
866 867
void
MapElement::toWire(std::stringstream& ss, int omit_length)
868
{
Jelte Jansen's avatar
Jelte Jansen committed
869
    std::stringstream ss2;
870 871 872 873 874 875
    std::map<std::string, ElementPtr> m;

    //
    // If we don't want the length, we will want the protocol header
    //
    if (omit_length) {
Jelte Jansen's avatar
Jelte Jansen committed
876 877
        ss2 << PROTOCOL_VERSION[0] << PROTOCOL_VERSION[1];
        ss2 << PROTOCOL_VERSION[2] << PROTOCOL_VERSION[3];
878 879
    }

880
    m = mapValue();
881 882
    for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
         it != m.end() ; ++it) {
Jelte Jansen's avatar
Jelte Jansen committed
883 884
        encode_tag(ss2, (*it).first);
        (*it).second->toWire(ss2, 0);
885 886 887 888 889 890
    }

    //
    // add length if needed
    //
    if (omit_length) {
891 892 893 894
        stringbuf *ss2_buf = ss2.rdbuf();
        if (ss2_buf->in_avail() > 0) {
            ss << ss2_buf;
        }
895
    } else {
Jelte Jansen's avatar
Jelte Jansen committed
896 897 898
        stringbuf *ss2_buf = ss2.rdbuf();
        ss2_buf->pubseekpos(0);
        ss << encode_length(ss2_buf->in_avail(), ITEM_HASH);
899 900 901
        if (ss2_buf->in_avail() > 0) {
            ss << ss2_buf;
        }
902 903 904 905 906 907
    }
}

bool
MapElement::find(const std::string& id, ElementPtr& t) {
    try {
Jelte Jansen's avatar
Jelte Jansen committed
908
        ElementPtr p = find(id);
909 910 911 912 913 914 915 916 917
        if (p) {
            t = p;
            return true;
        }
    } catch (TypeError e) {
        // ignore
    }
    return false;
}
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
bool
IntElement::equals(ElementPtr other)
{
    return (other->getType() == Element::integer) &&
           (i == other->intValue());
}

bool
DoubleElement::equals(ElementPtr other)
{
    return (other->getType() == Element::real) &&
           (d == other->doubleValue());
}

bool
BoolElement::equals(ElementPtr other)
{
    return (other->getType() == Element::boolean) &&
           (b == other->boolValue());
}

bool
StringElement::equals(ElementPtr other)
{
    return (other->getType() == Element::string) &&
           (s == other->stringValue());
}

bool
ListElement::equals(ElementPtr other)
{
    if (other->getType() == Element::list) {
        int s = size();
        if (s != other->size()) {
            return false;
        }
        for (int i = 0; i < s; i++) {
            if (!get(i)->equals(other->get(i))) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

bool
MapElement::equals(ElementPtr other)
{
    if (other->getType() == Element::map) {
        std::map<std::string, ElementPtr> m = mapValue();
        for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
             it != m.end() ; ++it) {
            if (other->contains((*it).first)) {
                if (!get((*it).first)->equals(other->get((*it).first))) {
                    return false;
                }
            } else {
                return false;
            }
        }
        // quickly walk through the other map too, to see if there's
        // anything in there that we don't have. We don't need to
        // compare those elements; if one of them is missing we
        // differ (and if it's not missing the loop above has checked
        // it)
        m = other->mapValue();
        for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
             it != m.end() ; ++it) {
            if (!contains((*it).first)) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

999
bool
1000
isc::data::isNull(ElementPtr p)
1001 1002 1003 1004
{
    return !p;
}

1005 1006 1007
void
isc::data::removeIdentical(ElementPtr a, const ElementPtr b)
{
1008 1009 1010
    if (!b) {
        return;
    }
1011 1012 1013
    if (a->getType() != Element::map || b->getType() != Element::map) {
        dns_throw(TypeError, "Non-map Elements passed to removeIdentical");
    }
1014

1015 1016 1017 1018 1019 1020 1021 1022 1023
    std::map<std::string, ElementPtr> m = a->mapValue();
    for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
         it != m.end() ; ++it) {
        if (b->contains((*it).first)) {
            if (a->get((*it).first)->equals(b->get((*it).first))) {
                a->remove((*it).first);
            }
        }
    }
1024
}
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
void
isc::data::merge(ElementPtr element, const ElementPtr other)
{
    if (element->getType() != Element::map ||
        other->getType() != Element::map) {
        dns_throw(TypeError, "merge arguments not MapElements");
    }
    
    std::map<std::string, ElementPtr> m = other->mapValue();
    for (std::map<std::string, ElementPtr>::iterator it = m.begin() ;
         it != m.end() ; ++it) {
        if ((*it).second) {
            element->set((*it).first, (*it).second);
        } else if (element->contains((*it).first)) {
            element->remove((*it).first);
        }
    }
1043
}
1044