ALPSCore reference
iniparser_interface.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1998-2018 ALPS Collaboration. See COPYRIGHT.TXT
3  * All rights reserved. Use is subject to license terms. See LICENSE.TXT
4  * For use in publications, see ACKNOWLEDGE.TXT
5  */
6 
11 
12 #include <iniparser.h>
13 
14 #include <stdexcept>
15 #include <algorithm>
16 #include <iterator>
17 
18 
19 namespace alps {
20  namespace params_ns {
21  namespace detail {
22 
23  class ini_dict_impl {
24  dictionary* inidict_;
25 
26  public:
27  struct kv_type {
28  const char* key;
29  const char* val;
30  kv_type(const char* k, const char* v): key(k), val(v) {}
31  };
32 
33  ini_dict_impl(const std::string& inifile)
34  : inidict_(iniparser_load(inifile.c_str()))
35  {
36  if (!inidict_) throw std::runtime_error("Cannot read INI file " + inifile);
37  }
38 
39  ~ini_dict_impl() {
40  if (inidict_) iniparser_freedict(inidict_);
41  }
42 
44  std::size_t size() const;
45 
47  kv_type get_kv(const std::size_t i) const;
48  };
49 
50  std::size_t ini_dict_impl::size() const
51  {
52  int n=inidict_->n;
53  if (n<0) throw std::runtime_error("Dictionary is invalid: negative number of entries");
54  return static_cast<std::size_t>(n);
55  }
56 
57  ini_dict_impl::kv_type ini_dict_impl::get_kv(const std::size_t i) const
58  {
59  if (i>=this->size()) throw std::out_of_range("Access beyond the end of the dictionary");
60  return kv_type(inidict_->key[i], inidict_->val[i]);
61  }
62 
63 
64  /* iniparser implementation */
65 
66  iniparser::iniparser(const std::string& inifile) : ini_dict_ptr_(new ini_dict_impl(inifile))
67  { }
68 
69  iniparser::~iniparser()
70  { }
71 
72  iniparser::kv_container_type iniparser::operator()() const
73  {
74  kv_container_type kv_vec;
75 
76  // the actual vector size will likely be smaller due to sections
77  std::size_t inidict_sz=ini_dict_ptr_->size();
78 
79  kv_vec.reserve(inidict_sz);
80  for (std::size_t i=0; i<inidict_sz; ++i) {
81  ini_dict_impl::kv_type kv=ini_dict_ptr_->get_kv(i);
82  if (kv.val && kv.key) {
83  kv_vec.push_back(std::make_pair(std::string(kv.key),std::string(kv.val)));
84  }
85  }
86  return kv_vec;
87  }
88 
89  } // ::detail
90  } // ::param_ns
91 } // ::alps
std::enable_if<!is_sequence< T >::value, std::size_t >::type size(T const &)
Definition: size.hpp:20