summaryrefslogtreecommitdiffstats
path: root/vhdlparser/vhdlstring.h
blob: 1980cf5c5e9413d985af2c5b7833d3ae1f4e3487 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef VHDLSTRING_H
#define VHDLSTRING_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/** @brief Minimal string class with std::string like behaviour that fulfills the JavaCC
 *  string requirements.
 */
class VhdlString
{
  public:
    VhdlString()
    {
      init();
    }
    VhdlString(const VhdlString &other)
    {
      m_str = (char*)malloc(other.m_len+1);
      memcpy(m_str,other.m_str,other.m_len);
      m_len = other.m_len;
      m_str[m_len]=0;
    }
    VhdlString &operator=(const VhdlString &other)
    {
      if (this!=&other)
      {
        free(m_str);
        m_str = (char*)malloc(other.m_len+1);
        memcpy(m_str,other.m_str,other.m_len);
        m_len = other.m_len;
        m_str[m_len]=0;
      }
      return *this;
    }
    VhdlString(const char *s)
    {
      m_len = strlen(s);
      m_str=(char*)malloc(m_len+1);
      memcpy(m_str,s,m_len+1);
    }
    VhdlString(const char *s,int size)
    {
      m_str = (char*)malloc(size+1);
      memcpy(m_str,s,size);
      m_str[size]=0;
      m_len=size;
    }
   ~VhdlString()
    {
      free(m_str);
    }
    VhdlString& append(const char *s,int size)
    {
      int oldlen = m_len;
      m_len+=size+1;
      if (m_len)
      {
        m_str = (char*)realloc(m_str,m_len);
        memcpy(m_str+oldlen,s,m_len-oldlen-1);
        m_str[m_len-1]=0;
      }
      return *this;
    }
    VhdlString& append(const char *s)
    {
      return append(s,strlen(s));
    }
    VhdlString& append(const VhdlString &other)
    {
      return append(other.m_str,other.m_len);
    }
    VhdlString substr(int pos=0,int len=-1)
    {
      return VhdlString(m_str?m_str+pos:0,len==-1?m_len-pos:m_len);
    }
    int copy(char *s,int len,int pos=0) const
    {
      if (len==0) return 0;
      if (pos>=m_len) { s[0]=0; return 0; }
      int r=m_len<pos+len ? m_len-pos : len;
      memcpy(s,m_str+pos,r);
      return r;
    }
    const char *c_str() const           { return m_str; }
    const char *data() const            { return m_str; }
    int         size() const            { return m_len; }
    int         length() const          { return m_len; }
    char &      operator[](int i)       { return m_str[i]; }
    const char &operator[](int i) const { return m_str[i]; }
    void        clear()                 { free(m_str); init(); }
    VhdlString  operator+=(char c)      { char s[2]; s[0]=c; s[1]=0; return append(s); }

  private:
    void init() { m_str=(char*)calloc(1,1); m_len=0; }
    char *m_str;
    int   m_len;
};

#endif