rts-sim-module/examples/test1/tstorages/model_storage.go
2023-09-22 10:53:51 +08:00

84 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tstorages
import (
"fmt"
"joylink.club/rtsssimulation/system"
)
// 仿真模型数据定义
type ModelData = system.IDeviceModel
// 模型存储、管理仓库
type ModelStorage struct {
//key-模型id,value-模型指针
idModelMap map[string]ModelData
//key-设备类型value-对应设备类型的所有模型数据的指针列表
typeModelMap map[system.DeviceType][]ModelData
}
func NewModelStorage() *ModelStorage {
return &ModelStorage{idModelMap: make(map[string]ModelData, 2048), typeModelMap: make(map[system.DeviceType][]ModelData, 128)}
}
// 添加模型数据
// m 为具体模型数据的指针
func (me *ModelStorage) AddModel(m ModelData) error {
_, ok := me.idModelMap[m.Id()]
if ok {
return fmt.Errorf("模型[%s]已经存在", m.Id())
} else {
me.idModelMap[m.Id()] = m
//
_, mdOk := me.typeModelMap[m.Type()]
if !mdOk {
me.typeModelMap[m.Type()] = make([]ModelData, 0, 512)
}
me.typeModelMap[m.Type()] = append(me.typeModelMap[m.Type()], m)
//
return nil
}
}
// 根据设备类型获取该类型的所有设备数据
func (me *ModelStorage) FindModelsByType(deviceType system.DeviceType) []ModelData {
models, ok := me.typeModelMap[deviceType]
if ok {
return models
} else {
return []ModelData{}
}
}
// 根据设备id获取对应模型数据
// 如果不存在返回nil
func (me *ModelStorage) FindModelById(id string) ModelData {
md, ok := me.idModelMap[id]
if ok {
return md
} else {
return nil
}
}
// 遍历某个类型的所有设备
func (me *ModelStorage) ForEachModelsByType(deviceType system.DeviceType, callback func(md ModelData)) {
mds := me.FindModelsByType(deviceType)
for _, modelData := range mds {
callback(modelData)
}
}
// 根据id检测设备模型数据是否存在
func (me *ModelStorage) HasModelById(id string) bool {
_, ok := me.idModelMap[id]
return ok
}
// 获取当前模型数据总数量
func (me *ModelStorage) AmountOfModels() int {
return len(me.idModelMap)
}
func (me *ModelStorage) AmountOfDeviceTypes() int {
return len(me.typeModelMap)
}