source: trunk/stopos_key.h

Last change on this file was 7, checked in by willem, 11 years ago

willem

File size: 2.5 KB
Line 
1
2/*
3   Copyright 2013 Willem Vermin, SURFsara
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9       http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16 */
17#ifndef STOPOS_KEY_H
18#define STOPOS_KEY_H
19#include <string>
20#include <iostream>
21#include "stopos.h"
22
23class stopos_key
24{
25  protected:
26    std::string value;
27    std::string slot;
28    static const char firstchar = 'a';
29    static const char lastchar  = 'z';
30    static const unsigned int base = lastchar - firstchar + 1;
31    template <typename T> void tostring1(std::string &v,const T n)
32    {
33      if (n == 0)
34        return;
35      unsigned int c = n + firstchar - base*(n/base);
36      tostring1(v,n/base);
37      v.push_back(c);
38    }
39    template <typename T> void tostring(std::string &v,const T n)
40    {
41      if (n == 0)
42        v = firstchar;
43      else
44        tostring1(v,n);
45    }
46  public:
47    stopos_key();
48    stopos_key(const std::string &s);
49    void increment(void);
50    std::string str(void) const;
51    std::string get_key(void) const;
52    std::string get_slot(void) const;
53    void set_key(const std::string &k){ this->value = k;}
54    void set_slot(const std::string &s){ this->slot = s;}
55    void impossible();
56    bool operator==(const stopos_key &k) const;
57    bool operator!=(const stopos_key &k) const;
58
59    // to assign an unsigned integer value to a key
60    template <typename T> void set(const T k,const std::string &slot)
61      {
62        this->value = "";
63        this->tostring(this->value,k);
64        this->slot = slot;
65        return;
66      }
67
68    // to get the unsigned integer value from a key
69    template <typename T> T get() const
70    {
71      T r = 0;
72
73      for (unsigned int i=0; i<this->value.size(); i++)
74        r = this->base*r + this->value[i]-this->firstchar;
75
76      return r;
77    }
78
79    static longuint KeyToNumber(const std::string s)
80    {
81      longuint r = 0;
82      stopos_key d;
83      for (unsigned int i=0; i<s.size(); i++)
84        r = base*r + s[i]-firstchar;
85
86      return r;
87    }
88
89    template <typename T> static std::string NumberToKey(const T n)
90    {
91      std::string s;
92      stopos_key k;
93      k.tostring(s,n);
94      return s;
95    }
96};
97#endif
Note: See TracBrowser for help on using the repository browser.