data.h 29.3 KB
Newer Older
1
// Copyright (C) 2010, 2014  Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// 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.

15 16
#ifndef ISC_DATA_H
#define ISC_DATA_H 1
17

Tomek Mrugalski's avatar
Tomek Mrugalski committed
18
#include <stdint.h>
19 20 21 22
#include <string>
#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>
23
#include <stdexcept>
24
#include <exceptions/exceptions.h>
25

Jelte Jansen's avatar
Jelte Jansen committed
26
namespace isc { namespace data {
27

28 29 30
class Element;
// todo: describe the rationale behind ElementPtr?
typedef boost::shared_ptr<Element> ElementPtr;
31
typedef boost::shared_ptr<const Element> ConstElementPtr;
32 33 34 35 36 37

///
/// \brief A standard Data module exception that is thrown if a function
/// is called for an Element that has a wrong type (e.g. int_value on a
/// ListElement)
///
38
class TypeError : public isc::Exception {
39
public:
Jelte Jansen's avatar
Jelte Jansen committed
40
    TypeError(const char* file, size_t line, const char* what) :
41
        isc::Exception(file, line, what) {}
42 43 44 45 46 47
};

///
/// \brief A standard Data module exception that is thrown if a parse
/// error is encountered when constructing an Element from a string
///
Jelte Jansen's avatar
Jelte Jansen committed
48 49 50
// 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)
51
class JSONError : public isc::Exception {
52
public:
53 54
    JSONError(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) {}
55 56 57 58 59 60 61 62 63 64 65
};

///
/// \brief The \c Element class represents a piece of data, used by
/// the command channel and configuration parts.
///
/// An \c Element can contain simple types (int, real, string, bool and
/// None), and composite types (list and string->element maps)
///
/// Elements should in calling functions usually be referenced through
/// an \c ElementPtr, which can be created using the factory functions
66
/// \c Element::create() and \c Element::fromJSON()
67 68 69 70 71 72 73 74
///
/// 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
/// raising a \c TypeError for functions that are not supported for
/// the type in question.
///
class Element {
75

76 77 78
public:
    /// \brief Represents the position of the data element within a
    /// configuration string.
79
    ///
80 81
    /// 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
82 83 84 85 86 87
    ///
    /// \code
    /// { "foo": "some string",
    ///   "bar": 123 }
    /// \endcode
    ///
88
    /// the position of the element "bar" is: line_ = 2; pos_ = 9, because
89 90 91
    /// begining of the value "123" is at offset 9 from the beginning of
    /// the second line, including whitespaces.
    ///
92
    /// Note that the @c Position structure is used as an argument to @c Element
93 94 95
    /// 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.
96
    struct Position {
97 98 99
        std::string file_; ///< File name.
        uint32_t line_;    ///< Line number.
        uint32_t pos_;     ///< Position within the line.
100

101 102 103
        /// \brief Default constructor.
        Position() : file_(""), line_(0), pos_(0) {
        }
104 105 106

        /// \brief Constructor.
        ///
107
        /// \param file File name.
108 109
        /// \param line Line number.
        /// \param pos Position within the line.
110 111 112
        Position(const std::string& file, const uint32_t line,
                 const uint32_t pos)
            : file_(file), line_(line), pos_(pos) {
113
        }
114 115 116 117 118

        /// \brief Returns the position in the textual format.
        ///
        /// The returned position has the following format: file:line:pos.
        std::string str() const;
119 120
    };

121 122
    /// \brief Returns @c Position object with line_ and pos_ set to 0, and
    /// with an empty file name.
123 124
    ///
    /// The object containing two zeros is a default for most of the
125 126 127
    /// 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.
128
    static const Position& ZERO_POSITION() {
129
        static Position position("", 0, 0);
130 131 132
        return (position);
    }

133 134 135 136
private:
    // technically the type could be omitted; is it useful?
    // should we remove it or replace it with a pure virtual
    // function getType?
137 138 139 140
    int type_;

    /// \brief Position of the element in the configuration string.
    Position position_;
141 142

protected:
143 144 145 146

    /// \brief Constructor.
    ///
    /// \param t Element type.
147 148 149
    /// \param pos Structure holding position of the value of the data element.
    /// It comprises the line number and the position within this line. The values
    /// held in this structure are used for error logging purposes.
150 151 152
    Element(int t, const Position& pos = ZERO_POSITION())
        : type_(t), position_(pos) {
    }
153

154

155
public:
156

157 158
    // any is a special type used in list specifications, specifying
    // that the elements can be of any type
159
    enum types { integer, real, boolean, null, string, list, map, any };
160 161 162 163
    // base class; make dtor virtual
    virtual ~Element() {};

    /// \return the type of this element
164 165
    int getType() const { return (type_); }

166 167 168 169 170
    /// \brief Returns position where the data element's value starts in a
    /// configuration string.
    ///
    /// @warning The returned reference is valid as long as the object which
    /// created it lives.
171
    const Position& getPosition() const { return (position_); }
172

173 174 175
    /// 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
176 177
    ///
    /// The resulting string will contain the Element in JSON format.
178 179
    ///
    /// \return std::string containing the string representation
180
    std::string str() const;
181 182 183 184 185

    /// Returns the wireformat for the Element and all its child
    /// elements.
    ///
    /// \return std::string containing the element in wire format
186 187
    std::string toWire() const;
    void toWire(std::ostream& out) const;
188

189
    /// \name pure virtuals, every derived class must implement these
Jelte Jansen's avatar
Jelte Jansen committed
190

191
    /// \return true if the other ElementPtr has the same type and value
192
    virtual bool equals(const Element& other) const = 0;
193

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

198 199 200 201 202 203 204 205
    /// \name Type-specific getters
    ///
    /// \brief These functions only
    /// 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
    //@{
206
    virtual int64_t intValue() const
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    { isc_throw(TypeError, "intValue() called on non-integer Element"); };
    virtual double doubleValue() const
    { isc_throw(TypeError, "doubleValue() called on non-double Element"); };
    virtual bool boolValue() const
    { isc_throw(TypeError, "boolValue() called on non-Bool Element"); };
    virtual std::string stringValue() const
    { isc_throw(TypeError, "stringValue() called on non-string Element"); };
    virtual const std::vector<ConstElementPtr>& listValue() const {
        // replace with real exception or empty vector?
        isc_throw(TypeError, "listValue() called on non-list Element");
    };
    virtual const std::map<std::string, ConstElementPtr>& mapValue() const {
        // replace with real exception or empty map?
        isc_throw(TypeError, "mapValue() called on non-map Element");
    };
222 223 224 225 226 227 228 229 230 231 232
    //@}

    /// \name Exception-safe getters
    ///
    /// \brief The getValue() functions return false if the given reference
    /// 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
    ///
    //@{
233
    virtual bool getValue(int64_t& t) const;
234 235 236 237 238
    virtual bool getValue(double& t) const;
    virtual bool getValue(bool& t) const;
    virtual bool getValue(std::string& t) const;
    virtual bool getValue(std::vector<ConstElementPtr>& t) const;
    virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
239
    //@}
240

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



    // Other functions for specific subtypes

    /// \name ListElement functions
    ///
    /// \brief If the Element on which these functions are called are not
    /// 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.
    /// \param i The position of the ElementPtr to return
273
    virtual ConstElementPtr get(const int i) const;
274

275 276 277 278
    /// Sets the ElementPtr at the given index. If the index is out
    /// of bounds, this function throws an std::out_of_range exception.
    /// \param i The position of the ElementPtr to set
    /// \param element The ElementPtr to set at the position
279
    virtual void set(const size_t i, ConstElementPtr element);
280

281 282
    /// Adds an ElementPtr to the list
    /// \param element The ElementPtr to add
283
    virtual void add(ConstElementPtr element);
284

285 286 287
    /// Removes the element at the given position. If the index is out
    /// of nothing happens.
    /// \param i The index of the element to remove.
288
    virtual void remove(const int i);
289

290
    /// Returns the number of elements in the list.
291
    virtual size_t size() const;
292 293 294

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

297

298 299 300 301 302 303 304
    /// \name MapElement functions
    ///
    /// \brief If the Element on which these functions are called are not
    /// an instance of MapElement, a TypeError exception is thrown.
    //@{
    /// Returns the ElementPtr at the given key
    /// \param name The key of the Element to return
305
    /// \return The ElementPtr at the given key, or null if not present
306
    virtual ConstElementPtr get(const std::string& name) const;
307

308 309
    /// Sets the ElementPtr at the given key
    /// \param name The key of the Element to set
310
    /// \param element The ElementPtr to set at the given key.
311
    virtual void set(const std::string& name, ConstElementPtr element);
312

313 314
    /// Remove the ElementPtr at the given key
    /// \param name The key of the Element to remove
315
    virtual void remove(const std::string& name);
316

317 318 319
    /// Checks if there is data at the given key
    /// \param name The key of the Element to remove
    /// \return true if there is data at the key, false if not.
320
    virtual bool contains(const std::string& name) const;
321

322 323 324 325 326 327 328 329 330 331 332 333 334
    /// 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".
    ///
    /// \param identifier The identifier of the element to find
    /// \return The ElementPtr at the given identifier. Returns a
    /// null ElementPtr if it is not found, which can be checked with
    /// Element::is_null(ElementPtr e).
335
    virtual ConstElementPtr find(const std::string& identifier) const;
336

337 338 339 340
    /// 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.
341
    virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
342 343
    //@}

344

345
    /// \name Factory functions
346

347 348 349 350 351 352 353 354
    // 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?

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

    /// \brief Creates an empty ListElement type ElementPtr.
383
    ///
384 385
    /// \param pos A structure holding position of the data element value
    /// in the configuration string. It is used for error logging purposes.
386
    static ElementPtr createList(const Position& pos = ZERO_POSITION());
387

388
    /// \brief Creates an empty MapElement type ElementPtr.
389
    ///
390 391
    /// \param pos A structure holding position of the data element value
    /// in the configuration string. It is used for error logging purposes.
392
    static ElementPtr createMap(const Position& pos = ZERO_POSITION());
393 394
    //@}

395

396 397
    /// \name Compound factory functions

Jelte Jansen's avatar
Jelte Jansen committed
398 399
    /// \brief These functions will parse the given string (JSON)
    /// representation  of a compound element. If there is a parse
Jelte Jansen's avatar
Jelte Jansen committed
400
    /// error, an exception of the type isc::data::JSONError is thrown.
401 402

    //@{
403
    /// Creates an Element from the given JSON string
404
    /// \param in The string to parse the element from
405 406
    /// \param preproc specified whether preprocessing (e.g. comment removal)
    ///                should be performed
407 408
    /// \return An ElementPtr that contains the element(s) specified
    /// in the given string.
409 410 411 412 413 414 415 416 417 418 419 420 421
    static ElementPtr fromJSON(const std::string& in, bool preproc = false);

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

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

435 436 437
    /// Creates an Element from the given input stream, where we keep
    /// track of the location in the stream for error reporting.
    ///
438 439
    /// \param in The string to parse the element from.
    /// \param file The input file name.
440 441
    /// \param line A reference to the int where the function keeps
    /// track of the current line.
442
    /// \param pos A reference to the int where the function keeps
443 444 445 446
    /// track of the current position within the current line.
    /// \return An ElementPtr that contains the element(s) specified
    /// in the given input stream.
    // make this one private?
447 448 449
    static ElementPtr fromJSON(std::istream& in, const std::string& file,
                               int& line, int &pos)
        throw(JSONError);
450 451 452 453 454 455 456 457 458 459

    /// 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);
460 461
    //@}

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    /// \name Type name conversion functions

    /// Returns the name of the given type as a string
    ///
    /// \param type The type to return the name of
    /// \return The name of the type, or "unknown" if the type
    ///         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.
    ///
    /// \param type_name The name to get the type of
    /// \return the corresponding type value
    static Element::types nameToType(const std::string& type_name);

478 479 480 481 482 483
    /// \brief input text preprocessor
    ///
    /// 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
484
    /// comments, file inclusions, maybe macro replacements?).
485
    ///
486 487 488
    /// 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.
489 490
    ///
    /// @param in input stream to be preprocessed
491 492
    /// @param out output stream (filtered content will be written here)
    static void preprocess(std::istream& in, std::stringstream& out);
493

494 495 496 497 498
    /// \name Wire format factory functions

    /// 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.
499

500 501 502
    //@{
    /// Creates an Element from the wire format in the given
    /// stringstream of the given length.
Jelte Jansen's avatar
Jelte Jansen committed
503
    /// Since the wire format is JSON, thise is the same as
504
    /// fromJSON, and could be removed.
Jelte Jansen's avatar
Jelte Jansen committed
505
    ///
506 507 508 509
    /// \param in The input stringstream.
    /// \param length The length of the wireformat data in the stream
    /// \return ElementPtr with the data that is parsed.
    static ElementPtr fromWire(std::stringstream& in, int length);
Jelte Jansen's avatar
Jelte Jansen committed
510

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

521 522 523 524 525
/// 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,
526
///           three (long long, long, int) override function definitions
527 528 529 530
///           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.
///
531
class IntElement : public Element {
532 533
    int64_t i;
private:
534 535

public:
536 537
    IntElement(int64_t v, const Position& pos = ZERO_POSITION())
        : Element(integer, pos), i(v) { }
538
    int64_t intValue() const { return (i); }
539
    using Element::getValue;
540
    bool getValue(int64_t& t) const { t = i; return (true); }
541
    using Element::setValue;
542
    bool setValue(long long int v) { i = v; return (true); }
543 544
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
545 546 547 548 549 550
};

class DoubleElement : public Element {
    double d;

public:
551 552
    DoubleElement(double v, const Position& pos = ZERO_POSITION())
        : Element(real, pos), d(v) {};
553
    double doubleValue() const { return (d); }
554
    using Element::getValue;
555
    bool getValue(double& t) const { t = d; return (true); }
556
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
557
    bool setValue(const double v) { d = v; return (true); }
558 559
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
560 561 562 563 564 565
};

class BoolElement : public Element {
    bool b;

public:
566 567
    BoolElement(const bool v, const Position& pos = ZERO_POSITION())
        : Element(boolean, pos), b(v) {};
568
    bool boolValue() const { return (b); }
569
    using Element::getValue;
570
    bool getValue(bool& t) const { t = b; return (true); }
571
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
572
    bool setValue(const bool v) { b = v; return (true); }
573 574
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
575 576 577 578
};

class NullElement : public Element {
public:
579 580
    NullElement(const Position& pos = ZERO_POSITION())
        : Element(null, pos) {};
581 582
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
583 584 585 586 587 588
};

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

public:
589 590
    StringElement(std::string v, const Position& pos = ZERO_POSITION())
        : Element(string, pos), s(v) {};
591
    std::string stringValue() const { return (s); }
592
    using Element::getValue;
593
    bool getValue(std::string& t) const { t = s; return (true); }
594
    using Element::setValue;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
595
    bool setValue(const std::string& v) { s = v; return (true); }
596 597
    void toJSON(std::ostream& ss) const;
    bool equals(const Element& other) const;
598 599 600
};

class ListElement : public Element {
601
    std::vector<ConstElementPtr> l;
602 603

public:
604 605
    ListElement(const Position& pos = ZERO_POSITION())
        : Element(list, pos) {}
606
    const std::vector<ConstElementPtr>& listValue() const { return (l); }
607
    using Element::getValue;
608
    bool getValue(std::vector<ConstElementPtr>& t) const {
609 610 611
        t = l;
        return (true);
    }
612
    using Element::setValue;
613 614 615 616
    bool setValue(const std::vector<ConstElementPtr>& v) {
        l = v;
        return (true);
    }
617
    using Element::get;
618
    ConstElementPtr get(int i) const { return (l.at(i)); }
619
    using Element::set;
620 621 622 623
    void set(size_t i, ConstElementPtr e) {
        l.at(i) = e;
    }
    void add(ConstElementPtr e) { l.push_back(e); };
624
    using Element::remove;
625
    void remove(int i) { l.erase(l.begin() + i); };
626 627
    void toJSON(std::ostream& ss) const;
    size_t size() const { return (l.size()); }
628
    bool empty() const { return (l.empty()); }
629
    bool equals(const Element& other) const;
630 631 632
};

class MapElement : public Element {
633
    std::map<std::string, ConstElementPtr> m;
634 635

public:
636 637 638
    MapElement(const Position& pos = ZERO_POSITION()) : Element(map, pos) {}
    // @todo should we have direct iterators instead of exposing the std::map
    // here?
639 640 641
    const std::map<std::string, ConstElementPtr>& mapValue() const {
        return (m);
    }
642
    using Element::getValue;
643
    bool getValue(std::map<std::string, ConstElementPtr>& t) const {
644 645 646
        t = m;
        return (true);
    }
647
    using Element::setValue;
648
    bool setValue(const std::map<std::string, ConstElementPtr>& v) {
649 650 651
        m = v;
        return (true);
    }
652
    using Element::get;
653
    ConstElementPtr get(const std::string& s) const {
654 655
        return (contains(s) ? m.find(s)->second : ConstElementPtr());
    }
656
    using Element::set;
657
    void set(const std::string& key, ConstElementPtr value);
658
    using Element::remove;
659
    void remove(const std::string& s) { m.erase(s); }
660 661 662 663
    bool contains(const std::string& s) const {
        return (m.find(s) != m.end());
    }
    void toJSON(std::ostream& ss) const;
664

665 666 667 668 669
    // 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
670
    ConstElementPtr find(const std::string& id) const;
671 672 673

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

678 679 680 681 682 683 684
    /// @brief Returns number of stored elements
    ///
    /// @return number of elements.
    size_t size() const {
        return (m.size());
    }

685
    bool equals(const Element& other) const;
686 687 688 689 690
};

/// Checks whether the given ElementPtr is a NULL pointer
/// \param p The ElementPtr to check
/// \return true if it is NULL, false if not.
691
bool isNull(ConstElementPtr p);
692

693 694
///
/// \brief Remove all values from the first ElementPtr that are
695
/// equal in the second. Both ElementPtrs MUST be MapElements
696 697 698 699
/// 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
700 701 702 703 704 705 706 707
void removeIdentical(ElementPtr a, ConstElementPtr b);

/// \brief Create a new ElementPtr from the first ElementPtr, removing all
/// 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);
708

709 710 711 712 713
/// \brief Merges the data from other into element.
/// (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
714 715 716 717 718 719
/// 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).
720
/// Raises a TypeError if either ElementPtr is not a MapElement
721
void merge(ElementPtr element, ConstElementPtr other);
722

723 724 725 726 727 728 729 730 731 732 733 734 735
///
/// \brief Insert Element::Position as a string into stream.
///
/// This operator converts the \c Element::Position into a string and
/// inserts it into the output stream \c out.
///
/// \param out A \c std::ostream object on which the insertion operation is
/// performed.
/// \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.
std::ostream& operator<<(std::ostream& out, const Element::Position& pos);

736 737 738
///
/// \brief Insert the Element as a string into stream.
///
739
/// This method converts the \c ElementPtr into a string with
740 741 742 743 744 745
/// \c Element::str() and inserts it into the
/// output stream \c out.
///
/// This function overloads the global operator<< to behave as described in
/// ostream::operator<< but applied to \c ElementPtr objects.
///
746
/// \param out A \c std::ostream object on which the insertion operation is
747 748 749
/// performed.
/// \param e The \c ElementPtr object to insert.
/// \return A reference to the same \c std::ostream object referenced by
750
/// parameter \c out after the insertion operation.
751
std::ostream& operator<<(std::ostream& out, const Element& e);
752

753 754
bool operator==(const Element& a, const Element& b);
bool operator!=(const Element& a, const Element& b);
JINMEI Tatuya's avatar
JINMEI Tatuya committed
755
} }
756
#endif // ISC_DATA_H
757

758
// Local Variables:
759
// mode: c++
760
// End: