PaddedOutputString.hpp
Go to the documentation of this file.
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
29namespace Opm { namespace EclIO {
30
38 template <std::size_t N>
40 {
41 public:
43 {
44 this->clear();
45 }
46
49 {
50 this->copy_in(s.c_str(), s.size());
51 }
52
54
57
60
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
const char *const string
Definition: cJSON.h:170
Definition: PaddedOutputString.hpp:40
PaddedOutputString & operator=(PaddedOutputString &&rhs)=default
PaddedOutputString()
Definition: PaddedOutputString.hpp:42
const char * c_str() const
Definition: PaddedOutputString.hpp:70
PaddedOutputString(const PaddedOutputString &rhs)=default
PaddedOutputString & operator=(const PaddedOutputString &rhs)=default
PaddedOutputString(PaddedOutputString &&rhs)=default
PaddedOutputString & operator=(const std::string &s)
Assign from.
Definition: PaddedOutputString.hpp:62
PaddedOutputString(const std::string &s)
Definition: PaddedOutputString.hpp:47
Definition: A.hpp:4
T min(const T v0, const T v1)
Definition: exprtk.hpp:1400