1 #ifndef MARISA_KEY_H_ 2 #define MARISA_KEY_H_ 3 4 #include "marisa/base.h" 5 6 namespace marisa { 7 8 class Key { 9 public: Key()10 Key() : ptr_(NULL), length_(0), union_() { 11 union_.id = 0; 12 } Key(const Key & key)13 Key(const Key &key) 14 : ptr_(key.ptr_), length_(key.length_), union_(key.union_) {} 15 16 Key &operator=(const Key &key) { 17 ptr_ = key.ptr_; 18 length_ = key.length_; 19 union_ = key.union_; 20 return *this; 21 } 22 23 char operator[](std::size_t i) const { 24 MARISA_DEBUG_IF(i >= length_, MARISA_BOUND_ERROR); 25 return ptr_[i]; 26 } 27 set_str(const char * str)28 void set_str(const char *str) { 29 MARISA_DEBUG_IF(str == NULL, MARISA_NULL_ERROR); 30 std::size_t length = 0; 31 while (str[length] != '\0') { 32 ++length; 33 } 34 MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); 35 ptr_ = str; 36 length_ = (UInt32)length; 37 } set_str(const char * ptr,std::size_t length)38 void set_str(const char *ptr, std::size_t length) { 39 MARISA_DEBUG_IF((ptr == NULL) && (length != 0), MARISA_NULL_ERROR); 40 MARISA_DEBUG_IF(length > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); 41 ptr_ = ptr; 42 length_ = (UInt32)length; 43 } set_id(std::size_t id)44 void set_id(std::size_t id) { 45 MARISA_DEBUG_IF(id > MARISA_UINT32_MAX, MARISA_SIZE_ERROR); 46 union_.id = (UInt32)id; 47 } set_weight(float weight)48 void set_weight(float weight) { 49 union_.weight = weight; 50 } 51 ptr()52 const char *ptr() const { 53 return ptr_; 54 } length()55 std::size_t length() const { 56 return length_; 57 } id()58 std::size_t id() const { 59 return union_.id; 60 } weight()61 float weight() const { 62 return union_.weight; 63 } 64 clear()65 void clear() { 66 Key().swap(*this); 67 } swap(Key & rhs)68 void swap(Key &rhs) { 69 marisa::swap(ptr_, rhs.ptr_); 70 marisa::swap(length_, rhs.length_); 71 marisa::swap(union_.id, rhs.union_.id); 72 } 73 74 private: 75 const char *ptr_; 76 UInt32 length_; 77 union Union { 78 UInt32 id; 79 float weight; 80 } union_; 81 }; 82 83 } // namespace marisa 84 85 #endif // MARISA_KEY_H_ 86