registry.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package imagedetect
  2. import (
  3. "sync"
  4. "github.com/imgproxy/imgproxy/v3/imagetype_new"
  5. )
  6. // DetectFunc is a function that detects the image type from byte data
  7. type DetectFunc func(b []byte) (imagetype_new.Type, error)
  8. // MagicBytes represents a magic byte signature for image type detection
  9. // Signature can contain '?' characters which match any byte
  10. type MagicBytes struct {
  11. Signature []byte
  12. Type imagetype_new.Type
  13. }
  14. // Detector represents a registered detector function with its byte requirements
  15. type Detector struct {
  16. Func DetectFunc
  17. BytesNeeded int
  18. }
  19. // Registry manages the registration and execution of image type detectors
  20. type Registry struct {
  21. mu sync.RWMutex
  22. detectors []Detector
  23. magicBytes []MagicBytes
  24. }
  25. // Global registry instance
  26. var registry = &Registry{}
  27. // RegisterDetector registers a custom detector function
  28. // Detectors are tried in the order they were registered
  29. func RegisterDetector(detector DetectFunc, bytesNeeded int) {
  30. registry.mu.Lock()
  31. defer registry.mu.Unlock()
  32. registry.detectors = append(registry.detectors, Detector{
  33. Func: detector,
  34. BytesNeeded: bytesNeeded,
  35. })
  36. }
  37. // RegisterMagicBytes registers magic bytes for a specific image type
  38. // Magic byte detectors are always tried before custom detectors
  39. func RegisterMagicBytes(signature []byte, typ imagetype_new.Type) {
  40. registry.mu.Lock()
  41. defer registry.mu.Unlock()
  42. registry.magicBytes = append(registry.magicBytes, MagicBytes{
  43. Signature: signature,
  44. Type: typ,
  45. })
  46. }
  47. // RegisterDetector registers a custom detector function on this registry instance
  48. func (r *Registry) RegisterDetector(detector DetectFunc, bytesNeeded int) {
  49. r.mu.Lock()
  50. defer r.mu.Unlock()
  51. r.detectors = append(r.detectors, Detector{
  52. Func: detector,
  53. BytesNeeded: bytesNeeded,
  54. })
  55. }
  56. // RegisterMagicBytes registers magic bytes for a specific image type on this registry instance
  57. func (r *Registry) RegisterMagicBytes(signature []byte, typ imagetype_new.Type) {
  58. r.mu.Lock()
  59. defer r.mu.Unlock()
  60. r.magicBytes = append(r.magicBytes, MagicBytes{
  61. Signature: signature,
  62. Type: typ,
  63. })
  64. }