compression.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #pragma once
  2. #include "stream.h"
  3. #include <util/generic/deque.h>
  4. #include <util/generic/hash.h>
  5. class TCompressionCodecFactory {
  6. public:
  7. using TDecoderConstructor = std::function<THolder<IInputStream>(IInputStream*)>;
  8. using TEncoderConstructor = std::function<THolder<IOutputStream>(IOutputStream*)>;
  9. TCompressionCodecFactory();
  10. static inline TCompressionCodecFactory& Instance() noexcept {
  11. return *SingletonWithPriority<TCompressionCodecFactory, 0>();
  12. }
  13. inline const TDecoderConstructor* FindDecoder(TStringBuf name) const {
  14. if (auto codec = Codecs_.FindPtr(name)) {
  15. return &codec->Decoder;
  16. }
  17. return nullptr;
  18. }
  19. inline const TEncoderConstructor* FindEncoder(TStringBuf name) const {
  20. if (auto codec = Codecs_.FindPtr(name)) {
  21. return &codec->Encoder;
  22. }
  23. return nullptr;
  24. }
  25. inline TArrayRef<const TStringBuf> GetBestCodecs() const {
  26. return BestCodecs_;
  27. }
  28. private:
  29. void Add(TStringBuf name, TDecoderConstructor d, TEncoderConstructor e);
  30. struct TCodec {
  31. TDecoderConstructor Decoder;
  32. TEncoderConstructor Encoder;
  33. };
  34. TDeque<TString> Strings_;
  35. THashMap<TStringBuf, TCodec> Codecs_;
  36. TVector<TStringBuf> BestCodecs_;
  37. };
  38. namespace NHttp {
  39. template <typename F>
  40. TString ChooseBestCompressionScheme(F accepted, TArrayRef<const TStringBuf> available) {
  41. if (available.empty()) {
  42. return "identity";
  43. }
  44. if (accepted("*")) {
  45. return TString(available[0]);
  46. }
  47. for (const auto& coding : available) {
  48. TString s(coding);
  49. if (accepted(s)) {
  50. return s;
  51. }
  52. }
  53. return "identity";
  54. }
  55. }