My Project
PaddedOutputString.hpp
1 /*
2  Copyright (c) 2018 Statoil ASA
3 
4  This file is part of the Open Porous Media project (OPM).
5 
6  OPM is free software: you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  OPM is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with OPM. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 #ifndef OPM_PADDEDOUTPUTSTRING_HEADER_HPP
21 #define OPM_PADDEDOUTPUTSTRING_HEADER_HPP
22 
23 #include <algorithm>
24 #include <array>
25 #include <cstring>
26 #include <cstddef>
27 #include <string>
28 
29 namespace Opm { namespace EclIO {
30 
38  template <std::size_t N>
40  {
41  public:
43  {
44  this->clear();
45  }
46 
47  explicit PaddedOutputString(const std::string& s)
49  {
50  this->copy_in(s.c_str(), s.size());
51  }
52 
53  ~PaddedOutputString() = default;
54 
55  PaddedOutputString(const PaddedOutputString& rhs) = default;
56  PaddedOutputString(PaddedOutputString&& rhs) = default;
57 
58  PaddedOutputString& operator=(const PaddedOutputString& rhs) = default;
59  PaddedOutputString& operator=(PaddedOutputString&& rhs) = default;
60 
62  PaddedOutputString& operator=(const std::string& s)
63  {
64  this->clear();
65  this->copy_in(s.data(), s.size());
66 
67  return *this;
68  }
69 
70  const char* c_str() const
71  {
72  return this->s_.data();
73  }
74 
75  private:
76  enum : typename std::array<char, N + 1>::size_type { NChar = N };
77 
78  std::array<char, NChar + 1> s_;
79 
81  void clear()
82  {
83  this->s_.fill(' ');
84  this->s_[NChar] = '\0';
85  }
86 
89  void copy_in(const char* s,
90  const typename std::array<char, NChar + 1>::size_type len)
91  {
92  const auto ncpy = std::min(len, static_cast<decltype(len)>(NChar));
93 
94  // Note: Not strcpy() or strncpy() here. The former has no bounds
95  // checking, the latter writes a null-terminator at position 'ncpy'
96  // (s_[ncpy]) which violates the post condition if ncpy < NChar.
97  std::memcpy(this->s_.data(), s,
98  ncpy * sizeof *this->s_.data());
99  }
100  };
101 
102 }} // Opm::EclIO
103 #endif // OPM_PADDEDOUTPUTSTRING_HEADER_HPP
Null-terminated, left adjusted, space padded array of N characters.
Definition: PaddedOutputString.hpp:40
PaddedOutputString & operator=(const std::string &s)
Assign from.
Definition: PaddedOutputString.hpp:62
This class implements a small container which holds the transmissibility mulitpliers for all the face...
Definition: Exceptions.hpp:29