non_blocking_adapter.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
  2. // (C) Copyright 2005-2007 Jonathan Turkanis
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
  5. // See http://www.boost.org/libs/iostreams for documentation.
  6. #ifndef BOOST_IOSTREAMS_DETAIL_NON_BLOCKING_ADAPTER_HPP_INCLUDED
  7. #define BOOST_IOSTREAMS_DETAIL_NON_BLOCKING_ADAPTER_HPP_INCLUDED
  8. #include <boost/iostreams/detail/ios.hpp> // streamsize, seekdir, openmode.
  9. #include <boost/iostreams/read.hpp>
  10. #include <boost/iostreams/seek.hpp>
  11. #include <boost/iostreams/traits.hpp>
  12. #include <boost/iostreams/write.hpp>
  13. namespace boost { namespace iostreams {
  14. template<typename Device>
  15. class non_blocking_adapter {
  16. public:
  17. typedef typename char_type_of<Device>::type char_type;
  18. struct category
  19. : mode_of<Device>::type, device_tag
  20. { };
  21. explicit non_blocking_adapter(Device& dev) : device_(dev) { }
  22. std::streamsize read(char_type* s, std::streamsize n)
  23. {
  24. std::streamsize result = 0;
  25. while (result < n) {
  26. std::streamsize amt = iostreams::read(device_, s + result, n - result);
  27. if (amt == -1)
  28. break;
  29. result += amt;
  30. }
  31. return result != 0 ? result : -1;
  32. }
  33. std::streamsize write(const char_type* s, std::streamsize n)
  34. {
  35. std::streamsize result = 0;
  36. while (result < n) {
  37. std::streamsize amt =
  38. iostreams::write(device_, s + result, n - result);
  39. // write errors, like EOF on read, need to be handled.
  40. if (amt == -1)
  41. break;
  42. result += amt;
  43. }
  44. return result;
  45. }
  46. std::streampos seek( stream_offset off, BOOST_IOS::seekdir way,
  47. BOOST_IOS::openmode which =
  48. BOOST_IOS::in | BOOST_IOS::out )
  49. { return iostreams::seek(device_, off, way, which); }
  50. public:
  51. non_blocking_adapter& operator=(const non_blocking_adapter&);
  52. Device& device_;
  53. };
  54. } } // End namespace iostreams.
  55. #endif // #ifndef BOOST_IOSTREAMS_DETAIL_NON_BLOCKING_ADAPTER_HPP_INCLUDED