data.h 31.5 KB
Newer Older
1
// Copyright (C) 2010-2017 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6

7 8
#ifndef ISC_DATA_H
#define ISC_DATA_H 1
9

Tomek Mrugalski's avatar
Tomek Mrugalski committed
10
#include <stdint.h>
11 12 13 14
#include <string>
#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>
15
#include <stdexcept>
16
#include <exceptions/exceptions.h>
17

Jelte Jansen's avatar
Jelte Jansen committed
18
namespace isc { namespace data {
19

20 21 22
class Element;
// todo: describe the rationale behind ElementPtr?
typedef boost::shared_ptr<Element> ElementPtr;
23
typedef boost::shared_ptr<const Element> ConstElementPtr;
24 25

///
26
/// @brief A standard Data module exception that is thrown if a function
27 28 29
/// is called for an Element that has a wrong type (e.g. int_value on a
/// ListElement)
///
30
class TypeError : public isc::Exception {
31
public:
Jelte Jansen's avatar
Jelte Jansen committed
32
    TypeError(const char* file, size_t line, const char* what) :
33
        isc::Exception(file, line, what) {}
34 35 36
};

///
37
/// @brief A standard Data module exception that is thrown if a parse
38 39
/// error is encountered when constructing an Element from a string
///
Jelte Jansen's avatar
Jelte Jansen committed
40 41 42
// i'd like to use Exception here but we need one that is derived from
// runtime_error (as this one is directly based on external data, and
// i want to add some values to any static data string that is provided)
43
class JSONError : public isc::Exception {
44
public:
45 46
    JSONError(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) {}
47 48 49
};

///
50
/// @brief The @c Element class represents a piece of data, used by
51 52
/// the command channel and configuration parts.
///
53
/// An @c Element can contain simple types (int, real, string, bool and
54 55 56
/// None), and composite types (list and string->element maps)
///
/// Elements should in calling functions usually be referenced through
57 58
/// an @c ElementPtr, which can be created using the factory functions
/// @c Element::create() and @c Element::fromJSON()
59 60 61 62
///
/// Notes to developers: Element is a base class, implemented by a
/// specific subclass for each type (IntElement, BoolElement, etc).
/// Element does define all functions for all types, and defaults to
63
/// raising a @c TypeError for functions that are not supported for
64 65 66
/// the type in question.
///
class Element {
67

68
public:
69
    /// @brief Represents the position of the data element within a
70
    /// configuration string.
71
    ///
72 73
    /// Position comprises a file name, line number and an offset within this
    /// line where the element value starts. For example, if the JSON string is
74
    ///
75
    /// @code
76 77 78 79
    /// { "foo": "some string",
    ///   "bar": 123 }
    /// \endcode
    ///
80
    /// the position of the element "bar" is: line_ = 2; pos_ = 9, because
81
    /// beginning of the value "123" is at offset 9 from the beginning of
82 83
    /// the second line, including whitespaces.
    ///
84
    /// Note that the @c Position structure is used as an argument to @c Element
85 86 87
    /// constructors and factory functions to avoid ambiguity and so that the
    /// uint32_t arguments holding line number and position within the line are
    /// not confused with the @c Element values passed to these functions.
88
    struct Position {
89 90 91
        std::string file_; ///< File name.
        uint32_t line_;    ///< Line number.
        uint32_t pos_;     ///< Position within the line.
92

93
        /// @brief Default constructor.
94 95
        Position() : file_(""), line_(0), pos_(0) {
        }
96

97
        /// @brief Constructor.
98
        ///
99 100 101
        /// @param file File name.
        /// @param line Line number.
        /// @param pos Position within the line.
102 103 104
        Position(const std::string& file, const uint32_t line,
                 const uint32_t pos)
            : file_(file), line_(line), pos_(pos) {
105
        }
106

107
        /// @brief Returns the position in the textual format.
108 109 110
        ///
        /// The returned position has the following format: file:line:pos.
        std::string str() const;
111 112
    };

113
    /// @brief Returns @c Position object with line_ and pos_ set to 0, and
114
    /// with an empty file name.
115 116
    ///
    /// The object containing two zeros is a default for most of the
117 118 119
    /// methods creating @c Element objects. The returned value is static
    /// so as it is not created everytime the function with the default
    /// position argument is called.
120
    static const Position& ZERO_POSITION() {
121
        static Position position("", 0, 0);
122 123 124
        return (position);
    }

125 126 127 128
private:
    // technically the type could be omitted; is it useful?
    // should we remove it or replace it with a pure virtual
    // function getType?
129 130
    int type_;

131
    /// @brief Position of the element in the configuration string.
132
    Position position_;
133 134

protected:
135

136
    /// @brief Constructor.
137
    ///
138 139
    /// @param t Element type.
    /// @param pos Structure holding position of the value of the data element.
140 141
    /// It comprises the line number and the position within this line. The values
    /// held in this structure are used for error logging purposes.
142 143 144
    Element(int t, const Position& pos = ZERO_POSITION())
        : type_(t), position_(pos) {
    }
145

146

147
public:
148

149 150
    // any is a special type used in list specifications, specifying
    // that the elements can be of any type
151
    enum types { integer, real, boolean, null, string, list, map, any };
152 153 154
    // base class; make dtor virtual
    virtual ~Element() {};

155
    /// @return the type of this element
156 157
    int getType() const { return (type_); }

158
    /// @brief Returns position where the data element's value starts in a
159 160 161 162
    /// configuration string.
    ///
    /// @warning The returned reference is valid as long as the object which
    /// created it lives.
163
    const Position& getPosition() const { return (position_); }
164

165 166 167
    /// Returns a string representing the Element and all its
    /// child elements; note that this is different from stringValue(),
    /// which only returns the single value of a StringElement
Jelte Jansen's avatar
Jelte Jansen committed
168 169
    ///
    /// The resulting string will contain the Element in JSON format.
170
    ///
171
    /// @return std::string containing the string representation
172
    std::string str() const;
173 174 175 176

    /// Returns the wireformat for the Element and all its child
    /// elements.
    ///
177
    /// @return std::string containing the element in wire format
178 179
    std::string toWire() const;
    void toWire(std::ostream& out) const;
180

181
    /// @brief Add the position to a TypeError message
182 183 184 185 186 187 188
    /// should be used in place of isc_throw(TypeError, error)
#define throwTypeError(error)                   \
    {                                           \
        std::string msg_ = error;               \
        if ((position_.file_ != "") ||          \
            (position_.line_ != 0) ||           \
            (position_.pos_ != 0)) {            \
189
            msg_ += " in (" + position_.str() + ")";   \
190 191 192 193
        }                                       \
        isc_throw(TypeError, msg_);             \
    }

194
    /// @name pure virtuals, every derived class must implement these
Jelte Jansen's avatar
Jelte Jansen committed
195

196
    /// @return true if the other ElementPtr has the same type and value
197
    virtual bool equals(const Element& other) const = 0;
198

Jelte Jansen's avatar
Jelte Jansen committed
199 200
    /// Converts the Element to JSON format and appends it to
    /// the given stringstream.
201
    virtual void toJSON(std::ostream& ss) const = 0;
Jelte Jansen's avatar
Jelte Jansen committed
202

203
    /// @name Type-specific getters
204
    ///
205
    /// @brief These functions only
206 207 208 209 210
    /// work on their corresponding Element type. For all other
    /// types, a TypeError is thrown.
    /// If you want an exception-safe getter method, use
    /// getValue() below
    //@{
211
    virtual int64_t intValue() const
212
    { throwTypeError("intValue() called on non-integer Element"); };
213
    virtual double doubleValue() const
214
    { throwTypeError("doubleValue() called on non-double Element"); };
215
    virtual bool boolValue() const
216
    { throwTypeError("boolValue() called on non-Bool Element"); };
217
    virtual std::string stringValue() const
218
    { throwTypeError("stringValue() called on non-string Element"); };
219
    virtual const std::vector<ElementPtr>& listValue() const {
220
        // replace with real exception or empty vector?
221
        throwTypeError("listValue() called on non-list Element");
222 223 224
    };
    virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
        // replace with real exception or empty map?
225
        throwTypeError("mapValue() called on non-map Element");
226
    };
227 228
    //@}

229
    /// @name Exception-safe getters
230
    ///
231
    /// @brief The getValue() functions return false if the given reference
232 233 234 235 236 237
    /// is of another type than the element contains
    /// By default it always returns false; the derived classes
    /// override the function for their type, copying their
    /// data to the given reference and returning true
    ///
    //@{
238
    virtual bool getValue(int64_t& t) const;
239 240 241
    virtual bool getValue(double& t) const;
    virtual bool getValue(bool& t) const;
    virtual bool getValue(std::string& t) const;
242
    virtual bool getValue(std::vector<ElementPtr>& t) const;
243
    virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
244
    //@}
245

246
    ///
247
    /// @name Exception-safe setters.
248
    ///
249
    /// @brief Return false if the Element is not
250 251 252
    /// the right type. Set the value and return true if the Elements
    /// is of the correct type
    ///
253 254
    /// Notes: Read notes of IntElement definition about the use of
    ///        long long int, long int and int.
255
    //@{
256 257 258
    virtual bool setValue(const long long int v);
    bool setValue(const long int i) { return (setValue(static_cast<long long int>(i))); };
    bool setValue(const int i) { return (setValue(static_cast<long long int>(i))); };
259 260 261
    virtual bool setValue(const double v);
    virtual bool setValue(const bool t);
    virtual bool setValue(const std::string& v);
262
    virtual bool setValue(const std::vector<ElementPtr>& v);
263
    virtual bool setValue(const std::map<std::string, ConstElementPtr>& v);
264 265 266 267 268 269
    //@}



    // Other functions for specific subtypes

270
    /// @name ListElement functions
271
    ///
272
    /// @brief If the Element on which these functions are called are not
273 274 275 276
    /// an instance of ListElement, a TypeError exception is thrown.
    //@{
    /// Returns the ElementPtr at the given index. If the index is out
    /// of bounds, this function throws an std::out_of_range exception.
277
    /// @param i The position of the ElementPtr to return
278
    virtual ConstElementPtr get(const int i) const;
279

280
    /// @brief returns element as non-const pointer
Tomek Mrugalski's avatar
Tomek Mrugalski committed
281
    ///
282 283
    /// @param i The position of the ElementPtr to retrieve
    /// @return specified element pointer
284
    virtual ElementPtr getNonConst(const int i) const;
285

286 287
    /// Sets the ElementPtr at the given index. If the index is out
    /// of bounds, this function throws an std::out_of_range exception.
288 289
    /// @param i The position of the ElementPtr to set
    /// @param element The ElementPtr to set at the position
290
    virtual void set(const size_t i, ElementPtr element);
291

292
    /// Adds an ElementPtr to the list
293
    /// @param element The ElementPtr to add
294
    virtual void add(ElementPtr element);
295

296 297
    /// Removes the element at the given position. If the index is out
    /// of nothing happens.
298
    /// @param i The index of the element to remove.
299
    virtual void remove(const int i);
300

301
    /// Returns the number of elements in the list.
302
    virtual size_t size() const;
303 304 305

    /// Return true if there are no elements in the list.
    virtual bool empty() const;
306
    //@}
307

308

309
    /// @name MapElement functions
310
    ///
311
    /// @brief If the Element on which these functions are called are not
312 313 314
    /// an instance of MapElement, a TypeError exception is thrown.
    //@{
    /// Returns the ElementPtr at the given key
315 316
    /// @param name The key of the Element to return
    /// @return The ElementPtr at the given key, or null if not present
317
    virtual ConstElementPtr get(const std::string& name) const;
318

319
    /// Sets the ElementPtr at the given key
320 321
    /// @param name The key of the Element to set
    /// @param element The ElementPtr to set at the given key.
322
    virtual void set(const std::string& name, ConstElementPtr element);
323

324
    /// Remove the ElementPtr at the given key
325
    /// @param name The key of the Element to remove
326
    virtual void remove(const std::string& name);
327

328
    /// Checks if there is data at the given key
329 330
    /// @param name The key of the Element to remove
    /// @return true if there is data at the key, false if not.
331
    virtual bool contains(const std::string& name) const;
332

333 334 335 336 337 338 339 340 341
    /// Recursively finds any data at the given identifier. The
    /// identifier is a /-separated list of names of nested maps, with
    /// the last name being the leaf that is returned.
    ///
    /// For instance, if you have a MapElement that contains another
    /// MapElement at the key "foo", and that second MapElement contains
    /// Another Element at key "bar", the identifier for that last
    /// element from the first is "foo/bar".
    ///
342 343
    /// @param identifier The identifier of the element to find
    /// @return The ElementPtr at the given identifier. Returns a
344 345
    /// null ElementPtr if it is not found, which can be checked with
    /// Element::is_null(ElementPtr e).
346
    virtual ConstElementPtr find(const std::string& identifier) const;
347

348 349 350 351
    /// See @c Element::find()
    /// @param identifier The identifier of the element to find
    /// @param t Reference to store the resulting ElementPtr, if found.
    /// @return true if the element was found, false if not.
352
    virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
353 354
    //@}

355

356
    /// @name Factory functions
357

358 359 360 361
    // TODO: should we move all factory functions to a different class
    // so as not to burden the Element base with too many functions?
    // and/or perhaps even to a separate header?

362 363
    /// @name Direct factory functions
    /// @brief These functions simply wrap the given data directly
364
    /// in an Element object, and return a reference to it, in the form
365
    /// of an @c ElementPtr.
366 367 368
    /// These factory functions are exception-free (unless there is
    /// no memory available, in which case bad_alloc is raised by the
    /// underlying system).
369 370
    /// (Note that that is different from an NullElement, which
    /// represents an empty value, and is created with Element::create())
371 372 373
    ///
    /// Notes: Read notes of IntElement definition about the use of
    ///        long long int, long int and int.
374
    //@{
375 376 377 378
    static ElementPtr create(const Position& pos = ZERO_POSITION());
    static ElementPtr create(const long long int i,
                             const Position& pos = ZERO_POSITION());
    static ElementPtr create(const int i,
379
                             const Position& pos = ZERO_POSITION());
380
    static ElementPtr create(const long int i,
381
                             const Position& pos = ZERO_POSITION());
382 383 384 385 386 387
    static ElementPtr create(const double d,
                             const Position& pos = ZERO_POSITION());
    static ElementPtr create(const bool b,
                             const Position& pos = ZERO_POSITION());
    static ElementPtr create(const std::string& s,
                             const Position& pos = ZERO_POSITION());
388 389
    // need both std:string and char *, since c++ will match
    // bool before std::string when you pass it a char *
390
    static ElementPtr create(const char *s,
391
                             const Position& pos = ZERO_POSITION());
392

393
    /// @brief Creates an empty ListElement type ElementPtr.
394
    ///
395
    /// @param pos A structure holding position of the data element value
396
    /// in the configuration string. It is used for error logging purposes.
397
    static ElementPtr createList(const Position& pos = ZERO_POSITION());
398

399
    /// @brief Creates an empty MapElement type ElementPtr.
400
    ///
401
    /// @param pos A structure holding position of the data element value
402
    /// in the configuration string. It is used for error logging purposes.
403
    static ElementPtr createMap(const Position& pos = ZERO_POSITION());
404 405
    //@}

406

407
    /// @name Compound factory functions
408

409
    /// @brief These functions will parse the given string (JSON)
Jelte Jansen's avatar
Jelte Jansen committed
410
    /// representation  of a compound element. If there is a parse
Jelte Jansen's avatar
Jelte Jansen committed
411
    /// error, an exception of the type isc::data::JSONError is thrown.
412 413

    //@{
414
    /// Creates an Element from the given JSON string
415 416
    /// @param in The string to parse the element from
    /// @param preproc specified whether preprocessing (e.g. comment removal)
417
    ///                should be performed
418
    /// @return An ElementPtr that contains the element(s) specified
419
    /// in the given string.
420 421 422 423 424
    static ElementPtr fromJSON(const std::string& in, bool preproc = false);

    /// Creates an Element from the given input stream containing JSON
    /// formatted data.
    ///
425 426
    /// @param in The string to parse the element from
    /// @param preproc specified whether preprocessing (e.g. comment removal)
427
    ///                should be performed
428
    /// @return An ElementPtr that contains the element(s) specified
429 430 431 432
    /// in the given input stream.
    static ElementPtr fromJSON(std::istream& in, bool preproc = false)
        throw(JSONError);

433 434 435
    /// Creates an Element from the given input stream containing JSON
    /// formatted data.
    ///
436 437 438
    /// @param in The string to parse the element from
    /// @param file_name specified input file name (used in error reporting)
    /// @param preproc specified whether preprocessing (e.g. comment removal)
439
    ///                should be performed
440
    /// @return An ElementPtr that contains the element(s) specified
441
    /// in the given input stream.
442 443
    static ElementPtr fromJSON(std::istream& in, const std::string& file_name,
                               bool preproc = false)
444
        throw(JSONError);
445

446 447 448
    /// Creates an Element from the given input stream, where we keep
    /// track of the location in the stream for error reporting.
    ///
449 450 451
    /// @param in The string to parse the element from.
    /// @param file The input file name.
    /// @param line A reference to the int where the function keeps
452
    /// track of the current line.
453
    /// @param pos A reference to the int where the function keeps
454
    /// track of the current position within the current line.
455
    /// @return An ElementPtr that contains the element(s) specified
456 457
    /// in the given input stream.
    // make this one private?
458 459 460
    static ElementPtr fromJSON(std::istream& in, const std::string& file,
                               int& line, int &pos)
        throw(JSONError);
461 462 463 464 465 466 467 468 469 470

    /// Reads contents of specified file and interprets it as JSON.
    ///
    /// @param file_name name of the file to read
    /// @param preproc specified whether preprocessing (e.g. comment removal)
    ///                should be performed
    /// @return An ElementPtr that contains the element(s) specified
    /// if the given file.
    static ElementPtr fromJSONFile(const std::string& file_name,
                                   bool preproc = false);
471 472
    //@}

473
    /// @name Type name conversion functions
474 475 476

    /// Returns the name of the given type as a string
    ///
477 478
    /// @param type The type to return the name of
    /// @return The name of the type, or "unknown" if the type
479 480 481 482 483 484
    ///         is not known.
    static std::string typeToName(Element::types type);

    /// Converts the string to the corresponding type
    /// Throws a TypeError if the name is unknown.
    ///
485 486
    /// @param type_name The name to get the type of
    /// @return the corresponding type value
487 488
    static Element::types nameToType(const std::string& type_name);

489
    /// @brief input text preprocessor
490 491 492 493 494
    ///
    /// This method performs preprocessing of the input stream (which is
    /// expected to contain a text version of to be parsed JSON). For now the
    /// sole supported operation is bash-style (line starting with #) comment
    /// removal, but it will be extended later to cover more cases (C, C++ style
495
    /// comments, file inclusions, maybe macro replacements?).
496
    ///
497 498 499
    /// This method processes the whole input stream. It reads all contents of
    /// the input stream, filters the content and returns the result in a
    /// different stream.
500 501
    ///
    /// @param in input stream to be preprocessed
502 503
    /// @param out output stream (filtered content will be written here)
    static void preprocess(std::istream& in, std::stringstream& out);
504

505
    /// @name Wire format factory functions
506 507 508 509

    /// These function pparse the wireformat at the given stringstream
    /// (of the given length). If there is a parse error an exception
    /// of the type isc::cc::DecodeError is raised.
510

511 512 513
    //@{
    /// Creates an Element from the wire format in the given
    /// stringstream of the given length.
514
    /// Since the wire format is JSON, this is the same as
515
    /// fromJSON, and could be removed.
Jelte Jansen's avatar
Jelte Jansen committed
516
    ///
517 518 519
    /// @param in The input stringstream.
    /// @param length The length of the wireformat data in the stream
    /// @return ElementPtr with the data that is parsed.
520
    static ElementPtr fromWire(std::stringstream& in, int length);
Jelte Jansen's avatar
Jelte Jansen committed
521

522
    /// Creates an Element from the wire format in the given string
523
    /// Since the wire format is JSON, this is the same as
524
    /// fromJSON, and could be removed.
Jelte Jansen's avatar
Jelte Jansen committed
525
    ///
526 527
    /// @param s The input string
    /// @return ElementPtr with the data that is parsed.
528 529 530 531
    static ElementPtr fromWire(const std::string& s);
    //@}
};

532 533 534 535 536
/// Notes: IntElement type is changed to int64_t.
///        Due to C++ problems on overloading and automatic type conversion,
///          (C++ tries to convert integer type values and reference/pointer
///           if value types do not match exactly)
///        We decided the storage as int64_t,
537
///           three (long long, long, int) override function definitions
538 539 540 541
///           and cast int/long/long long to int64_t via long long.
///        Therefore, call by value methods (create, setValue) have three
///        (int,long,long long) definitions. Others use int64_t.
///
542
class IntElement : public Element {
543 544
    int64_t i;
private:
545 546

public:
547 548
    IntElement(int64_t v, const Position& pos = ZERO_POSITION())
        : Element(integer, pos), i(v) { }
549
    int64_t intValue() const { return (i); }
550
    using Element::getValue;
551
    bool getValue(int64_t& t) const { t = i; return (true); }
552
    using Element::setValue;
553
    bool setValue(long long int v) { i = v; return (true); }
554 555
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
556 557 558 559 560 561
};

class DoubleElement : public Element {
    double d;

public:
562 563
    DoubleElement(double v, const Position& pos = ZERO_POSITION())
        : Element(real, pos), d(v) {};
564
    double doubleValue() const { return (d); }
565
    using Element::getValue;
566
    bool getValue(double& t) const { t = d; return (true); }
567
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
568
    bool setValue(const double v) { d = v; return (true); }
569 570
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
571 572 573 574 575 576
};

class BoolElement : public Element {
    bool b;

public:
577 578
    BoolElement(const bool v, const Position& pos = ZERO_POSITION())
        : Element(boolean, pos), b(v) {};
579
    bool boolValue() const { return (b); }
580
    using Element::getValue;
581
    bool getValue(bool& t) const { t = b; return (true); }
582
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
583
    bool setValue(const bool v) { b = v; return (true); }
584 585
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
586 587 588 589
};

class NullElement : public Element {
public:
590 591
    NullElement(const Position& pos = ZERO_POSITION())
        : Element(null, pos) {};
592 593
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
594 595 596 597 598 599
};

class StringElement : public Element {
    std::string s;

public:
600 601
    StringElement(std::string v, const Position& pos = ZERO_POSITION())
        : Element(string, pos), s(v) {};
602
    std::string stringValue() const { return (s); }
603
    using Element::getValue;
604
    bool getValue(std::string& t) const { t = s; return (true); }
605
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
606
    bool setValue(const std::string& v) { s = v; return (true); }
607 608
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
609 610 611
};

class ListElement : public Element {
612
    std::vector<ElementPtr> l;
613 614

public:
615 616
    ListElement(const Position& pos = ZERO_POSITION())
        : Element(list, pos) {}
617
    const std::vector<ElementPtr>& listValue() const { return (l); }
618
    using Element::getValue;
619
    bool getValue(std::vector<ElementPtr>& t) const {
620 621 622
        t = l;
        return (true);
    }
623
    using Element::setValue;
624
    bool setValue(const std::vector<ElementPtr>& v) {
625 626 627
        l = v;
        return (true);
    }
628
    using Element::get;
629
    ConstElementPtr get(int i) const { return (l.at(i)); }
630
    ElementPtr getNonConst(int i) const  { return (l.at(i)); }
631
    using Element::set;
632
    void set(size_t i, ElementPtr e) {
633 634
        l.at(i) = e;
    }
635
    void add(ElementPtr e) { l.push_back(e); };
636
    using Element::remove;
637
    void remove(int i) { l.erase(l.begin() + i); };
638 639
    void toJSON(std::ostream& ss) const;
    size_t size() const { return (l.size()); }
640
    bool empty() const { return (l.empty()); }
641
    bool equals(const Element& other) const;
642 643 644
};

class MapElement : public Element {
645
    std::map<std::string, ConstElementPtr> m;
646 647

public:
648 649 650
    MapElement(const Position& pos = ZERO_POSITION()) : Element(map, pos) {}
    // @todo should we have direct iterators instead of exposing the std::map
    // here?
651 652 653
    const std::map<std::string, ConstElementPtr>& mapValue() const {
        return (m);
    }
654
    using Element::getValue;
655
    bool getValue(std::map<std::string, ConstElementPtr>& t) const {
656 657 658
        t = m;
        return (true);
    }
659
    using Element::setValue;
660
    bool setValue(const std::map<std::string, ConstElementPtr>& v) {
661 662 663
        m = v;
        return (true);
    }
664
    using Element::get;
665
    ConstElementPtr get(const std::string& s) const {
666 667
        return (contains(s) ? m.find(s)->second : ConstElementPtr());
    }
668
    using Element::set;
669
    void set(const std::string& key, ConstElementPtr value);
670
    using Element::remove;
671
    void remove(const std::string& s) { m.erase(s); }
672 673 674 675
    bool contains(const std::string& s) const {
        return (m.find(s) != m.end());
    }
    void toJSON(std::ostream& ss) const;
676

677 678 679 680 681
    // we should name the two finds better...
    // find the element at id; raises TypeError if one of the
    // elements at path except the one we're looking for is not a
    // mapelement.
    // returns an empty element if the item could not be found
682
    ConstElementPtr find(const std::string& id) const;
683 684 685

    // find the Element at 'id', and store the element pointer in t
    // returns true if found, or false if not found (either because
686
    // it doesn't exist or one of the elements in the path is not
687
    // a MapElement)
688
    bool find(const std::string& id, ConstElementPtr& t) const;
689

690 691 692 693 694 695 696
    /// @brief Returns number of stored elements
    ///
    /// @return number of elements.
    size_t size() const {
        return (m.size());
    }

697
    bool equals(const Element& other) const;
698 699 700
};

/// Checks whether the given ElementPtr is a NULL pointer
701 702
/// @param p The ElementPtr to check
/// @return true if it is NULL, false if not.
703
bool isNull(ConstElementPtr p);
704

705
///
706
/// @brief Remove all values from the first ElementPtr that are
707
/// equal in the second. Both ElementPtrs MUST be MapElements
708 709 710 711
/// The use for this function is to end up with a MapElement that
/// only contains new and changed values (for ModuleCCSession and
/// configuration update handlers)
/// Raises a TypeError if a or b are not MapElements
712 713
void removeIdentical(ElementPtr a, ConstElementPtr b);

714
/// @brief Create a new ElementPtr from the first ElementPtr, removing all
715 716 717 718 719
/// values that are equal in the second. Both ElementPtrs MUST be MapElements.
/// The returned ElementPtr will be a MapElement that only contains new and
/// changed values (for ModuleCCSession and configuration update handlers).
/// Raises a TypeError if a or b are not MapElements
ConstElementPtr removeIdentical(ConstElementPtr a, ConstElementPtr b);
720

721
/// @brief Merges the data from other into element.
722 723 724 725
/// (on the first level). Both elements must be
/// MapElements.
/// Every string,value pair in other is copied into element
/// (the ElementPtr of value is copied, this is not a new object)
Jelte Jansen's avatar
Jelte Jansen committed
726 727 728 729 730 731
/// Unless the value is a NullElement, in which case the
/// key is removed from element, rather than setting the value to
/// the given NullElement.
/// This way, we can remove values from for instance maps with
/// configuration data (which would then result in reverting back
/// to the default).
732
/// Raises a TypeError if either ElementPtr is not a MapElement
733
void merge(ElementPtr element, ConstElementPtr other);
734

735
/// @brief Copy the data up to a nesting level.
736 737 738 739
///
/// The copy is a deep copy so nothing is shared if it is not
/// under the given nesting level.
///
740 741
/// @param from the pointer to the element to copy
/// @param level nesting level (default is 100, 0 means shallow copy,
742
/// negative means outbound and perhaps looping forever).
743
/// @return a pointer to a fresh copy
744 745 746
/// \throw raises a BadValue is a null pointer occurs.
ElementPtr copy(ConstElementPtr from, int level = 100); 

747
/// @brief Compares the data with other using unordered lists
748 749 750 751 752 753
///
/// This comparison function handles lists (JSON arrays) as
/// unordered multi sets (multi means an item can occurs more
/// than once as soon as it occurs the same number of times).
bool isEquivalent(ConstElementPtr a, ConstElementPtr b);

754
/// @brief Pretty prints the data into stream.
755
///
756 757 758
/// This operator converts the @c ConstElementPtr into a string and
/// inserts it into the output stream @c out with an initial
/// indentation @c indent and add at each level @c step spaces.
759
///
760 761 762 763
/// @param element A @c ConstElementPtr to pretty print
/// @param out A @c std::ostream on which the print operation is performed
/// @param indent An initial number of spaces to add each new line
/// @param step A number of spaces to add to indentation at a new level
764 765 766
void prettyPrint(ConstElementPtr element, std::ostream& out,
                 unsigned indent = 0, unsigned step = 2);

767
/// @brief Pretty prints the data into string
768
///
769 770
/// This operator converts the @c ConstElementPtr into a string with
/// an initial indentation @c indent and add at each level @c step spaces.
771
///
772 773 774 775
/// @param element A @c ConstElementPtr to pretty print
/// @param indent An initial number of spaces to add each new line
/// @param step A number of spaces to add to indentation at a new level
/// @return a string where element was pretty printed
776 777 778
std::string prettyPrint(ConstElementPtr element,
                        unsigned indent = 0, unsigned step = 2);

779
///
780
/// @brief Insert Element::Position as a string into stream.
781
///
782 783
/// This operator converts the @c Element::Position into a string and
/// inserts it into the output stream @c out.
784
///
785
/// @param out A @c std::ostream object on which the insertion operation is
786
/// performed.
787 788 789
/// @param pos The @c Element::Position structure to insert.
/// @return A reference to the same @c std::ostream object referenced by
/// parameter @c out after the insertion operation.
790 791
std::ostream& operator<<(std::ostream& out, const Element::Position& pos);

792
///
793
/// @brief Insert the Element as a string into stream.
794
///
795 796 797
/// This method converts the @c ElementPtr into a string with
/// @c Element::str() and inserts it into the
/// output stream @c out.
798 799
///
/// This function overloads the global operator<< to behave as described in
800
/// ostream::operator<< but applied to @c ElementPtr objects.
801
///
802
/// @param out A @c std::ostream object on which the insertion operation is
803
/// performed.
804 805 806
/// @param e The @c ElementPtr object to insert.
/// @return A reference to the same @c std::ostream object referenced by
/// parameter @c out after the insertion operation.
807
std::ostream& operator<<(std::ostream& out, const Element& e);
808

809 810
bool operator==(const Element& a, const Element& b);
bool operator!=(const Element& a, const Element& b);
JINMEI Tatuya's avatar
JINMEI Tatuya committed
811
} }