file_stream.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/base/file_stream.h"
  5. #include <utility>
  6. #include "net/base/file_stream_context.h"
  7. #include "net/base/net_errors.h"
  8. namespace net {
  9. FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
  10. : context_(std::make_unique<Context>(task_runner)) {}
  11. FileStream::FileStream(base::File file,
  12. const scoped_refptr<base::TaskRunner>& task_runner)
  13. : context_(std::make_unique<Context>(std::move(file), task_runner)) {}
  14. FileStream::~FileStream() {
  15. context_.release()->Orphan();
  16. }
  17. int FileStream::Open(const base::FilePath& path,
  18. int open_flags,
  19. CompletionOnceCallback callback) {
  20. if (IsOpen()) {
  21. DLOG(FATAL) << "File is already open!";
  22. return ERR_UNEXPECTED;
  23. }
  24. DCHECK(open_flags & base::File::FLAG_ASYNC);
  25. context_->Open(path, open_flags, std::move(callback));
  26. return ERR_IO_PENDING;
  27. }
  28. int FileStream::Close(CompletionOnceCallback callback) {
  29. context_->Close(std::move(callback));
  30. return ERR_IO_PENDING;
  31. }
  32. bool FileStream::IsOpen() const {
  33. return context_->IsOpen();
  34. }
  35. int FileStream::Seek(int64_t offset, Int64CompletionOnceCallback callback) {
  36. if (!IsOpen())
  37. return ERR_UNEXPECTED;
  38. context_->Seek(offset, std::move(callback));
  39. return ERR_IO_PENDING;
  40. }
  41. int FileStream::Read(IOBuffer* buf,
  42. int buf_len,
  43. CompletionOnceCallback callback) {
  44. if (!IsOpen())
  45. return ERR_UNEXPECTED;
  46. // read(..., 0) will return 0, which indicates end-of-file.
  47. DCHECK_GT(buf_len, 0);
  48. return context_->Read(buf, buf_len, std::move(callback));
  49. }
  50. int FileStream::Write(IOBuffer* buf,
  51. int buf_len,
  52. CompletionOnceCallback callback) {
  53. if (!IsOpen())
  54. return ERR_UNEXPECTED;
  55. DCHECK_GE(buf_len, 0);
  56. return context_->Write(buf, buf_len, std::move(callback));
  57. }
  58. int FileStream::GetFileInfo(base::File::Info* file_info,
  59. CompletionOnceCallback callback) {
  60. if (!IsOpen())
  61. return ERR_UNEXPECTED;
  62. context_->GetFileInfo(file_info, std::move(callback));
  63. return ERR_IO_PENDING;
  64. }
  65. int FileStream::Flush(CompletionOnceCallback callback) {
  66. if (!IsOpen())
  67. return ERR_UNEXPECTED;
  68. context_->Flush(std::move(callback));
  69. return ERR_IO_PENDING;
  70. }
  71. } // namespace net