RESTinio
sendfile_defs_default.hpp
Go to the documentation of this file.
1 /*
2  restinio
3 */
4 
5 /*!
6  Sendfile routine definitions (default implementation via <cstdio>).
7 
8  @since v.0.4.3
9 */
10 
11 #pragma once
12 
13 #include <cstdio>
14 
15 namespace restinio
16 {
17 
18 /** @name Aliases for sendfile operation.
19  */
20 ///@{
24 ///@}
25 
26 
27 /** @name File operations.
28  * @brief A minimal set of file operations.
29  *
30  * Incapsulates the details *cstdio* API for a set of file operations neccessary
31  * for sendfile_t class implementation.
32  */
33 ///@{
34 
35 //! Get file descriptor which stands for null.
36 constexpr file_descriptor_t null_file_descriptor(){ return nullptr; }
37 
38 //! Open file.
39 inline file_descriptor_t
40 open_file( const char * file_path )
41 {
42  file_descriptor_t file_descriptor = std::fopen( file_path, "rb" );
43 
44  if( null_file_descriptor() == file_descriptor )
45  {
46  throw exception_t{ fmt::format( "std::fopen failed: '{}'", file_path ) };
47  }
48 
49  return file_descriptor;
50 }
51 
52 //! Get file size.
53 template < typename META >
54 META
55 get_file_meta( file_descriptor_t fd )
56 {
57  file_size_t fsize = 0;
58 
59  if( null_file_descriptor() != fd )
60  {
61  // Obtain file size:
62  if( 0 == std::fseek( fd , 0 , SEEK_END ) )
63  {
64  const auto end_pos = std::ftell( fd );
65 
66  if( -1 != end_pos )
67  {
68  fsize = static_cast< file_size_t >( end_pos );
69  std::rewind( fd );
70  }
71  else
72  {
73  throw exception_t{ "std::ftell failed" };
74  }
75  }
76  else
77  {
78  throw exception_t{ "std::fseek failed" };
79  }
80  }
81 
82  // No way to get last modification,
83  // Use current time instead.
84  return META{ fsize, std::chrono::system_clock::now() };
85 }
86 
87 //! Close file by its descriptor.
88 inline void
89 close_file( file_descriptor_t fd )
90 {
91  std::fclose( fd );
92 }
93 ///@}
94 
95 } /* namespace restinio */
constexpr file_descriptor_t null_file_descriptor()
Get file descriptor which stands for null.
void close_file(file_descriptor_t fd)
Close file by its descriptor.
META get_file_meta(file_descriptor_t fd)
Get file size.
file_descriptor_t open_file(const char *file_path)
Open file.
std::enable_if< std::is_same< Parameter_Container, query_string_params_t >::value||std::is_same< Parameter_Container, router::route_params_t >::value, optional_t< Value_Type > >::type opt_value(const Parameter_Container &params, string_view_t key)
Gets the value of a parameter specified by key wrapped in optional_t<Value_Type> if parameter exists ...
Definition: value_or.hpp:64