github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/cache/operation_list.go (about)

     1  package cache
     2  
     3  import (
     4  	"errors"
     5  	"reflect"
     6  )
     7  
     8  func (c *Cache) AddItem(key string, value ...any) error {
     9  	c.mu.Lock()
    10  	defer c.mu.Unlock()
    11  
    12  	if item, found := c.items[key]; found {
    13  		data := item.Data
    14  		if reflect.TypeOf(data).Kind() != reflect.Slice {
    15  			return errors.New("key 对应的数据类型不是 slice")
    16  		}
    17  		item.Data = append(data.([]any), value...)
    18  		c.items[key] = item
    19  	} else {
    20  		e := c.getUnixNano()
    21  		data := Item{
    22  			Data: value,
    23  			Ttl:  e,
    24  		}
    25  		c.items[key] = data
    26  	}
    27  	return nil
    28  }
    29  
    30  //SetItem set or replace a value of items by index
    31  func (c *Cache) SetItem(key string, idx int, value any) error {
    32  	c.mu.Lock()
    33  	defer c.mu.Unlock()
    34  	if item, found := c.items[key]; found {
    35  		data := item.Data
    36  		if reflect.TypeOf(data).Kind() != reflect.Slice {
    37  			return errors.New("key 对应的数据类型不是 slice")
    38  		}
    39  		items := data.([]any)
    40  		if len(items) <= idx {
    41  			return errors.New("数组下标越界")
    42  		}
    43  
    44  		items[idx] = value
    45  		item.Data = items
    46  		return nil
    47  	}
    48  	return errors.New("key不存在")
    49  }
    50  
    51  //GetItem return an array of points or nil
    52  func (c *Cache) GetItem(key string) []any {
    53  	c.mu.Lock()
    54  	defer c.mu.Unlock()
    55  	if item, found := c.items[key]; !found {
    56  		return nil
    57  	} else {
    58  		data := item.Data
    59  		if reflect.TypeOf(data).Kind() != reflect.Slice {
    60  			return nil
    61  		}
    62  		return data.([]any)
    63  	}
    64  }
    65  
    66  //GetItemByIndex return a value of Type is T or nil
    67  func (c *Cache) GetItemByIndex(key string, idx int) any {
    68  	if idx < 0 {
    69  		return nil
    70  	}
    71  	if items := c.GetItem(key); items != nil {
    72  		if len(items) <= idx {
    73  			return nil
    74  		}
    75  		return items[idx]
    76  	}
    77  	return nil
    78  }
    79  
    80  //RemoveItem an item from the cache. Does nothing if the key is not in the cache.
    81  func (c *Cache) RemoveItem(key string, idx int) error {
    82  	if idx < 0 {
    83  		c.Remove(key)
    84  		return nil
    85  	}
    86  	item := c.GetItem(key)
    87  	if item == nil {
    88  		return errors.New("key不存在")
    89  	}
    90  	if len(item) <= idx {
    91  		return nil
    92  	}
    93  	newItem := item[:idx]
    94  	newItem = append(newItem, item[idx+1:]...)
    95  	_ = c.Set(key, newItem)
    96  	return nil
    97  }