compression.h 1.8 KB

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