Welcome to mirror list, hosted at ThFree Co, Russian Federation.

value_opt_string.hpp « coding - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9061f454c914550a4682434c6d7de0a108ec5a38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#pragma once

#include "coding/varint.hpp"

#include "base/string_utils.hpp"
#include "base/assert.hpp"

#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>

class StringNumericOptimal
{
  std::string m_s;

public:
  bool operator==(StringNumericOptimal const & rhs) const { return m_s == rhs.m_s; }

  void Set(std::string const & s)
  {
    CHECK(!s.empty(), ());
    m_s = s;
  }

  void Set(char const * p)
  {
    m_s = p;
    CHECK(!m_s.empty(), ());
  }

  template <typename T>
  void Set(T const & s)
  {
    m_s = strings::to_string(s);
    CHECK(!m_s.empty(), ());
  }

  void Clear() { m_s.clear(); }
  bool IsEmpty() const { return m_s.empty(); }
  std::string const & Get() const { return m_s; }

  /// First uint64_t value is:
  /// - a number if low control bit is 1;
  /// - a string size-1 if low control bit is 0;
  template <typename TSink>
  void Write(TSink & sink) const
  {
    // If string is a number and we have space for control bit
    uint64_t n;
    if (strings::to_uint64(m_s, n) && ((n << 1) >> 1) == n)
      WriteVarUint(sink, ((n << 1) | 1));
    else
    {
      size_t const sz = m_s.size();
      ASSERT_GREATER(sz, 0, ());

      WriteVarUint(sink, static_cast<uint32_t>((sz-1) << 1));
      sink.Write(m_s.c_str(), sz);
    }
  }

  template <typename TSource>
  void Read(TSource & src)
  {
    uint64_t sz = ReadVarUint<uint64_t>(src);

    if ((sz & 1) != 0)
      m_s = strings::to_string(sz >> 1);
    else
    {
      sz = (sz >> 1) + 1;
      ASSERT_LESS_OR_EQUAL(sz, std::numeric_limits<size_t>::max(),
                           ("sz is out of platform's range."));
      m_s.resize(static_cast<size_t>(sz));
      src.Read(&m_s[0], sz);
    }
  }
};

inline std::string DebugPrint(StringNumericOptimal const & s) { return s.Get(); }