#1 - Pool of Objects

Date: 2018-03-24 12:00 - Go

Synchronous pool of objects referenced by a byte slice identifier. A similar implementation is used in my project AutoRPC to store calls waiting for a response from the remote server.

package main

import (
    "crypto/rand"
    "encoding/hex"
    "errors"
    "fmt"
    "sync"
)

type someType struct {
    someNumber int
}

const idSize = 16

var pool sync.Map

func storeStruct(val *someType) ([]byte, error) {
    result := make([]byte, idSize)
    for {
        n, err := rand.Read(result)
        if err != nil {
            return nil, err
        } else if n != idSize {
            return nil, errors.New("generated id differs in length")
        }

        if _, exists := pool.LoadOrStore(hex.EncodeToString(result), val); !exists {
            break
        }
    }

    return result, nil
}

func loadStruct(id []byte) (*someType, bool) {
    val, ok := pool.Load(hex.EncodeToString(id))
    if !ok {
        return nil, false
    }
    if v, ok := val.(*someType); ok {
        return v, true
    }

    panic("Stored value has wrong type,")
}

func deleteStruct(id []byte) {
    pool.Delete(hex.EncodeToString(id))
}

Usage:

func main() {
    id, _ := storeStruct(&someType{someNumber: 123})
    val, _ := loadStruct(id)
    deleteStruct(id)
    fmt.Println(val.someNumber) // output: 123
}

Previous snippet | Next snippet