<commit_before>/*
 * items.hpp
 *  Declarations and definitions of items to show
 *  Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
 *  see LICENSE for redistributing, modifying, and so on.
 * */

#ifndef ITEMS_HPP
#define ITEMS_HPP

#include "../../include/avsutil.hpp"
#include "../../helper/observer.hpp"
#include "../../helper/tconv.hpp"

#include <bitset>
#include <locale>
#include <ostream>
#include <string>
#include <vector>

// for convenience
#define ITEM_CLASS_DECL(_name)                              \
class _name : public Item {                                 \
    protected:                                              \
        const char* header(void) const;                     \
        const char* unit(void) const;                       \
        const std::string value(const info_t& vi) const;    \
};

namespace avsinfo {
    namespace items {
        // human-friendly or machine-friendly
        class Notation : public pattern::observer::basic_subject<bool> {
            private:
                // status
                bool is_human_friendly;

            protected:
                // implementation of virtual function
                const state_t& state(void) const { return is_human_friendly; }

            public:
                // constructor
                explicit Notation(bool is_human_friendly = true)
                    : is_human_friendly(is_human_friendly) { notify(); }

                // setter
                inline void human_friendly(void) {
                    is_human_friendly = true;
                    notify();
                }
                inline void machine_friendly(void) {
                    is_human_friendly = false;
                    notify();
                }
        };

        // the base class to represent an item to show
        template<typename T>
            class basic_item : public pattern::observer::basic_observer<bool> {
                public:
                    typedef T   info_t;

                protected:
                    // member variables
                    bool is_human_friendly;
                    const std::string delimiter;
                    static const unsigned int header_size;
                    // wrapper for utility object
                    inline util::string::tconv& tconv(void) const {
                        static util::string::tconv tconv(std::locale::classic());
                        return tconv;
                    }

                    // virtual functions
                    // these functions determin the outputed content
                    virtual const char* header(void) const = 0;
                    virtual const char* unit(void) const = 0;
                    virtual const std::string value(const info_t&) const = 0;

                public:
                    // constructor
                    basic_item(void) : delimiter(": ") {}
                    // destructor
                    virtual ~basic_item(void) {}

                    // output informations to ostream object
                    template<typename charT>
                    inline std::ostream& output(std::basic_ostream<charT>& out, const info_t& info) const {
                        if (is_human_friendly)
                            return out
                                << std::setw(header_size) << header() << delimiter
                                << value(info) << unit() << endl;
                        else
                            return out << value(info) << endl;
                    }

                    // implementation of virtual function
                    void update(const state_t& s) { is_human_friendly = s; }
            };

        // items to show, for video stream
        namespace video {
            typedef basic_item<avsutil::VideoInfo> Item;

            // the declarations of classes for items to show
            ITEM_CLASS_DECL(Width)
            ITEM_CLASS_DECL(Height)
            ITEM_CLASS_DECL(Ratio)
            ITEM_CLASS_DECL(Fps)
            ITEM_CLASS_DECL(FpsFraction)
            ITEM_CLASS_DECL(VideoTime)
            ITEM_CLASS_DECL(Frames)
            ITEM_CLASS_DECL(ColorSpace)
            ITEM_CLASS_DECL(Bpp)
            ITEM_CLASS_DECL(InterlaceType)
            ITEM_CLASS_DECL(FieldOrder)

            // for convenience
            enum item_t {
                WIDTH,
                HEIGHT,
                RATIO,
                FPS,
                FPS_FRACTION,
                VIDEO_TIME,
                FRAMES,
                COLOR_SPACE,
                BPP,
                INTERLACE_TYPE,
                FIELD_ORDER,

                NUMOF_ITEMS
            };

            struct traits {
                typedef Item                base_t;
                typedef item_t              itemkind_t;
                typedef avsutil::VideoInfo  info_t;
                static inline unsigned int numof(void) { return NUMOF_ITEMS; }
                static Item* create_item(item_t item) {
                    switch (item) {
                        case WIDTH:             return new Width;
                        case HEIGHT:            return new Height;
                        case RATIO:             return new Ratio;
                        case FPS:               return new Fps;
                        case FPS_FRACTION:      return new FpsFraction;
                        case VIDEO_TIME:        return new VideoTime;
                        case FRAMES:            return new Frames;
                        case COLOR_SPACE:       return new ColorSpace;
                        case BPP:               return new Bpp;
                        case INTERLACE_TYPE:    return new InterlaceType;
                        case FIELD_ORDER:       return new FieldOrder;
                        default:                return NULL;
                    }
                }
            };
        }

        // items to show, for audio stream
        namespace audio {
            typedef basic_item<avsutil::AudioInfo> Item;

            // the declarations of classes for items to show
            ITEM_CLASS_DECL(Channels)
            ITEM_CLASS_DECL(BitDepth)
            ITEM_CLASS_DECL(SampleType)
            ITEM_CLASS_DECL(AudioTime)
            ITEM_CLASS_DECL(SamplingRate)
            ITEM_CLASS_DECL(Samples)
            ITEM_CLASS_DECL(BlockSize)

            // for convenience
            enum item_t {
                CHANNELS,
                BIT_DEPTH,
                SAMPLE_TYPE,
                AUDIO_TIME,
                SAMPLING_RATE,
                SAMPLES,
                BLOCK_SIZE,

                NUMOF_ITEMS
            };

            struct traits {
                typedef Item                base_t;
                typedef item_t              itemkind_t;
                typedef avsutil::AudioInfo  info_t;
                static inline unsigned int numof(void) { return NUMOF_ITEMS; }
                static Item* create_item(item_t item) {
                    switch (item) {
                        case CHANNELS:      return new Channels;
                        case BIT_DEPTH:     return new BitDepth;
                        case SAMPLE_TYPE:   return new SampleType;
                        case AUDIO_TIME:    return new AudioTime;
                        case SAMPLING_RATE: return new SamplingRate;
                        case SAMPLES:       return new Samples;
                        case BLOCK_SIZE:    return new BlockSize;
                        default:            return NULL;
                    }
                }
            };
        }

        // the base class to represent items that should be outputed
        // This class also contains the order to show.
        // TODO: use reference-count pointer for base_t*
        template<typename traitsT, int numof>
            class basic_items {
                private:
                    typedef typename traitsT::base_t        base_t;
                    typedef std::vector<base_t*>            items_t;
                    typedef typename items_t::iterator      items_it;
                    typedef typename traitsT::itemkind_t    itemkind_t;
                    typedef typename traitsT::info_t        info_t;

                private:
                    // member variables
                    // items to show, and showing order
                    items_t items;
                    // flags to check dupricative assignment
                    std::bitset<numof> specified_flag;
                    // human-friendly or machine-friendly
                    Notation mv_notation;

                public:
                    // add an item to show at the end of the order if still not specified.
                    basic_items<traitsT, numof>& add_item(itemkind_t itemkind) {
                        if (!specified_flag[itemkind]) {
                            base_t* new_item = traitsT::create_item(itemkind);
                            items.push_back(new_item);
                            mv_notation.attach(new_item);
                            specified_flag.set(itemkind);
                        }
                        return *this;
                    }

                    // setter for status
                    inline basic_items<traitsT, numof>&  notation(bool is_human_friendly) {
                        is_human_friendly
                            ? mv_notation.human_friendly()
                            : mv_notation.machine_friendly();
                        return *this;
                    }

                    // output contents
                    template<typename charT>
                    void output(std::basic_ostream<charT>& out, const info_t& info) {
                        for (items_it it = items.begin(); it != items.end(); ++it) {
                            (*it)->output(out, info);
                        }
                    }
            };

        typedef basic_items<video::traits, video::NUMOF_ITEMS> VideoItems;
        typedef basic_items<audio::traits, audio::NUMOF_ITEMS> AudioItems;

        namespace video {
            // for convenience
            void add_all_items(VideoItems& items);
        }

        namespace audio {
            // for convenience
            void add_all_items(AudioItems& items);
        }
    }
}

#endif // ITEMS_HPP

<commit_msg>Refactoring<commit_after>/*
 * items.hpp
 *  Declarations and definitions of items to show
 *  Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
 *  see LICENSE for redistributing, modifying, and so on.
 * */

#ifndef ITEMS_HPP
#define ITEMS_HPP

#include "../../include/avsutil.hpp"
#include "../../helper/observer.hpp"
#include "../../helper/tconv.hpp"

#include <bitset>
#include <locale>
#include <ostream>
#include <string>
#include <vector>

// for convenience
#define ITEM_CLASS_DECL(_name)                              \
class _name : public Item {                                 \
    protected:                                              \
        const char* header(void) const;                     \
        const char* unit(void) const;                       \
        const std::string value(const info_t& vi) const;    \
};

namespace avsinfo {
    namespace items {
        // human-friendly or machine-friendly
        class Notation : public pattern::observer::basic_subject<bool> {
            private:
                // status
                bool is_human_friendly;

            protected:
                // implementation of virtual function
                const state_t& state(void) const { return is_human_friendly; }

            public:
                // constructor
                explicit Notation(bool is_human_friendly = true)
                    : is_human_friendly(is_human_friendly) { notify(); }

                // setter
                inline void human_friendly(void) {
                    is_human_friendly = true;
                    notify();
                }
                inline void machine_friendly(void) {
                    is_human_friendly = false;
                    notify();
                }
        };

        // the base class to represent an item to show
        template<typename T>
            class basic_item : public pattern::observer::basic_observer<bool> {
                public:
                    typedef T   info_t;

                protected:
                    // member variables
                    bool is_human_friendly;
                    const std::string delimiter;
                    static const unsigned int header_size;
                    // wrapper for utility object
                    inline util::string::tconv& tconv(void) const {
                        static util::string::tconv tconv(std::locale::classic());
                        return tconv;
                    }

                    // virtual functions
                    // these functions determin the outputed content
                    virtual const char* header(void) const = 0;
                    virtual const char* unit(void) const = 0;
                    virtual const std::string value(const info_t&) const = 0;

                public:
                    // constructor
                    basic_item(void) : delimiter(": ") {}
                    // destructor
                    virtual ~basic_item(void) {}

                    // output informations to ostream object
                    template<typename charT>
                    inline std::ostream& output(std::basic_ostream<charT>& out, const info_t& info) const {
                        if (is_human_friendly)
                            return out
                                << std::setw(header_size) << header() << delimiter
                                << value(info) << unit() << endl;
                        else
                            return out << value(info) << endl;
                    }

                    // implementation of virtual function
                    void update(const state_t& s) { is_human_friendly = s; }
            };

        // items to show, for video stream
        namespace video {
            typedef basic_item<avsutil::VideoInfo> Item;

            // the declarations of classes for items to show
            ITEM_CLASS_DECL(Width)
            ITEM_CLASS_DECL(Height)
            ITEM_CLASS_DECL(Ratio)
            ITEM_CLASS_DECL(Fps)
            ITEM_CLASS_DECL(FpsFraction)
            ITEM_CLASS_DECL(VideoTime)
            ITEM_CLASS_DECL(Frames)
            ITEM_CLASS_DECL(ColorSpace)
            ITEM_CLASS_DECL(Bpp)
            ITEM_CLASS_DECL(InterlaceType)
            ITEM_CLASS_DECL(FieldOrder)

            // for convenience
            enum item_t {
                WIDTH,
                HEIGHT,
                RATIO,
                FPS,
                FPS_FRACTION,
                VIDEO_TIME,
                FRAMES,
                COLOR_SPACE,
                BPP,
                INTERLACE_TYPE,
                FIELD_ORDER,

                NUMOF_ITEMS
            };

            struct traits {
                typedef Item                base_t;
                typedef item_t              itemkind_t;
                typedef avsutil::VideoInfo  info_t;
                static const unsigned int numof_items = NUMOF_ITEMS;
                static Item* create_item(item_t item) {
                    switch (item) {
                        case WIDTH:             return new Width;
                        case HEIGHT:            return new Height;
                        case RATIO:             return new Ratio;
                        case FPS:               return new Fps;
                        case FPS_FRACTION:      return new FpsFraction;
                        case VIDEO_TIME:        return new VideoTime;
                        case FRAMES:            return new Frames;
                        case COLOR_SPACE:       return new ColorSpace;
                        case BPP:               return new Bpp;
                        case INTERLACE_TYPE:    return new InterlaceType;
                        case FIELD_ORDER:       return new FieldOrder;
                        default:                return NULL;
                    }
                }
            };
        }

        // items to show, for audio stream
        namespace audio {
            typedef basic_item<avsutil::AudioInfo> Item;

            // the declarations of classes for items to show
            ITEM_CLASS_DECL(Channels)
            ITEM_CLASS_DECL(BitDepth)
            ITEM_CLASS_DECL(SampleType)
            ITEM_CLASS_DECL(AudioTime)
            ITEM_CLASS_DECL(SamplingRate)
            ITEM_CLASS_DECL(Samples)
            ITEM_CLASS_DECL(BlockSize)

            // for convenience
            enum item_t {
                CHANNELS,
                BIT_DEPTH,
                SAMPLE_TYPE,
                AUDIO_TIME,
                SAMPLING_RATE,
                SAMPLES,
                BLOCK_SIZE,

                NUMOF_ITEMS
            };

            struct traits {
                typedef Item                base_t;
                typedef item_t              itemkind_t;
                typedef avsutil::AudioInfo  info_t;
                static const unsigned int numof_items = NUMOF_ITEMS;
                static Item* create_item(item_t item) {
                    switch (item) {
                        case CHANNELS:      return new Channels;
                        case BIT_DEPTH:     return new BitDepth;
                        case SAMPLE_TYPE:   return new SampleType;
                        case AUDIO_TIME:    return new AudioTime;
                        case SAMPLING_RATE: return new SamplingRate;
                        case SAMPLES:       return new Samples;
                        case BLOCK_SIZE:    return new BlockSize;
                        default:            return NULL;
                    }
                }
            };
        }

        // the base class to represent items that should be outputed
        // This class also contains the order to show.
        // TODO: use reference-count pointer for base_t*
        template<typename traitsT>
            class basic_items {
                private:
                    typedef typename traitsT::base_t        base_t;
                    typedef std::vector<base_t*>            items_t;
                    typedef typename items_t::iterator      items_it;
                    typedef typename traitsT::itemkind_t    itemkind_t;
                    typedef typename traitsT::info_t        info_t;

                private:
                    // member variables
                    // items to show, and showing order
                    items_t items;
                    // flags to check dupricative assignment
                    std::bitset<traitsT::numof_items> specified_flag;
                    // human-friendly or machine-friendly
                    Notation mv_notation;

                public:
                    // add an item to show at the end of the order if still not specified.
                    basic_items<traitsT>& add_item(itemkind_t itemkind) {
                        if (!specified_flag[itemkind]) {
                            base_t* new_item = traitsT::create_item(itemkind);
                            items.push_back(new_item);
                            mv_notation.attach(new_item);
                            specified_flag.set(itemkind);
                        }
                        return *this;
                    }

                    // setter for status
                    inline basic_items<traitsT>& notation(bool is_human_friendly) {
                        is_human_friendly
                            ? mv_notation.human_friendly()
                            : mv_notation.machine_friendly();
                        return *this;
                    }

                    // output contents
                    template<typename charT>
                        void output(std::basic_ostream<charT>& out, const info_t& info) {
                            for (items_it it = items.begin(); it != items.end(); ++it) {
                                (*it)->output(out, info);
                            }
                        }
            };

        typedef basic_items<video::traits> VideoItems;
        typedef basic_items<audio::traits> AudioItems;

        namespace video {
            // for convenience
            void add_all_items(VideoItems& items);
        }

        namespace audio {
            // for convenience
            void add_all_items(AudioItems& items);
        }
    }
}

#endif // ITEMS_HPP

<|endoftext|>


<commit_before>/*
 *Copyright (c) 2013 Sebastien Caille.
 *All rights reserved.
 *
 *Redistribution and use in source and binary forms are permitted
 *provided that the above copyright notice and this paragraph are
 *duplicated in all such forms and that any documentation,
 *advertising materials, and other materials related to such
 *distribution and use acknowledge that the software was developed
 *by Sebastien Caille.  The name of Sebastien Caille may not be used to endorse or promote products derived
 *from this software without specific prior written permission.
 *THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 *IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 *WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
/*
 * GtkBindings.cpp
 *
 *  Created on: Apr 4, 2012
 *      Author: scaille
 */
#include <iostream>
#include "gtk_bindings.hh"

namespace ch_skymarshall::gui::gtk {

entry_binding::entry_binding(Gtk::Entry& _entry) :
				m_entry(_entry) {
}

entry_binding::~entry_binding() {
	remove_component_value_change_listener();
}

void entry_binding::on_changed_signal() {
	Glib::ustring text(m_entry.get_text());
	m_componentLink.lock()->set_value_from_component(get_component(), text);
}

void entry_binding::add_component_value_change_listener(weak_ptr<component_link<Glib::ustring>> _componentLink) {
	if (!m_connection.connected()) {
		m_componentLink = _componentLink;
		m_connection = m_entry.signal_changed().connect(sigc::mem_fun(*this, &entry_binding::on_changed_signal));
	}
}

void entry_binding::remove_component_value_change_listener() {
	m_connection.disconnect();
}

void entry_binding::set_component_value(property& _source, Glib::ustring _value) {
	cout << _value << endl;
	m_entry.set_text(_value);
}

source_ptr entry_binding::get_component() {
	return (source_ptr) &m_entry;
}

label_binding::label_binding(Gtk::Label& _label) :
				m_label(_label) {
}

label_binding::~label_binding() = default;

void label_binding::add_component_value_change_listener(weak_ptr<component_link<Glib::ustring>> _componentLink) {
}

void label_binding::remove_component_value_change_listener() {
}

void label_binding::set_component_value(property& _source, Glib::ustring _value) {
	m_label.set_text(_value);
}

source_ptr label_binding::get_component() {
	return (source_ptr) &m_label;
}

}
<commit_msg>Cleanups<commit_after>/*
 *Copyright (c) 2013 Sebastien Caille.
 *All rights reserved.
 *
 *Redistribution and use in source and binary forms are permitted
 *provided that the above copyright notice and this paragraph are
 *duplicated in all such forms and that any documentation,
 *advertising materials, and other materials related to such
 *distribution and use acknowledge that the software was developed
 *by Sebastien Caille.  The name of Sebastien Caille may not be used to endorse or promote products derived
 *from this software without specific prior written permission.
 *THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 *IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 *WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
/*
 * GtkBindings.cpp
 *
 *  Created on: Apr 4, 2012
 *      Author: scaille
 */
#include <iostream>

#include "utils.hh"
#include "gtk_bindings.hh"

namespace ch_skymarshall::gui::gtk {

entry_binding::entry_binding(Gtk::Entry &_entry) :
		m_entry(_entry) {
}

entry_binding::~entry_binding() {
	DESTR_LOG("~entry_binding");
	remove_component_value_change_listener();
}

void entry_binding::on_changed_signal() {
	Glib::ustring text(m_entry.get_text());
	m_componentLink.lock()->set_value_from_component(get_component(), text);
}

void entry_binding::add_component_value_change_listener(
		weak_ptr<component_link<Glib::ustring>> _componentLink) {
	if (!m_connection.connected()) {
		m_componentLink = _componentLink;
		m_connection = m_entry.signal_changed().connect(
				sigc::mem_fun(*this, &entry_binding::on_changed_signal));
	}
}

void entry_binding::remove_component_value_change_listener() {
	m_connection.disconnect();
}

void entry_binding::set_component_value(property &_source,
		Glib::ustring _value) {
	m_entry.set_text(_value);
}

source_ptr entry_binding::get_component() {
	return (source_ptr) &m_entry;
}

label_binding::label_binding(Gtk::Label &_label) :
		m_label(_label) {
}

label_binding::~label_binding()
DESTR_WITH_LOG("~label_binding")

void label_binding::add_component_value_change_listener(
		weak_ptr<component_link<Glib::ustring>> _componentLink) {
}

void label_binding::remove_component_value_change_listener() {
}

void label_binding::set_component_value(property &_source,
		Glib::ustring _value) {
	m_label.set_text(_value);
}

source_ptr label_binding::get_component() {
	return (source_ptr) &m_label;
}

}
<|endoftext|>


<commit_before>//
// Originally written by BjÃrn Fahller (bjorn@fahller.se)
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//

#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>

namespace basic {
  struct stack_frame { jmp_buf buf; };
  std::forward_list<stack_frame> stack;

#define GOSUB                                                           \
  if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
        && (basic::stack.pop_front(),true)))                            \
    goto

#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)

  template <typename T, typename U>
  struct separator
  {
    static char const *str() { return ""; }
  };

  template <typename T>
  struct separator<T,T>
  {
    static char const *str() { return ","; }
  };

  template <typename T>
  class printer_h
  {
    using str = char const *;
  public:
    printer_h<str> operator,(str s) {
      std::cout << separator<T, str>::str() << s;
      return printer_h<str>();
    }
    template <typename U>
    printer_h<U> operator,(U const& u) const {
      std::cout << separator<T,U>::str() << u;
      return printer_h<U>();
    }
  };

  class printer
  {
    using str = char const;
  public:
    printer_h<str> operator,(str s) {
      std::cout  << s;
      return printer_h<str>();
    }
    template <typename T>
    printer_h<T> operator,(T const& t) const {
      std::cout << t;
      return printer_h<T>();
    }
    ~printer() { std::cout << std::endl; }
  };

  class input
  {
  public:
    input& operator,(char const *s) {
      std::cout << s << std::flush;
      return *this;
    }
    template <typename T>
    input& operator,(T& t) {
      std::cin >> t;
      return *this;
    }
  };

#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET double
#define GOTO goto
#define FOR { double& for_loop_variable =
#define TO ;                                   \
           {                                   \
             jmp_buf for_loop_top;             \
             bool for_loop_exit = 0;           \
             while (!for_loop_exit)            \
             {                                 \
               if (setjmp(for_loop_top) == 0)  \
               {                               \
                 double for_loop_step=1;       \
                 double const for_loop_endval=
#define STEP ;              \
             for_loop_step=

#define NEXT for_loop_variable+=for_loop_step;                           \
             for_loop_exit=(  (   for_loop_step > 0                      \
                               && for_loop_variable > for_loop_endval)   \
                            ||(   for_loop_step < 0                      \
                               && for_loop_variable < for_loop_endval)); \
             longjmp(for_loop_top, 1);                                   \
             }                                                           \
           }                                                             \
         }                                                               \
       }

} // namespace basic
<commit_msg>added BEGIN and END<commit_after>//
// Originally written by BjÃrn Fahller (bjorn@fahller.se)
//
// No rights claimed. The sources are released to the public domain
//
// For license information, please refer to <http://unlicense.org>
//

#include <setjmp.h>
#include <stdlib.h>
#include <iostream>
#include <ostream>
#include <forward_list>

namespace basic {
  struct stack_frame { jmp_buf buf; };
  std::forward_list<stack_frame> stack;

#define GOSUB                                                           \
  if (!(setjmp((basic::stack.emplace_front(),basic::stack.front().buf)) \
        && (basic::stack.pop_front(),true)))                            \
    goto

#define RETURN if (basic::stack.empty()) return 0; longjmp(basic::stack.front().buf, 1)

  template <typename T, typename U>
  struct separator
  {
    static char const *str() { return ""; }
  };

  template <typename T>
  struct separator<T,T>
  {
    static char const *str() { return ","; }
  };

  template <typename T>
  class printer_h
  {
    using str = char const *;
  public:
    printer_h<str> operator,(str s) {
      std::cout << separator<T, str>::str() << s;
      return printer_h<str>();
    }
    template <typename U>
    printer_h<U> operator,(U const& u) const {
      std::cout << separator<T,U>::str() << u;
      return printer_h<U>();
    }
  };

  class printer
  {
    using str = char const;
  public:
    printer_h<str> operator,(str s) {
      std::cout  << s;
      return printer_h<str>();
    }
    template <typename T>
    printer_h<T> operator,(T const& t) const {
      std::cout << t;
      return printer_h<T>();
    }
    ~printer() { std::cout << std::endl; }
  };

  class input
  {
  public:
    input& operator,(char const *s) {
      std::cout << s << std::flush;
      return *this;
    }
    template <typename T>
    input& operator,(T& t) {
      std::cin >> t;
      return *this;
    }
  };

#define INPUT basic::input(),
#define PRINT basic::printer(),
#define IF if (
#define THEN )
#define LET double
#define GOTO goto
#define FOR { double& for_loop_variable =
#define TO ;                                   \
           {                                   \
             jmp_buf for_loop_top;             \
             bool for_loop_exit = 0;           \
             while (!for_loop_exit)            \
             {                                 \
               if (setjmp(for_loop_top) == 0)  \
               {                               \
                 double for_loop_step=1;       \
                 double const for_loop_endval=
#define STEP ;              \
             for_loop_step=

#define NEXT for_loop_variable+=for_loop_step;                           \
             for_loop_exit=(  (   for_loop_step > 0                      \
                               && for_loop_variable > for_loop_endval)   \
                            ||(   for_loop_step < 0                      \
                               && for_loop_variable < for_loop_endval)); \
             longjmp(for_loop_top, 1);                                   \
             }                                                           \
           }                                                             \
         }                                                               \
       }

#define BEGIN {

#define END }

} // namespace basic
<|endoftext|>


<commit_before>#pragma once

/*
Copyright (c) 2014, Jeff Koftinoff
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"

#if JDKSAVDECCMCU_ENABLE_PCAPFILE == 1

namespace JDKSAvdeccMCU
{
uint64_t get_current_time_in_microseconds();

/* wireshark PCAP file header from
 * http://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format */
struct pcap_hdr_t
{
    uint32_t magic_number;  /* magic number */
    uint16_t version_major; /* major version number */
    uint16_t version_minor; /* minor version number */
    int32_t thiszone;       /* GMT to local correction */
    uint32_t sigfigs;       /* accuracy of timestamps */
    uint32_t snaplen;       /* max length of captured packets, in octets */
    uint32_t network;       /* data link type */
};

/* wireshark PCAP record header from
 * http://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format */

struct pcaprec_hdr_t
{
    uint32_t ts_sec;  /* timestamp seconds */
    uint32_t ts_usec; /* timestamp microseconds */
    int32_t incl_len; /* number of octets of packet saved in file */
    int32_t orig_len; /* actual length of packet */
};

typedef std::vector<uint8_t> PcapFilePacket;

inline uint32_t PcapFileSwap( uint32_t v )
{
    uint32_t r = 0;

    r |= ( ( v >> 24 ) & 0x000000ff );
    r |= ( ( v >> 8 ) & 0x0000ff00 );
    r |= ( ( v << 8 ) & 0x00ff0000 );
    r |= ( ( v << 24 ) & 0xff000000 );
    return r;
}

class PcapFile
{
  public:
    PcapFile( std::string const &filename, const char *mode )
    {
#if defined( _WIN32 )
        std::fopen_s( &m_f, filename.c_str(), mode );
#else
        m_f = std::fopen( filename.c_str(), mode );
#endif
    }

    ~PcapFile()
    {
        if ( m_f )
        {
            fclose( m_f );
            m_f = 0;
        }
    }

    FILE *get() { return m_f; }

  private:
    FILE *m_f;
};
}

#endif
<commit_msg>fopen not in std<commit_after>#pragma once

/*
Copyright (c) 2014, Jeff Koftinoff
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"

#if JDKSAVDECCMCU_ENABLE_PCAPFILE == 1

namespace JDKSAvdeccMCU
{
uint64_t get_current_time_in_microseconds();

/* wireshark PCAP file header from
 * http://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format */
struct pcap_hdr_t
{
    uint32_t magic_number;  /* magic number */
    uint16_t version_major; /* major version number */
    uint16_t version_minor; /* minor version number */
    int32_t thiszone;       /* GMT to local correction */
    uint32_t sigfigs;       /* accuracy of timestamps */
    uint32_t snaplen;       /* max length of captured packets, in octets */
    uint32_t network;       /* data link type */
};

/* wireshark PCAP record header from
 * http://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format */

struct pcaprec_hdr_t
{
    uint32_t ts_sec;  /* timestamp seconds */
    uint32_t ts_usec; /* timestamp microseconds */
    int32_t incl_len; /* number of octets of packet saved in file */
    int32_t orig_len; /* actual length of packet */
};

typedef std::vector<uint8_t> PcapFilePacket;

inline uint32_t PcapFileSwap( uint32_t v )
{
    uint32_t r = 0;

    r |= ( ( v >> 24 ) & 0x000000ff );
    r |= ( ( v >> 8 ) & 0x0000ff00 );
    r |= ( ( v << 8 ) & 0x00ff0000 );
    r |= ( ( v << 24 ) & 0xff000000 );
    return r;
}

class PcapFile
{
  public:
    PcapFile( std::string const &filename, const char *mode )
    {
#if defined( _WIN32 )
        fopen_s( &m_f, filename.c_str(), mode );
#else
        m_f = fopen( filename.c_str(), mode );
#endif
    }

    ~PcapFile()
    {
        if ( m_f )
        {
            fclose( m_f );
            m_f = 0;
        }
    }

    FILE *get() { return m_f; }

  private:
    FILE *m_f;
};
}

#endif
<|endoftext|>


<commit_before>#pragma once

#include "EntitySystem.hpp"
#include "Component.hpp"

#include "detail/ComponentPool.hpp"

namespace Kunlaboro
{

	template<typename T>
	ComponentHandle<T> EntitySystem::getComponent(ComponentId id) const
	{
		return static_cast<ComponentHandle<T>>(getComponent(id));
	}

	template<typename T>
	ComponentHandle<T> EntitySystem::entityGetComponent(ComponentId::FamilyType family, EntityId eid) const
	{
		return static_cast<ComponentHandle<T>>(entityGetComponent(family, eid));
	}

	template<typename T, typename... Args>
	ComponentHandle<T> EntitySystem::componentCreate(Args... args)
	{
		auto family = Kunlaboro::ComponentFamily<T>::getFamily();
		if (mComponentFamilies.size() <= family)
			mComponentFamilies.resize(family + 1);

		auto& data = mComponentFamilies[family];
		if (!data.MemoryPool)
		{
			auto* pool = new detail::ComponentPool<T>();
			data.MemoryPool = pool;
		}

		auto* pool = static_cast<detail::ComponentPool<T>*>(data.MemoryPool);
		ComponentId::IndexType index;
		if (data.FreeIndices.empty())
		{
			index = data.Components.size();
			data.Components.push_back({ });
		}
		else
		{
			index = data.FreeIndices.front();
			data.FreeIndices.pop_front();
		}

		pool->ensure(index + 1);
		auto& component = data.Components[index];
		component.RefCount->store(0);

		pool->setBit(index);
		auto* comp = static_cast<T*>(pool->getData(index));

		auto id = ComponentId(index, component.Generation, family);

		comp->mES = this;
		comp->mId = id;

		new(pool->getData(index)) T(std::forward<Args>(args)...);

		// TODO: Move more of this out of header
		// if (mEventSystem)
		//     mEventSystem->eventEmit<ComponentCreatedEvent>(comp->mId, this);

		return ComponentHandle<T>(comp, component.RefCount);
	}

}
<commit_msg>Don't copy IDs or ES pointers<commit_after>#pragma once

#include "EntitySystem.hpp"
#include "Component.hpp"

#include "detail/ComponentPool.hpp"

namespace Kunlaboro
{

	template<typename T>
	ComponentHandle<T> EntitySystem::getComponent(ComponentId id) const
	{
		return static_cast<ComponentHandle<T>>(getComponent(id));
	}

	template<typename T>
	ComponentHandle<T> EntitySystem::entityGetComponent(ComponentId::FamilyType family, EntityId eid) const
	{
		return static_cast<ComponentHandle<T>>(entityGetComponent(family, eid));
	}

	template<typename T, typename... Args>
	ComponentHandle<T> EntitySystem::componentCreate(Args... args)
	{
		auto family = Kunlaboro::ComponentFamily<T>::getFamily();
		if (mComponentFamilies.size() <= family)
			mComponentFamilies.resize(family + 1);

		auto& data = mComponentFamilies[family];
		if (!data.MemoryPool)
		{
			auto* pool = new detail::ComponentPool<T>();
			data.MemoryPool = pool;
		}

		auto* pool = static_cast<detail::ComponentPool<T>*>(data.MemoryPool);
		ComponentId::IndexType index;
		if (data.FreeIndices.empty())
		{
			index = data.Components.size();
			data.Components.push_back({ });
		}
		else
		{
			index = data.FreeIndices.front();
			data.FreeIndices.pop_front();
		}

		pool->ensure(index + 1);
		auto& component = data.Components[index];
		component.RefCount->store(0);

		pool->setBit(index);
		auto* comp = static_cast<T*>(pool->getData(index));

		auto id = ComponentId(index, component.Generation, family);

		comp->mES = this;
		comp->mId = id;

		new(pool->getData(index)) T(std::forward<Args>(args)...);

		// In case copy-construction happens
		comp->mES = this;
		comp->mId = id;

		// TODO: Move more of this out of header
		// if (mEventSystem)
		//     mEventSystem->eventEmit<ComponentCreatedEvent>(comp->mId, this);

		return ComponentHandle<T>(comp, component.RefCount);
	}

}
<|endoftext|>


<commit_before>/* Copyright 2017 - 2021 R. Thomas
 * Copyright 2017 - 2021 Quarkslab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef LIEF_PE_X509_H_
#define LIEF_PE_X509_H_
#include <array>
#include <memory>

#include "LIEF/Object.hpp"
#include "LIEF/visibility.h"

#include "LIEF/PE/enums.hpp"

#include "LIEF/PE/signature/types.hpp"

#include "LIEF/enums.hpp"

struct mbedtls_x509_crt;

namespace LIEF {
namespace PE {

class Parser;
class SignatureParser;
class Signature;

class RsaInfo;

//! Interface over a x509 certificate
class LIEF_API x509 : public Object {

  friend class Parser;
  friend class SignatureParser;
  friend class Signature;

  public:
  //! Tuple (Year, Month, Day, Hour, Minute, Second)
  using date_t = std::array<int32_t, 6>;

  using certificates_t = std::vector<x509>;

  //! Parse x509 certificate(s) from file path
  static certificates_t parse(const std::string& path);

  //! Parse x500 certificate(s) from raw blob
  static certificates_t parse(const std::vector<uint8_t>& content);

  //! Return True if ``before`` is *before* than ``after``. False otherwise
  static bool check_time(const date_t& before, const date_t& after);

  //! True if the given time is in the **past** according to the clock's system
  static bool time_is_past(const date_t& to);

  //! True if the given time is in the future according to the clock's system
  static bool time_is_future(const date_t& from);

  //! Public key scheme
  enum class KEY_TYPES  {
    NONE = 0,    ///< Unknown scheme
    RSA,         ///< RSA Scheme
    ECKEY,       ///< Elliptic-curve scheme
    ECKEY_DH,    ///< Elliptic-curve Diffie-Hellman
    ECDSA,       ///< Elliptic-curve Digital Signature Algorithm
    RSA_ALT,     ///< RSA scheme with an alternative implementation for signing and decrypting
    RSASSA_PSS,  ///< RSA Probabilistic signature scheme
  };

  //! Mirror of mbedtls's X509 Verify codes: MBEDTLS_X509_XX
  //!
  //! It must be sync with include/mbedtls/x509.h
  enum class VERIFICATION_FLAGS {
    OK                     = 0,       /**< The verification succeed  */
    BADCERT_EXPIRED        = 1 << 0,  /**< The certificate validity has expired. */
    BADCERT_REVOKED        = 1 << 1,  /**< The certificate has been revoked (is on a CRL). */
    BADCERT_CN_MISMATCH    = 1 << 2,  /**< The certificate Common Name (CN) does not match with the expected CN. */
    BADCERT_NOT_TRUSTED    = 1 << 3,  /**< The certificate is not correctly signed by the trusted CA. */
    BADCRL_NOT_TRUSTED     = 1 << 4,  /**< The CRL is not correctly signed by the trusted CA. */
    BADCRL_EXPIRED         = 1 << 5,  /**< The CRL is expired. */
    BADCERT_MISSING        = 1 << 6,  /**< Certificate was missing. */
    BADCERT_SKIP_VERIFY    = 1 << 7,  /**< Certificate verification was skipped. */
    BADCERT_OTHER          = 1 << 8,  /**< Other reason (can be used by verify callback) */
    BADCERT_FUTURE         = 1 << 9,  /**< The certificate validity starts in the future. */
    BADCRL_FUTURE          = 1 << 10, /**< The CRL is from the future */
    BADCERT_KEY_USAGE      = 1 << 11, /**< Usage does not match the keyUsage extension. */
    BADCERT_EXT_KEY_USAGE  = 1 << 12, /**< Usage does not match the extendedKeyUsage extension. */
    BADCERT_NS_CERT_TYPE   = 1 << 13, /**< Usage does not match the nsCertType extension. */
    BADCERT_BAD_MD         = 1 << 14, /**< The certificate is signed with an unacceptable hash. */
    BADCERT_BAD_PK         = 1 << 15, /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
    BADCERT_BAD_KEY        = 1 << 16, /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */
    BADCRL_BAD_MD          = 1 << 17, /**< The CRL is signed with an unacceptable hash. */
    BADCRL_BAD_PK          = 1 << 18, /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
    BADCRL_BAD_KEY         = 1 << 19, /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */
  };

  //! Key usage as defined in [RFC #5280 - section-4.2.1.3](https://tools.ietf.org/html/rfc5280#section-4.2.1.3)
  enum class KEY_USAGE {
    DIGITAL_SIGNATURE = 0, /**< The key is used for digital signature */
    NON_REPUDIATION,       /**< The key is used for digital signature AND to protects against falsely denying some action */
    KEY_ENCIPHERMENT,      /**< The key is used for enciphering private or secret keys */
    DATA_ENCIPHERMENT,     /**< The key is used for directly enciphering raw user data without the use of an intermediate symmetric cipher */
    KEY_AGREEMENT,         /**< The Key is used for key agreement. (e.g. with Diffie-Hellman) */
    KEY_CERT_SIGN,         /**< The key is used for verifying signatures on public key certificates */
    CRL_SIGN,              /**< The key is used for verifying signatures on certificate revocation lists */
    ENCIPHER_ONLY,         /**< In **association with** KEY_AGREEMENT (otherwise the meaning is undefined), the key is only used for enciphering data while performing key agreement */
    DECIPHER_ONLY,         /**< In **association with** KEY_AGREEMENT (otherwise the meaning is undefined), the key is only used for deciphering data while performing key agreement */
  };

  x509(mbedtls_x509_crt* ca);
  x509(const x509& other);
  x509& operator=(x509 other);
  void swap(x509& other);

  //! X.509 version. (1=v1, 2=v2, 3=v3)
  uint32_t version(void) const;

  //! Unique id for certificate issued by a specific CA.
  std::vector<uint8_t> serial_number(void) const;

  //! Signature algorithm (OID)
  oid_t signature_algorithm(void) const;

  //! Start time of certificate validity
  date_t valid_from(void) const;

  //! End time of certificate validity
  date_t valid_to(void) const;

  //! Issuer informations
  std::string issuer(void) const;

  //! Subject informations
  std::string subject(void) const;

  //! Try to decrypt the given signature and check if it matches the given hash according to
  //! the hash algorithm provided
  bool check_signature(const std::vector<uint8_t>& hash, const std::vector<uint8_t>& signature, ALGORITHMS digest) const;

  //! The raw x509 bytes (DER encoded)
  std::vector<uint8_t> raw(void) const;

  //! Return the underlying public-key scheme
  KEY_TYPES key_type() const;

  //! **If** the underlying public-key scheme is RSA, return the RSA information.
  //! Otherwise, return a nullptr
  std::unique_ptr<RsaInfo> rsa_info() const;

  //! Verify that this certificate has been used **to trust** the given certificate
  VERIFICATION_FLAGS verify(const x509& child) const;

  //! Verify that this certificate **is trusted** by the given CA list
  VERIFICATION_FLAGS is_trusted_by(const std::vector<x509>& ca) const;

  //! Policy information terms as OID (see RFC #5280)
  std::vector<oid_t> certificate_policies() const;

  //! Purpose of the key contained in the certificate
  std::vector<KEY_USAGE> key_usage() const;

  //! Indicates one or more purposes for which the certified public key may be used (OID types)
  std::vector<oid_t> ext_key_usage() const;

  bool is_ca() const;

  //! The signature of the certificate
  std::vector<uint8_t> signature() const;

  virtual void accept(Visitor& visitor) const override;

  virtual ~x509(void);

  LIEF_API friend std::ostream& operator<<(std::ostream& os, const x509& x509_cert);

  private:
  x509(void);
  mbedtls_x509_crt* x509_cert_ = nullptr;

};

}
}

ENABLE_BITMASK_OPERATORS(LIEF::PE::x509::VERIFICATION_FLAGS);

#endif
<commit_msg>Fix typo<commit_after>/* Copyright 2017 - 2021 R. Thomas
 * Copyright 2017 - 2021 Quarkslab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef LIEF_PE_X509_H_
#define LIEF_PE_X509_H_
#include <array>
#include <memory>

#include "LIEF/Object.hpp"
#include "LIEF/visibility.h"

#include "LIEF/PE/enums.hpp"

#include "LIEF/PE/signature/types.hpp"

#include "LIEF/enums.hpp"

struct mbedtls_x509_crt;

namespace LIEF {
namespace PE {

class Parser;
class SignatureParser;
class Signature;

class RsaInfo;

//! Interface over a x509 certificate
class LIEF_API x509 : public Object {

  friend class Parser;
  friend class SignatureParser;
  friend class Signature;

  public:
  //! Tuple (Year, Month, Day, Hour, Minute, Second)
  using date_t = std::array<int32_t, 6>;

  using certificates_t = std::vector<x509>;

  //! Parse x509 certificate(s) from file path
  static certificates_t parse(const std::string& path);

  //! Parse x509 certificate(s) from raw blob
  static certificates_t parse(const std::vector<uint8_t>& content);

  //! Return True if ``before`` is *before* than ``after``. False otherwise
  static bool check_time(const date_t& before, const date_t& after);

  //! True if the given time is in the **past** according to the clock's system
  static bool time_is_past(const date_t& to);

  //! True if the given time is in the future according to the clock's system
  static bool time_is_future(const date_t& from);

  //! Public key scheme
  enum class KEY_TYPES  {
    NONE = 0,    ///< Unknown scheme
    RSA,         ///< RSA Scheme
    ECKEY,       ///< Elliptic-curve scheme
    ECKEY_DH,    ///< Elliptic-curve Diffie-Hellman
    ECDSA,       ///< Elliptic-curve Digital Signature Algorithm
    RSA_ALT,     ///< RSA scheme with an alternative implementation for signing and decrypting
    RSASSA_PSS,  ///< RSA Probabilistic signature scheme
  };

  //! Mirror of mbedtls's X509 Verify codes: MBEDTLS_X509_XX
  //!
  //! It must be sync with include/mbedtls/x509.h
  enum class VERIFICATION_FLAGS {
    OK                     = 0,       /**< The verification succeed  */
    BADCERT_EXPIRED        = 1 << 0,  /**< The certificate validity has expired. */
    BADCERT_REVOKED        = 1 << 1,  /**< The certificate has been revoked (is on a CRL). */
    BADCERT_CN_MISMATCH    = 1 << 2,  /**< The certificate Common Name (CN) does not match with the expected CN. */
    BADCERT_NOT_TRUSTED    = 1 << 3,  /**< The certificate is not correctly signed by the trusted CA. */
    BADCRL_NOT_TRUSTED     = 1 << 4,  /**< The CRL is not correctly signed by the trusted CA. */
    BADCRL_EXPIRED         = 1 << 5,  /**< The CRL is expired. */
    BADCERT_MISSING        = 1 << 6,  /**< Certificate was missing. */
    BADCERT_SKIP_VERIFY    = 1 << 7,  /**< Certificate verification was skipped. */
    BADCERT_OTHER          = 1 << 8,  /**< Other reason (can be used by verify callback) */
    BADCERT_FUTURE         = 1 << 9,  /**< The certificate validity starts in the future. */
    BADCRL_FUTURE          = 1 << 10, /**< The CRL is from the future */
    BADCERT_KEY_USAGE      = 1 << 11, /**< Usage does not match the keyUsage extension. */
    BADCERT_EXT_KEY_USAGE  = 1 << 12, /**< Usage does not match the extendedKeyUsage extension. */
    BADCERT_NS_CERT_TYPE   = 1 << 13, /**< Usage does not match the nsCertType extension. */
    BADCERT_BAD_MD         = 1 << 14, /**< The certificate is signed with an unacceptable hash. */
    BADCERT_BAD_PK         = 1 << 15, /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
    BADCERT_BAD_KEY        = 1 << 16, /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */
    BADCRL_BAD_MD          = 1 << 17, /**< The CRL is signed with an unacceptable hash. */
    BADCRL_BAD_PK          = 1 << 18, /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
    BADCRL_BAD_KEY         = 1 << 19, /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */
  };

  //! Key usage as defined in [RFC #5280 - section-4.2.1.3](https://tools.ietf.org/html/rfc5280#section-4.2.1.3)
  enum class KEY_USAGE {
    DIGITAL_SIGNATURE = 0, /**< The key is used for digital signature */
    NON_REPUDIATION,       /**< The key is used for digital signature AND to protects against falsely denying some action */
    KEY_ENCIPHERMENT,      /**< The key is used for enciphering private or secret keys */
    DATA_ENCIPHERMENT,     /**< The key is used for directly enciphering raw user data without the use of an intermediate symmetric cipher */
    KEY_AGREEMENT,         /**< The Key is used for key agreement. (e.g. with Diffie-Hellman) */
    KEY_CERT_SIGN,         /**< The key is used for verifying signatures on public key certificates */
    CRL_SIGN,              /**< The key is used for verifying signatures on certificate revocation lists */
    ENCIPHER_ONLY,         /**< In **association with** KEY_AGREEMENT (otherwise the meaning is undefined), the key is only used for enciphering data while performing key agreement */
    DECIPHER_ONLY,         /**< In **association with** KEY_AGREEMENT (otherwise the meaning is undefined), the key is only used for deciphering data while performing key agreement */
  };

  x509(mbedtls_x509_crt* ca);
  x509(const x509& other);
  x509& operator=(x509 other);
  void swap(x509& other);

  //! X.509 version. (1=v1, 2=v2, 3=v3)
  uint32_t version(void) const;

  //! Unique id for certificate issued by a specific CA.
  std::vector<uint8_t> serial_number(void) const;

  //! Signature algorithm (OID)
  oid_t signature_algorithm(void) const;

  //! Start time of certificate validity
  date_t valid_from(void) const;

  //! End time of certificate validity
  date_t valid_to(void) const;

  //! Issuer informations
  std::string issuer(void) const;

  //! Subject informations
  std::string subject(void) const;

  //! Try to decrypt the given signature and check if it matches the given hash according to
  //! the hash algorithm provided
  bool check_signature(const std::vector<uint8_t>& hash, const std::vector<uint8_t>& signature, ALGORITHMS digest) const;

  //! The raw x509 bytes (DER encoded)
  std::vector<uint8_t> raw(void) const;

  //! Return the underlying public-key scheme
  KEY_TYPES key_type() const;

  //! **If** the underlying public-key scheme is RSA, return the RSA information.
  //! Otherwise, return a nullptr
  std::unique_ptr<RsaInfo> rsa_info() const;

  //! Verify that this certificate has been used **to trust** the given certificate
  VERIFICATION_FLAGS verify(const x509& child) const;

  //! Verify that this certificate **is trusted** by the given CA list
  VERIFICATION_FLAGS is_trusted_by(const std::vector<x509>& ca) const;

  //! Policy information terms as OID (see RFC #5280)
  std::vector<oid_t> certificate_policies() const;

  //! Purpose of the key contained in the certificate
  std::vector<KEY_USAGE> key_usage() const;

  //! Indicates one or more purposes for which the certified public key may be used (OID types)
  std::vector<oid_t> ext_key_usage() const;

  bool is_ca() const;

  //! The signature of the certificate
  std::vector<uint8_t> signature() const;

  virtual void accept(Visitor& visitor) const override;

  virtual ~x509(void);

  LIEF_API friend std::ostream& operator<<(std::ostream& os, const x509& x509_cert);

  private:
  x509(void);
  mbedtls_x509_crt* x509_cert_ = nullptr;

};

}
}

ENABLE_BITMASK_OPERATORS(LIEF::PE::x509::VERIFICATION_FLAGS);

#endif
<|endoftext|>


<commit_before>#pragma once

#include <functional>

#include "blackhole/sink.hpp"

namespace blackhole {

template<typename>
struct factory;

}  // namespace blackhole

namespace blackhole {
namespace config {

class node_t;

}  // namespace config
}  // namespace blackhole

namespace blackhole {
namespace sink {

/// Terminal color manipulator.
class color_t {
    class scope_t;

    int attr;
    int code;

public:
    /// Constructs a default terminal color.
    color_t();

    /// Creates a terminal color stream manipulator, which equals the blue color.
    ///
    /// Usually useful for marking information events.
    static auto blue() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the green color.
    ///
    /// Usually useful for marking information events.
    static auto green() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the yellow color.
    ///
    /// Usually useful for marking warning events.
    static auto yellow() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the red color.
    ///
    /// Usually useful for marking error events.
    static auto red() -> color_t;

    /// Creates a terminal color stream manipulator, which resets the color.
    static auto reset() -> color_t;

    /// Lightens the current color.
    auto lighter() -> color_t&;

    /// Applies the current color to the given stream and writes data specified to it.
    auto apply(std::ostream& stream, const char* data, std::size_t size) -> void;

    auto colored() const noexcept -> bool;

    auto operator==(const color_t& other) const noexcept -> bool;
    auto operator!=(const color_t& other) const noexcept -> bool;

    friend auto operator<<(std::ostream& stream, const color_t& color) -> std::ostream&;

private:
    color_t(int attr, int code);
};

typedef std::function<auto(const record_t&) -> color_t> termcolor_map;

/// Represents the console sink which is responsible for writing all incoming log events directly
/// into one of the selected standard outputs with an ability to optionally colorize result strings.
///
/// The sink automatically detects whether the destination stream is a TTY disabling colored output
/// otherwise, which makes possible to redirect standard output to file without escaping codes
/// garbage.
///
/// Note, that despite of C++ `std::cout` and `std::cerr` thread-safety with no undefined behavior
/// its guarantees is insufficiently for safe working with them from multiple threads, leading to
/// result messages intermixing.
/// To avoid this a global mutex is used internally, which is kinda hack. Any other stdout/stderr
/// usage outside from logger will probably results in character mixing, but no undefined behavior
/// will be invoked.
class console_t : public sink_t {
public:
    enum class type_t { stdout, stderr };

private:
    std::ostream& stream;
    termcolor_map colormap;

public:
    class builder_t;

    /// Constructs a default console sink, which will write all incoming events to the standard
    /// output.
    ///
    /// No output coloring occurred in this case.
    console_t();

    /// Constucts a new console sink, which will write all incoming events to the standard output
    /// using the given terminal color mapping to colorize the output.
    ///
    /// \param colormap color mappings from logging level to terminal color.
    explicit console_t(termcolor_map colormap);

    /// Constructs a new console sink, which will write all incoming events to the specified
    /// standard stream (stdout or stderr) using the given terminal color mapping to colorize the
    /// output.
    ///
    /// \param type standard output type.
    /// \param colormap color mappings from logging level to terminal color.
    console_t(type_t type, termcolor_map colormap);

    /// Filters the given log record determining if it is allowed to be consumed by this sink.
    ///
    /// The console implementation always returns `true`, meaning that all logging events should be
    /// accepted.
    auto filter(const record_t& record) -> bool;

    /// Consumes the log record with the given formatted string with its further writing to the
    /// stream attached.
    auto execute(const record_t& record, const string_view& formatted) -> void;

protected:
    /// Constructs a new console sink, which will write all incoming events to the specified
    /// stream using the given terminal color mapping to colorize the output.
    ///
    /// This constructor is protected, because it accepts a generic stream instead of predefined
    /// one making it possible to write anywhere that implements stream protocol, which is useful
    /// for testing reasons for example.
    console_t(std::ostream& stream, termcolor_map colormap);

    /// Maps the given log record returning the color that is used for colored formatting the result
    /// output message.
    ///
    /// The implementation uses `colormap` variable provided with construction.
    auto color(const record_t& record) -> color_t;

private:
    static auto output(type_t type) -> std::ostream&;
};

class console_t::builder_t {
public:
    auto build() const -> console_t;
};

}  // namespace sink

template<>
struct factory<sink::console_t> {
    static auto type() -> const char*;
    static auto from(const config::node_t& config) -> sink::console_t;
};

}  // namespace blackhole
<commit_msg>docs(sink/console): fix wording<commit_after>#pragma once

#include <functional>

#include "blackhole/sink.hpp"

namespace blackhole {

template<typename>
struct factory;

}  // namespace blackhole

namespace blackhole {
namespace config {

class node_t;

}  // namespace config
}  // namespace blackhole

namespace blackhole {
namespace sink {

/// Terminal color manipulator.
class color_t {
    class scope_t;

    int attr;
    int code;

public:
    /// Constructs a default terminal color.
    color_t();

    /// Creates a terminal color stream manipulator, which equals the blue color.
    ///
    /// Usually useful for marking information events.
    static auto blue() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the green color.
    ///
    /// Usually useful for marking information events.
    static auto green() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the yellow color.
    ///
    /// Usually useful for marking warning events.
    static auto yellow() -> color_t;

    /// Creates a terminal color stream manipulator, which equals the red color.
    ///
    /// Usually useful for marking error events.
    static auto red() -> color_t;

    /// Creates a terminal color stream manipulator, which resets the color.
    static auto reset() -> color_t;

    /// Lightens the current color.
    auto lighter() -> color_t&;

    /// Applies the current color to the given stream and writes data specified to it.
    auto apply(std::ostream& stream, const char* data, std::size_t size) -> void;

    auto colored() const noexcept -> bool;

    auto operator==(const color_t& other) const noexcept -> bool;
    auto operator!=(const color_t& other) const noexcept -> bool;

    friend auto operator<<(std::ostream& stream, const color_t& color) -> std::ostream&;

private:
    color_t(int attr, int code);
};

typedef std::function<auto(const record_t&) -> color_t> termcolor_map;

/// Represents the console sink which is responsible for writing all incoming log events directly
/// into one of the selected standard outputs with an ability to optionally colorize result strings.
///
/// The sink automatically detects whether the destination stream is a TTY disabling colored output
/// otherwise, which makes possible to redirect standard output to file without escaping codes
/// garbage.
///
/// Note, that despite of C++ `std::cout` and `std::cerr` thread-safety with no undefined behavior
/// its guarantees is insufficiently for safe working with them from multiple threads, leading to
/// result messages intermixing.
/// To avoid this a global mutex is used internally, which is kinda hack. Any other stdout/stderr
/// usage outside from logger will probably results in character mixing, but no undefined behavior
/// will be invoked.
class console_t : public sink_t {
public:
    enum class type_t { stdout, stderr };

private:
    std::ostream& stream;
    termcolor_map colormap;

public:
    class builder_t;

    /// Constructs a default console sink, which will write all incoming events to the standard
    /// output.
    ///
    /// No output coloring occurred in this case.
    console_t();

    /// Constucts a new console sink, which will write all incoming events to the standard output
    /// using the given terminal color mapping to colorize the output.
    ///
    /// \param colormap color mappings from logging level to terminal color.
    explicit console_t(termcolor_map colormap);

    /// Constructs a new console sink, which will write all incoming events to the specified
    /// standard stream (stdout or stderr) using the given terminal color mapping to colorize the
    /// output.
    ///
    /// \param type standard output type.
    /// \param colormap color mappings from logging level to terminal color.
    console_t(type_t type, termcolor_map colormap);

    /// Filters the given log record determining if it is allowed to be consumed by this sink.
    ///
    /// The console implementation always returns `true`, meaning that all logging events should be
    /// accepted.
    auto filter(const record_t& record) -> bool;

    /// Consumes the log record with the given formatted string with its further writing to the
    /// stream attached.
    auto execute(const record_t& record, const string_view& formatted) -> void;

protected:
    /// Constructs a new console sink, which will write all incoming events to the specified
    /// stream using the given terminal color mapping to colorize the output.
    ///
    /// This constructor is protected, because it accepts a generic stream instead of predefined
    /// one making it possible to write into anything that implements stream protocol, which is
    /// useful for testing reasons for example.
    console_t(std::ostream& stream, termcolor_map colormap);

    /// Maps the given log record returning the color that is used for colored formatting the result
    /// output message.
    ///
    /// The implementation uses `colormap` variable provided with construction.
    auto color(const record_t& record) -> color_t;

private:
    static auto output(type_t type) -> std::ostream&;
};

class console_t::builder_t {
public:
    auto build() const -> console_t;
};

}  // namespace sink

template<>
struct factory<sink::console_t> {
    static auto type() -> const char*;
    static auto from(const config::node_t& config) -> sink::console_t;
};

}  // namespace blackhole
<|endoftext|>


<commit_before>#ifndef ALIGNED_STORAGE_HPP
#define ALIGNED_STORAGE_HPP

#include <new>

namespace opt {
namespace detail {

template <typename T>
class Aligned_storage {
   public:
    // Aligned_storage() = default;

    // Aligned_storage(const T& value) { ::new (this->address()) T(value); }

    const T* ptr_ref() const { return static_cast<const T*>(this->address()); }

    T* ptr_ref() { return static_cast<T*>(this->address()); }

    const T& ref() const { return *this->ptr_ref(); }

    T& ref() { return *this->ptr_ref(); }

    const void* address() const { return data_; }

    void* address() { return data_; }

   private:
    char data_[sizeof(T)];
};

}  // namespace detail
}  // namespace opt
#endif  // ALIGNED_STORAGE_HPP
<commit_msg>Clean up commented out code.<commit_after>#ifndef ALIGNED_STORAGE_HPP
#define ALIGNED_STORAGE_HPP

#include <new>

namespace opt {
namespace detail {

template <typename T>
class Aligned_storage {
   public:
    const T* ptr_ref() const { return static_cast<const T*>(this->address()); }

    T* ptr_ref() { return static_cast<T*>(this->address()); }

    const T& ref() const { return *this->ptr_ref(); }

    T& ref() { return *this->ptr_ref(); }

    const void* address() const { return data_; }

    void* address() { return data_; }

   private:
    char data_[sizeof(T)];
};

}  // namespace detail
}  // namespace opt
#endif  // ALIGNED_STORAGE_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright (c) 2012 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#ifndef __MDDS_MULTI_TYPE_MATRIX_HPP__
#define __MDDS_MULTI_TYPE_MATRIX_HPP__

#include "multi_type_vector.hpp"
#include "multi_type_matrix_block_func.hpp"

namespace mdds {

template<typename _String, typename _Flag>
class multi_type_matrix
{
public:
    enum element_t { element_empty, element_boolean, element_string, element_numeric };
    typedef _String     string_type;
    typedef _Flag       flag_type;
    typedef size_t      size_type;

    struct size_pair_type
    {
        size_type row;
        size_type column;
        size_pair_type() : row(0), column(0) {}
        size_pair_type(size_type _row, size_type _column) : row(_row), column(_column) {}
    };

    /**
     * Default constructor.
     */
    multi_type_matrix();

    /**
     * Construct a matrix of specified size with specified density type.
     */
    multi_type_matrix(size_t rows, size_t cols);

    template<typename _T>
    multi_type_matrix(size_t rows, size_t cols, const _T& value);

    multi_type_matrix(const multi_type_matrix& r);
    ~multi_type_matrix();

    multi_type_matrix& operator= (const multi_type_matrix& r);

    /**
     * Get the type of element specified by its position.  The type can be one
     * of empty, string, numeric, or boolean.
     *
     * @return element type.
     */
    element_t get_type(size_t row, size_t col) const;

    double get_numeric(size_t row, size_t col) const;
    bool get_boolean(size_t row, size_t col) const;
    const string_type& get_string(size_t row, size_t col) const;

    void set_empty(size_type row, size_type col);

    void set(size_type row, size_type col, double val);
    void set(size_type row, size_type col, bool val);
    void set(size_type row, size_type col, const string_type& str);

    /**
     * Set flag value at specified position.
     *
     * @param row row position
     * @param col column position
     * @param flag_type flag value
     */
    void set_flag(size_t row, size_t col, flag_type flag);

    /**
     * Get flag value at specified position.
     *
     * @param row row position
     * @param col column position
     *
     * @return flag value stored at specified position
     */
    flag_type get_flag(size_t row, size_t col) const;

    void clear_flag(size_t row, size_t col);

    /**
     * Return the size of matrix as a pair.  The first value is the row size,
     * while the second value is the column size.
     *
     * @return matrix size as a value pair.
     */
    size_pair_type size() const;

    /**
     * Transpose the stored matrix data.
     *
     * @return reference to this matrix instance.
     */
    multi_type_matrix& transpose();

    /**
     * Assign values from the passed matrix instance.  If the size of the
     * passed matrix is smaller, then the element values are assigned by their
     * positions, while the rest of the elements that fall outside the size of
     * the passed matrix instance will remain unmodified.  If the size of the
     * passed matrix instance is larger, then only the elements within the
     * size of this matrix instance will get assigned.
     *
     * @param r passed matrix object to assign element values from.
     */
    void assign(const multi_type_matrix& r);

    /**
     * Resize the matrix to specified size.  This method supports resizing to
     * zero-sized matrix; however, either specifying the row or column size to
     * zero will resize the matrix to 0 x 0.
     *
     * @param row new row size
     * @param col new column size
     */
    void resize(size_t row, size_t col);

    /**
     * Empty the matrix.
     */
    void clear();

    /**
     * Check whether or not this matrix is numeric.  A numeric matrix contains
     * only numeric or boolean elements.
     *
     * @return true if the matrix contains only numeric or boolean elements,
     *         or false otherwise.
     */
    bool numeric() const;

    /**
     * Check whether or not this matrix is empty.
     *
     * @return true if this matrix is empty, or false otherwise.
     */
    bool empty() const;

    /**
     * Swap the content of the matrix with another instance.
     */
    void swap(multi_type_matrix& r);

private:

    /**
     * Get an array position of the data referenced by the row and column
     * indices.  The array consists of multiple rows, the content of row 0
     * followded by the content of row 1, and so on.  Note that no
     * boundary check is performed in this method.
     *
     * @param row 0-based row index.
     * @param col 0-based column index.
     * @return position in the data array.
     */
    inline size_type get_pos(size_type row, size_type col) const
    {
        return m_size.column * row + col;
    }

private:
    typedef __mtm::trait<string_type> string_trait;
    typedef __mtm::trait<flag_type> flag_trait;
    typedef mdds::multi_type_vector<typename string_trait::elem_block_func> store_type;
    typedef mdds::multi_type_vector<typename flag_trait::elem_block_func> flag_store_type;

    store_type m_store;
    flag_store_type m_flag_store;
    size_pair_type m_size;
};

}

#include "multi_type_matrix_def.inl"

#endif
<commit_msg>Make this a column-major, to be in line with grid_map.<commit_after>/*************************************************************************
 *
 * Copyright (c) 2012 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#ifndef __MDDS_MULTI_TYPE_MATRIX_HPP__
#define __MDDS_MULTI_TYPE_MATRIX_HPP__

#include "multi_type_vector.hpp"
#include "multi_type_matrix_block_func.hpp"

namespace mdds {

template<typename _String, typename _Flag>
class multi_type_matrix
{
public:
    enum element_t { element_empty, element_boolean, element_string, element_numeric };
    typedef _String     string_type;
    typedef _Flag       flag_type;
    typedef size_t      size_type;

    struct size_pair_type
    {
        size_type row;
        size_type column;
        size_pair_type() : row(0), column(0) {}
        size_pair_type(size_type _row, size_type _column) : row(_row), column(_column) {}
    };

    /**
     * Default constructor.
     */
    multi_type_matrix();

    /**
     * Construct a matrix of specified size with specified density type.
     */
    multi_type_matrix(size_t rows, size_t cols);

    template<typename _T>
    multi_type_matrix(size_t rows, size_t cols, const _T& value);

    multi_type_matrix(const multi_type_matrix& r);
    ~multi_type_matrix();

    multi_type_matrix& operator= (const multi_type_matrix& r);

    /**
     * Get the type of element specified by its position.  The type can be one
     * of empty, string, numeric, or boolean.
     *
     * @return element type.
     */
    element_t get_type(size_t row, size_t col) const;

    double get_numeric(size_t row, size_t col) const;
    bool get_boolean(size_t row, size_t col) const;
    const string_type& get_string(size_t row, size_t col) const;

    void set_empty(size_type row, size_type col);

    void set(size_type row, size_type col, double val);
    void set(size_type row, size_type col, bool val);
    void set(size_type row, size_type col, const string_type& str);

    /**
     * Set flag value at specified position.
     *
     * @param row row position
     * @param col column position
     * @param flag_type flag value
     */
    void set_flag(size_t row, size_t col, flag_type flag);

    /**
     * Get flag value at specified position.
     *
     * @param row row position
     * @param col column position
     *
     * @return flag value stored at specified position
     */
    flag_type get_flag(size_t row, size_t col) const;

    void clear_flag(size_t row, size_t col);

    /**
     * Return the size of matrix as a pair.  The first value is the row size,
     * while the second value is the column size.
     *
     * @return matrix size as a value pair.
     */
    size_pair_type size() const;

    /**
     * Transpose the stored matrix data.
     *
     * @return reference to this matrix instance.
     */
    multi_type_matrix& transpose();

    /**
     * Assign values from the passed matrix instance.  If the size of the
     * passed matrix is smaller, then the element values are assigned by their
     * positions, while the rest of the elements that fall outside the size of
     * the passed matrix instance will remain unmodified.  If the size of the
     * passed matrix instance is larger, then only the elements within the
     * size of this matrix instance will get assigned.
     *
     * @param r passed matrix object to assign element values from.
     */
    void assign(const multi_type_matrix& r);

    /**
     * Resize the matrix to specified size.  This method supports resizing to
     * zero-sized matrix; however, either specifying the row or column size to
     * zero will resize the matrix to 0 x 0.
     *
     * @param row new row size
     * @param col new column size
     */
    void resize(size_t row, size_t col);

    /**
     * Empty the matrix.
     */
    void clear();

    /**
     * Check whether or not this matrix is numeric.  A numeric matrix contains
     * only numeric or boolean elements.
     *
     * @return true if the matrix contains only numeric or boolean elements,
     *         or false otherwise.
     */
    bool numeric() const;

    /**
     * Check whether or not this matrix is empty.
     *
     * @return true if this matrix is empty, or false otherwise.
     */
    bool empty() const;

    /**
     * Swap the content of the matrix with another instance.
     */
    void swap(multi_type_matrix& r);

private:

    /**
     * Get an array position of the data referenced by the row and column
     * indices.  The array consists of multiple columns, the content of column
     * 0 followded by the content of column 1, and so on.  Note that no
     * boundary check is performed in this method.
     *
     * @param row 0-based row index.
     * @param col 0-based column index.
     * @return position in the data array.
     */
    inline size_type get_pos(size_type row, size_type col) const
    {
        return m_size.row * col + row;
    }

private:
    typedef __mtm::trait<string_type> string_trait;
    typedef __mtm::trait<flag_type> flag_trait;
    typedef mdds::multi_type_vector<typename string_trait::elem_block_func> store_type;
    typedef mdds::multi_type_vector<typename flag_trait::elem_block_func> flag_store_type;

    store_type m_store;
    flag_store_type m_flag_store;
    size_pair_type m_size;
};

}

#include "multi_type_matrix_def.inl"

#endif
<|endoftext|>