Skip to content
Snippets Groups Projects
ephemeral.go 1.42 KiB
Newer Older
gjahn's avatar
gjahn committed
package state

import (
    "errors"
gjahn's avatar
gjahn committed
)


type Ephemeral struct {
    store map[ string ] Item
    mux sync.Mutex
gjahn's avatar
gjahn committed
}


func NewEphemeralStore() *Ephemeral {
    return &Ephemeral{
        store: map[ string ] Item {},
        mux: sync.Mutex{},
gjahn's avatar
gjahn committed
    }
}


func ( e *Ephemeral ) Add( i *Item ) error {
    if e.store == nil {
        return errors.New( "ephemeral storage not available" )
    }

    name := i.Name()

    e.mux.Lock()
gjahn's avatar
gjahn committed
    e.store[ name ] = i
    e.mux.Unlock()

gjahn's avatar
gjahn committed
    return nil
}


func ( e *Ephemeral ) Remove( name string ) error {
    if e.store == nil {
        return errors.New( "ephemeral storage not available" )
    }

    e.mux.Lock()
gjahn's avatar
gjahn committed
    delete( e.store, name )
    e.mux.Unlock()

gjahn's avatar
gjahn committed
    return nil
}


func ( e *Ephemeral ) Fetch( name string ) ( *Item, error ) {
    if e.store == nil {
        return nil, errors.New( "ephemeral storage not available" )
    }

    e.mux.Lock()
gjahn's avatar
gjahn committed
    item, found := e.store[ name ]
    e.mux.Unlock()

gjahn's avatar
gjahn committed
    if !found {
        return nil, nil
    }
    return item, nil
}


func ( e *Ephemeral ) Show() ( []string, error ) {
    if e.store == nil {
        return nil, errors.New( "ephemeral storage not available" )
    }

    e.mux.Lock()
gjahn's avatar
gjahn committed
    names := make( []string, 0, len( e.store ) )
    for k := range e.store {
        names = append( names, k )
    }
    e.mux.Unlock()

gjahn's avatar
gjahn committed
    return names, nil
}


func ( e *Ephemeral ) Disconnect() error {
    e.store = nil
    return nil
}