mapping.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2017. See AUTHORS.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package openssl
  15. import (
  16. "sync"
  17. "unsafe"
  18. )
  19. // #include <stdlib.h>
  20. import "C"
  21. type mapping struct {
  22. lock sync.Mutex
  23. values map[token]unsafe.Pointer
  24. }
  25. func newMapping() *mapping {
  26. return &mapping{
  27. values: make(map[token]unsafe.Pointer),
  28. }
  29. }
  30. type token unsafe.Pointer
  31. func (m *mapping) Add(x unsafe.Pointer) token {
  32. res := token(C.malloc(1))
  33. m.lock.Lock()
  34. m.values[res] = x
  35. m.lock.Unlock()
  36. return res
  37. }
  38. func (m *mapping) Get(x token) unsafe.Pointer {
  39. m.lock.Lock()
  40. res := m.values[x]
  41. m.lock.Unlock()
  42. return res
  43. }
  44. func (m *mapping) Del(x token) {
  45. m.lock.Lock()
  46. delete(m.values, x)
  47. m.lock.Unlock()
  48. C.free(unsafe.Pointer(x))
  49. }