source: SHVCSoftware/branches/SHM-dev/source/Lib/TAppCommon/program_options_lite.h @ 1457

Last change on this file since 1457 was 1437, checked in by seregin, 9 years ago

formatting of printing output

  • Property svn:eol-style set to native
File size: 9.3 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license.
5 *
6 * Copyright (c) 2010-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33#include <iostream>
34#include <sstream>
35#include <string>
36#include <list>
37#include <map>
38
39#ifndef __PROGRAM_OPTIONS_LITE__
40#define __PROGRAM_OPTIONS_LITE__
41
42//! \ingroup TAppCommon
43//! \{
44
45
46namespace df
47{
48  namespace program_options_lite
49  {
50    struct Options;
51
52    struct ParseFailure : public std::exception
53    {
54      ParseFailure(std::string arg0, std::string val0) throw()
55      : arg(arg0), val(val0)
56      {}
57
58      ~ParseFailure() throw() {};
59
60      std::string arg;
61      std::string val;
62
63      const char* what() const throw() { return "Option Parse Failure"; }
64    };
65
66    struct ErrorReporter
67    {
68      ErrorReporter()
69      : is_errored(0)
70#if 1 //SVC_EXTENSION
71      , verbose(true)
72#endif
73      {}
74      virtual ~ErrorReporter() {}
75      virtual std::ostream& error(const std::string& where);
76      virtual std::ostream& warn(const std::string& where);
77      bool is_errored;
78#if 1 //SVC_EXTENSION
79      bool verbose;
80#endif
81    };
82
83    extern ErrorReporter default_error_reporter;
84
85    void doHelp(std::ostream& out, Options& opts, unsigned columns = 80);
86    std::list<const char*> scanArgv(Options& opts, unsigned argc, const char* argv[], ErrorReporter& error_reporter = default_error_reporter);
87    void setDefaults(Options& opts);
88    void parseConfigFile(Options& opts, const std::string& filename, ErrorReporter& error_reporter = default_error_reporter);
89
90    /** OptionBase: Virtual base class for storing information relating to a
91     * specific option This base class describes common elements.  Type specific
92     * information should be stored in a derived class. */
93    struct OptionBase
94    {
95      OptionBase(const std::string& name, const std::string& desc)
96      : opt_string(name), opt_desc(desc)
97      {};
98
99      virtual ~OptionBase() {}
100
101      /* parse argument arg, to obtain a value for the option */
102      virtual void parse(const std::string& arg, ErrorReporter&) = 0;
103      /* set the argument to the default value */
104      virtual void setDefault() = 0;
105
106      std::string opt_string;
107      std::string opt_desc;
108    };
109
110    /** Type specific option storage */
111    template<typename T>
112    struct Option : public OptionBase
113    {
114      Option(const std::string& name, T& storage, T default_val, const std::string& desc)
115      : OptionBase(name, desc), opt_storage(storage), opt_default_val(default_val)
116      {}
117
118      void parse(const std::string& arg, ErrorReporter&);
119
120      void setDefault()
121      {
122        opt_storage = opt_default_val;
123      }
124
125      T& opt_storage;
126      T opt_default_val;
127    };
128
129    /* Generic parsing */
130    template<typename T>
131    inline void
132    Option<T>::parse(const std::string& arg, ErrorReporter&)
133    {
134      std::istringstream arg_ss (arg,std::istringstream::in);
135      arg_ss.exceptions(std::ios::failbit);
136      try
137      {
138        arg_ss >> opt_storage;
139      }
140      catch (...)
141      {
142        throw ParseFailure(opt_string, arg);
143      }
144    }
145
146    /* string parsing is specialized -- copy the whole string, not just the
147     * first word */
148    template<>
149    inline void
150    Option<std::string>::parse(const std::string& arg, ErrorReporter&)
151    {
152      opt_storage = arg;
153    }
154
155    /** Option class for argument handling using a user provided function */
156    struct OptionFunc : public OptionBase
157    {
158      typedef void (Func)(Options&, const std::string&, ErrorReporter&);
159
160      OptionFunc(const std::string& name, Options& parent_, Func *func_, const std::string& desc)
161      : OptionBase(name, desc), parent(parent_), func(func_)
162      {}
163
164      void parse(const std::string& arg, ErrorReporter& error_reporter)
165      {
166        func(parent, arg, error_reporter);
167      }
168
169      void setDefault()
170      {
171        return;
172      }
173
174    private:
175      Options& parent;
176      Func* func;
177    };
178
179    class OptionSpecific;
180    struct Options
181    {
182      ~Options();
183
184      OptionSpecific addOptions();
185
186      struct Names
187      {
188        Names() : opt(0) {};
189        ~Names()
190        {
191          if (opt)
192          {
193            delete opt;
194          }
195        }
196        std::list<std::string> opt_long;
197        std::list<std::string> opt_short;
198        OptionBase* opt;
199      };
200
201      void addOption(OptionBase *opt);
202
203      typedef std::list<Names*> NamesPtrList;
204      NamesPtrList opt_list;
205
206      typedef std::map<std::string, NamesPtrList> NamesMap;
207      NamesMap opt_long_map;
208      NamesMap opt_short_map;
209    };
210
211    /* Class with templated overloaded operator(), for use by Options::addOptions() */
212    class OptionSpecific
213    {
214    public:
215      OptionSpecific(Options& parent_) : parent(parent_) {}
216
217      /**
218       * Add option described by name to the parent Options list,
219       *   with storage for the option's value
220       *   with default_val as the default value
221       *   with desc as an optional help description
222       */
223      template<typename T>
224      OptionSpecific&
225      operator()(const std::string& name, T& storage, T default_val, const std::string& desc = "")
226      {
227        parent.addOption(new Option<T>(name, storage, default_val, desc));
228        return *this;
229      }
230#if 1 //SVC_EXTENSION
231      template<typename T>
232      OptionSpecific&
233        operator()(const std::string& name, T* storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
234      {
235        std::string cNameBuffer;
236        std::string cDescriptionBuffer;
237
238        cNameBuffer       .resize( name.size() + 10 );
239        cDescriptionBuffer.resize( desc.size() + 10 );
240
241        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
242        {
243          // isn't there are sprintf function for string??
244          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
245          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
246
247          size_t pos = cNameBuffer.find_first_of('\0');
248          if(pos != std::string::npos)
249          {
250            cNameBuffer.resize(pos);
251          }
252     
253          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescriptionBuffer ));
254        }
255
256        return *this;
257      }
258
259      template<typename T>
260      OptionSpecific&
261        operator()(const std::string& name, T** storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
262      {
263        std::string cNameBuffer;
264        std::string cDescriptionBuffer;
265
266        cNameBuffer       .resize( name.size() + 10 );
267        cDescriptionBuffer.resize( desc.size() + 10 );
268
269        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
270        {
271          // isn't there are sprintf function for string??
272          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
273          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
274
275          size_t pos = cNameBuffer.find_first_of('\0');
276          if(pos != std::string::npos)
277            cNameBuffer.resize(pos);
278
279          parent.addOption(new Option<T>( cNameBuffer, *(storage[uiK]), default_val, cDescriptionBuffer ));
280        }
281
282        return *this;
283      }
284#endif
285      /**
286       * Add option described by name to the parent Options list,
287       *   with desc as an optional help description
288       * instead of storing the value somewhere, a function of type
289       * OptionFunc::Func is called.  It is upto this function to correctly
290       * handle evaluating the option's value.
291       */
292      OptionSpecific&
293      operator()(const std::string& name, OptionFunc::Func *func, const std::string& desc = "")
294      {
295        parent.addOption(new OptionFunc(name, parent, func, desc));
296        return *this;
297      }
298    private:
299      Options& parent;
300    };
301
302  } /* namespace: program_options_lite */
303} /* namespace: df */
304
305//! \}
306
307#endif
Note: See TracBrowser for help on using the repository browser.