package cache import ( "f1-game/internal/extend/math" "strings" cstring "github.com/cherry-game/cherry/extend/string" cutils "github.com/cherry-game/cherry/extend/utils" ) type item struct { ID int64 Name string Name2 string } type MemStore struct { data []item } func NewMemStore() *MemStore { return &MemStore{ data: make([]item, 0), } } // Add 添加新元素 func (m *MemStore) Add(id int64, name string, name2 string) { // 检查是否已存在, 如果存在则不重复添加 for _, item := range m.data { if item.ID == id { return } } m.data = append(m.data, item{ID: id, Name: name, Name2: name2}) } // Update 更新Name数据 func (m *MemStore) Update(id int64, newName string) bool { for i, item := range m.data { if item.ID == id { m.data[i].Name = newName return true } } return false } // Update 更新Name2数据 func (m *MemStore) UpdateName2(id int64, newName2 string) bool { for i, item := range m.data { if item.ID == id { m.data[i].Name2 = newName2 return true } } return false } // Query 查询方法 func (m MemStore) Query(keyword string, pageNum, pageSize int32) (total int32, data []int64) { id := int64(0) if cutils.IsNumeric(keyword) { id, _ = cstring.ToInt64(keyword) } if pageSize == 0 { total = m.countFilteredItems(keyword, id) return total, nil } if pageNum < 1 { pageNum = 1 } if pageSize < 1 { pageSize = 10 } k := strings.ToLower(keyword) total = m.countFilteredItems(keyword, id) start := (pageNum - 1) * pageSize if start >= total { return total, nil } data = make([]int64, 0, math.Min(pageSize, total-start)) currentIndex := int32(0) for _, item := range m.data { if k == "" || item.ID == id || strings.Contains(strings.ToLower(item.Name), k) || strings.Contains(strings.ToLower(item.Name2), k) { if currentIndex >= start && currentIndex < start+pageSize { data = append(data, item.ID) } currentIndex++ if int32(len(data)) >= pageSize { break } } } return total, data } // 计算符合条件总条目数 func (m MemStore) countFilteredItems(keyword string, id int64) int32 { if keyword == "" { return int32(len(m.data)) } k := strings.ToLower(keyword) count := int32(0) for _, item := range m.data { if strings.Contains(strings.ToLower(item.Name), k) || strings.Contains(strings.ToLower(item.Name2), k) || item.ID == id { count++ } } return count } // func main() { // ms := NewMemStore() // // 写入示例数据 // start := time.Now() // for i := int64(1); i <= 1000000; i++ { // ms.Add(i, fmt.Sprintf("user-%07d", i)) // } // fmt.Printf("写入完成,耗时 %v\n", time.Since(start)) // // 查询测试 // start = time.Now() // total, page := ms.Query("456", 1, 10) // fmt.Printf("查询耗时 %v,total=%d\n", time.Since(start), total) // for idx, v := range page { // fmt.Println(idx, "-", v.ID, v.Name) // } // // 测试只获取总数 // start = time.Now() // total, _ = ms.Query("123", 1, 0) // fmt.Printf("仅计数耗时 %v,total=%d\n", time.Since(start), total) // }