ronantakizawa/codereview-bench huggingface dataset:
Repository: oatpp/oatpp
File: src/oatpp/parser/json/Beautifier.cpp (C++)

Code before:
Beautifier::Beautifier(ConsistentOutputStream* outputStream, const oatpp::String& indent, const oatpp::String& newLine)
  : m_outputStream(outputStream)
  , m_indent(indent)
  , m_newLine(newLine)
  , m_level(0)
  , m_wantIndent(false)
  , m_isCharEscaped(false)
  , m_isInString(false)
{}

void Beautifier::writeIndent(ConsistentOutputStream* outputStream) {
  outputStream->writeSimple(m_newLine->data(), m_newLine->size());
  for(v_int32 i = 0; i < m_level; i ++ ) {
    outputStream->writeSimple(m_indent->data(), m_indent->size());
  }
}

v_io_size Beautifier::write(const void *data, v_buff_size count, async::Action& action) {

  (void) action;

  oatpp::data::stream::BufferOutputStream buffer(count);

  for(v_buff_size i = 0; i < count; i ++) {

    v_char8 c = (reinterpret_cast<p_char8>(const_cast<void*>(data))) [i];

    if(m_isCharEscaped) {
      m_isCharEscaped = false;
      buffer.writeCharSimple(c);
      continue;
    }

    if(m_isInString) {
      if(c == '\\') {
        m_isCharEscaped = true;
      } else if(c == '"') {
        m_isInString = false;
      }
      buffer.writeCharSimple(c);
      continue;
    }

    switch(c) {

      case '{': {
        if(m_wantIndent) {
          writeIndent(&buffer);
        }
        m_level ++;
        m_wantIndent = true;

Review comment (suggestion):
No need to remove const here:

```cpp
v_char8 c = (reinterpret_cast<const char*>(data)) [i];
```

Code after:
Beautifier::Beautifier(ConsistentOutputStream* outputStream, const oatpp::String& indent, const oatpp::String& newLine)
  : m_outputStream(outputStream)
  , m_indent(indent)
  , m_newLine(newLine)
  , m_level(0)
  , m_wantIndent(false)
  , m_isCharEscaped(false)
  , m_isInString(false)
{}

void Beautifier::writeIndent(ConsistentOutputStream* outputStream) {
  outputStream->writeSimple(m_newLine->data(), m_newLine->size());
  for(v_int32 i = 0; i < m_level; i ++ ) {
    outputStream->writeSimple(m_indent->data(), m_indent->size());
  }
}

v_io_size Beautifier::write(const void *data, v_buff_size count, async::Action& action) {

  (void) action;

  oatpp::data::stream::BufferOutputStream buffer(count);

  for(v_buff_size i = 0; i < count; i ++) {

    v_char8 c = (reinterpret_cast<const char*>(data)) [i];

    if(m_isCharEscaped) {
      m_isCharEscaped = false;
      buffer.writeCharSimple(c);
      continue;
    }

    if(m_isInString) {
      if(c == '\\') {
        m_isCharEscaped = true;
      } else if(c == '"') {
        m_isInString = false;
      }
      buffer.writeCharSimple(c);
      continue;
    }

    switch(c) {

      case '{': {
        if(m_wantIndent) {
          writeIndent(&buffer);
        }
        m_level ++;
        m_wantIndent = true;
Repository: oatpp/oatpp
File: test/oatpp/core/data/mapping/type/StringTest.cpp (C++)

Code before:
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************/

#include "StringTest.hpp"

#include "oatpp/core/Types.hpp"

#include <functional>

namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace  type {

void StringTest::onRun() {

  {
    oatpp::String s = "hello"; // check hash function exists
    std::hash<oatpp::String>{}(s);
  }

  {
    OATPP_LOGI(TAG, "test default constructor");
    oatpp::String s;
    OATPP_ASSERT(!s);
    OATPP_ASSERT(s == nullptr);
    OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType());
    OATPP_LOGI(TAG, "OK");
  }

  {
    OATPP_LOGI(TAG, "test nullptr constructor");
    oatpp::String s(nullptr);
    OATPP_ASSERT(!s);
    OATPP_ASSERT(s == nullptr);
    OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType());
    OATPP_LOGI(TAG, "OK");
  }

  {
    OATPP_LOGI(TAG, "test const char* constructor");
    oatpp::String s("abc\0xyz");
    OATPP_ASSERT(s);
    OATPP_ASSERT(s != nullptr);
    OATPP_ASSERT(s->size() == 3);
    OATPP_ASSERT(s == "abc");
    OATPP_ASSERT(s == "abc\0xyz");
    OATPP_LOGI(TAG, "OK");
  }

  {
    OATPP_LOGI(TAG, "test std::string constructor");

Review comment (bug):
It's not a useless test as it seems - there are two different operators: one for `nullptr_t` and one for `const char*`

Code after:
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************/

#include "StringTest.hpp"

#include "oatpp/core/Types.hpp"

#include <functional>

namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace  type {

void StringTest::onRun() {

  {
    oatpp::String s = "hello"; // check hash function exists
    std::hash<oatpp::String>{}(s);
  }

  {
    OATPP_LOGI(TAG, "test default constructor");
    oatpp::String s;
    OATPP_ASSERT(!s);
    OATPP_ASSERT(s == nullptr);
    OATPP_ASSERT(s == static_cast<const char*>(nullptr));
    OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType());
    OATPP_LOGI(TAG, "OK");
  }

  {
    OATPP_LOGI(TAG, "test nullptr constructor");
    oatpp::String s(nullptr);
    OATPP_ASSERT(!s);
    OATPP_ASSERT(s == nullptr);
    OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType());
    OATPP_LOGI(TAG, "OK");
  }

  {
    OATPP_LOGI(TAG, "test const char* constructor");
    oatpp::String s("abc\0xyz");
    OATPP_ASSERT(s);
    OATPP_ASSERT(s != nullptr);
    OATPP_ASSERT(s->size() == 3);
    OATPP_ASSERT(s == "abc");
    OATPP_ASSERT(s == "abc\0xyz");
    OATPP_LOGI(TAG, "OK");
  }

  {
Repository: oatpp/oatpp
File: src/oatpp/network/tcp/Connection.cpp (C++)

Code before:
    } else {
      //OATPP_LOGD("Connection", "write errno=%d", e);
      return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
    }
  }
  return result;

#else

  errno = 0;
  v_int32 flags = 0;

#ifdef MSG_NOSIGNAL
  flags |= MSG_NOSIGNAL;
#endif

  auto result = ::send(m_handle, buff, static_cast<size_t>(count), flags);

  if(result < 0) {
    auto e = errno;

#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif

    bool retry = ((e == EAGAIN) || (e == EWOULDBLOCK));

#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

    if(retry){
      if(m_mode == data::stream::ASYNCHRONOUS) {
        action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
      }
      return IOError::RETRY_WRITE; // For async io. In case socket is non-blocking
    }

    if(e == EINTR) {
      return IOError::RETRY_WRITE;
    }

    if(e == EPIPE) {
      return IOError::BROKEN_PIPE;
    }

    //OATPP_LOGD("Connection", "write errno=%d", e);
    return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
  }
  return result;

Review comment (suggestion):
Let's suppress warning for the whole function - 
just to make code more readable.

```cpp
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif

function {
 ...
}

#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

```

Code after:
      return IOError::RETRY_WRITE; // For async io. In case socket is non-blocking
    } else if(e == WSAEINTR) {
      return IOError::RETRY_WRITE;
    } else if(e == WSAECONNRESET) {
      return IOError::BROKEN_PIPE;
    } else {
      //OATPP_LOGD("Connection", "write errno=%d", e);
      return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
    }
  }
  return result;

#else

  errno = 0;
  v_int32 flags = 0;

#ifdef MSG_NOSIGNAL
  flags |= MSG_NOSIGNAL;
#endif

  auto result = ::send(m_handle, buff, static_cast<size_t>(count), flags);

  if(result < 0) {
    auto e = errno;

    bool retry = ((e == EAGAIN) || (e == EWOULDBLOCK));

    if(retry){
      if(m_mode == data::stream::ASYNCHRONOUS) {
        action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
      }
      return IOError::RETRY_WRITE; // For async io. In case socket is non-blocking
    }

    if(e == EINTR) {
      return IOError::RETRY_WRITE;
    }

    if(e == EPIPE) {
      return IOError::BROKEN_PIPE;
    }

    //OATPP_LOGD("Connection", "write errno=%d", e);
    return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
  }
  return result;

#endif

}
Repository: oatpp/oatpp
File: src/oatpp/network/tcp/Connection.cpp (C++)

Code before:
      return IOError::RETRY_READ; // For async io. In case socket is non-blocking
    } else if(e == WSAEINTR) {
      return IOError::RETRY_READ;
    } else if(e == WSAECONNRESET) {
      return IOError::BROKEN_PIPE;
    } else {
      //OATPP_LOGD("Connection", "write errno=%d", e);
      return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
    }
  }
  return result;

#else

  errno = 0;

  auto result = ::read(m_handle, buff, static_cast<size_t>(count));

  if(result < 0) {
    auto e = errno;

#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif

    bool retry = ((e == EAGAIN) || (e == EWOULDBLOCK));

#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

    if(retry){
      if(m_mode == data::stream::ASYNCHRONOUS) {
        action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_READ);
      }
      return IOError::RETRY_READ; // For async io. In case socket is non-blocking
    }

    if(e == EINTR) {
      return IOError::RETRY_READ;
    }

    if(e == ECONNRESET) {
      return IOError::BROKEN_PIPE;
    }

    //OATPP_LOGD("Connection", "write errno=%d", e);
    return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
  }
  return result;

Review comment (suggestion):
Let's suppress warning for the whole function - 
just to make code more readable.

```cpp
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wlogical-op"
#endif

function {
 ...
}

#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

```

Code after:

    if(e == WSAEWOULDBLOCK){
      if(m_mode == data::stream::ASYNCHRONOUS) {
        action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_READ);
      }
      return IOError::RETRY_READ; // For async io. In case socket is non-blocking
    } else if(e == WSAEINTR) {
      return IOError::RETRY_READ;
    } else if(e == WSAECONNRESET) {
      return IOError::BROKEN_PIPE;
    } else {
      //OATPP_LOGD("Connection", "write errno=%d", e);
      return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
    }
  }
  return result;

#else

  errno = 0;

  auto result = ::read(m_handle, buff, static_cast<size_t>(count));

  if(result < 0) {
    auto e = errno;

    bool retry = ((e == EAGAIN) || (e == EWOULDBLOCK));

    if(retry){
      if(m_mode == data::stream::ASYNCHRONOUS) {
        action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_READ);
      }
      return IOError::RETRY_READ; // For async io. In case socket is non-blocking
    }

    if(e == EINTR) {
      return IOError::RETRY_READ;
    }

    if(e == ECONNRESET) {
      return IOError::BROKEN_PIPE;
    }

    //OATPP_LOGD("Connection", "write errno=%d", e);
    return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
  }
  return result;

#endif

}
Repository: ogham/exa
File: src/options/file_name.rs (Rust)

Code before:
impl Options {
    pub fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
        let classify = Classify::deduce(matches)?;
        let show_icons = ShowIcons::deduce(matches, vars)?;

        Ok(Self { classify, show_icons })
    }
}

impl Classify {
    fn deduce(matches: &MatchedFlags<'_>) -> Result<Self, OptionsError> {
        let flagged = matches.has(&flags::CLASSIFY)?;

        if flagged { Ok(Self::AddFileIndicators) }
              else { Ok(Self::JustFilenames) }
    }
}

impl ShowIcons {
    fn enable_icons(matches: &MatchedFlags<'_>) -> bool {
        matches.has(&flags::ICONS).unwrap_or_default()
            && !matches.has(&flags::NO_ICONS).unwrap_or_default()
    }

    pub fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
        if ! Self::enable_icons(matches) {
            Ok(Self::Off)
        }
        else if let Some(columns) = vars.get(vars::EXA_ICON_SPACING).and_then(|s| s.into_string().ok()) {
            match columns.parse() {
                Ok(width)  => Ok(Self::On(width)),
                Err(e)     => Err(OptionsError::FailedParse(e)),
            }
        }
        else {
            Ok(Self::On(1))
        }
    }
}


Review comment (suggestion):
I’m not an expert on exa codebase, but it seems weird to use `.unwrap_or_default()` when literally everything else using the `has()` method use `?`.

Why not just use `if matches.has(&flags::ICONS)? && !matches.has(&flags::NO_ICONS)? {`. Since it’s not reused, short and clear, it doesn’t need a separate function.

Code after:
impl Options {
    pub fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
        let classify = Classify::deduce(matches)?;
        let show_icons = ShowIcons::deduce(matches, vars)?;

        Ok(Self { classify, show_icons })
    }
}

impl Classify {
    fn deduce(matches: &MatchedFlags<'_>) -> Result<Self, OptionsError> {
        let flagged = matches.has(&flags::CLASSIFY)?;

        if flagged { Ok(Self::AddFileIndicators) }
              else { Ok(Self::JustFilenames) }
    }
}

impl ShowIcons {
    pub fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
        if matches.has(&flags::NO_ICONS)? || !matches.has(&flags::ICONS)? {
            Ok(Self::Off)
        }
        else if let Some(columns) = vars.get(vars::EXA_ICON_SPACING).and_then(|s| s.into_string().ok()) {
            match columns.parse() {
                Ok(width)  => Ok(Self::On(width)),
                Err(e)     => Err(OptionsError::FailedParse(e)),
            }
        }
        else {
            Ok(Self::On(1))
        }
    }
}
Repository: onejs/one
File: packages/vite-native-client/src/client.ts (TypeScript)

Code before:
  )

  // Listen for messages
  socket.addEventListener('message', ({ data }) => {
    console.info('🌶️' + data)
    handleMessage(JSON.parse(data))
  })

  socket.addEventListener('error', (err) => {
    console.info('err' + err['message'] + err['stack'])
  })

  // ping server
  socket.addEventListener('close', ({ wasClean }) => {
    if (wasClean) return

    if (!isOpened && onCloseWithoutOpen) {
      onCloseWithoutOpen()
      return
    }

    notifyListeners('vite:ws:disconnect', { webSocket: socket })

    console.info(`[vite] server connection lost. polling for restart...`)
    waitForSuccessfulPing(protocol, hostAndPath).then(() => {
      console.info('shuld reload')
      // location.reload()
    })
  })

  return socket
}

function warnFailedFetch(err: Error, path: string | string[]) {
  console.error(`${err}`)
  console.error(
    `[hmr] Failed to reload ${path}. ` +
      `This could be due to syntax errors or importing non-existent ` +
      `modules. (see errors above)`
  )
}

let isFirstUpdate = true

const debounceReload = (time: number) => {
  let timer: ReturnType<typeof setTimeout> | null
  return () => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }

Review comment (suggestion):
```suggestion
      console.info('should reload')
```

just a small typo :)

Code after:
  )

  // Listen for messages
  socket.addEventListener('message', ({ data }) => {
    console.info('🌶️' + data)
    handleMessage(JSON.parse(data))
  })

  socket.addEventListener('error', (err) => {
    console.info('err' + err['message'] + err['stack'])
  })

  // ping server
  socket.addEventListener('close', ({ wasClean }) => {
    if (wasClean) return

    if (!isOpened && onCloseWithoutOpen) {
      onCloseWithoutOpen()
      return
    }

    notifyListeners('vite:ws:disconnect', { webSocket: socket })

    console.info(`[vite] server connection lost. polling for restart...`)
    waitForSuccessfulPing(protocol, hostAndPath).then(() => {
      console.info('should reload')
      // location.reload()
    })
  })

  return socket
}

function warnFailedFetch(err: Error, path: string | string[]) {
  console.error(`${err}`)
  console.error(
    `[hmr] Failed to reload ${path}. ` +
      `This could be due to syntax errors or importing non-existent ` +
      `modules. (see errors above)`
  )
}

let isFirstUpdate = true

const debounceReload = (time: number) => {
  let timer: ReturnType<typeof setTimeout> | null
  return () => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
Repository: onevcat/Kingfisher
File: Kingfisher-Demo/ViewController.swift (Swift)

Code before:
        title = "Kingfisher"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func clearCache(sender: AnyObject) {
        KingfisherManager.sharedManager.cache.clearMemoryCache()
        KingfisherManager.sharedManager.cache.clearDiskCache()
    }
    
    @IBAction func reload(sender: AnyObject) {
        collectionView?.reloadData()
    }
}

extension ViewController: UICollectionViewDataSource {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
        cell.cellImageView.kf_setImageWithURL(NSURL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.row + 1).jpg")!, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
            println("\(indexPath.row + 1): \(receivedSize)/\(totalSize)")
        }) { (image, error, cacheType, imageURL) -> () in
            println("\(indexPath.row + 1): Finished")
        }
        
        return cell
    }
}

Review comment (suggestion):
Why don't you add the activity indicator flag as a boolean option that's part of `KingfisherOptionsInfo`


Code after:
        title = "Kingfisher"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func clearCache(sender: AnyObject) {
        KingfisherManager.sharedManager.cache.clearMemoryCache()
        KingfisherManager.sharedManager.cache.clearDiskCache()
    }
    
    @IBAction func reload(sender: AnyObject) {
        collectionView?.reloadData()
    }
}

extension ViewController: UICollectionViewDataSource {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
        cell.cellImageView.kf_showIndicatorWhenLoading = true
        cell.cellImageView.kf_setImageWithURL(NSURL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.row + 1).jpg")!, placeholderImage: nil, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
            println("\(indexPath.row + 1): \(receivedSize)/\(totalSize)")
        }) { (image, error, cacheType, imageURL) -> () in
            println("\(indexPath.row + 1): Finished")
        }
        return cell
    }
}
Repository: onevcat/Kingfisher
File: Sources/Networking/SessionDelegate.swift (Swift)

Code before:
        }
        let token = task.addCallback(callback)
        tasks[url] = task
        return DownloadTask(sessionTask: task, cancelToken: token)
    }

    private func cancelTask(_ dataTask: URLSessionDataTask) {
        lock.lock()
        defer { lock.unlock() }
        dataTask.cancel()
    }

    func append(
        _ task: SessionDataTask,
        url: URL,
        callback: SessionDataTask.TaskCallback) -> DownloadTask
    {
        let token = task.addCallback(callback)
        return DownloadTask(sessionTask: task, cancelToken: token)
    }

    private func remove(_ task: URLSessionTask) {
        lock.lock()
        defer { lock.unlock() }

        guard let url = task.originalRequest?.url else {
            return
        }
        tasks[url] = nil
    }

    private func task(for task: URLSessionTask) -> SessionDataTask? {
        lock.lock()
        defer { lock.unlock() }

        guard let url = task.originalRequest?.url else {
            return nil
        }
        guard let sessionTask = tasks[url] else {
            return nil
        }
        guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
            return nil
        }
        return sessionTask
    }

    func task(for url: URL) -> SessionDataTask? {
        lock.lock()
        defer { lock.unlock() }
        return tasks[url]

Review comment (suggestion):
Wouldn't you want to use `task.originalURL` here as well? Also in `task(for:)`, so we only ever call `task.originalRequest?.url` once, and that's in the `SessionDataTask` init. Then I don't think you need to adjust the locks (or at least I don't think it will affect the behavior)

Code after:
        }
        let token = task.addCallback(callback)
        tasks[url] = task
        return DownloadTask(sessionTask: task, cancelToken: token)
    }

    private func cancelTask(_ dataTask: URLSessionDataTask) {
        lock.lock()
        defer { lock.unlock() }
        dataTask.cancel()
    }

    func append(
        _ task: SessionDataTask,
        url: URL,
        callback: SessionDataTask.TaskCallback) -> DownloadTask
    {
        let token = task.addCallback(callback)
        return DownloadTask(sessionTask: task, cancelToken: token)
    }

    private func remove(_ task: SessionDataTask) {
        lock.lock()
        defer { lock.unlock() }

        guard let url = task.originalURL else {
            return
        }
        tasks[url] = nil
    }

    private func task(for task: URLSessionTask) -> SessionDataTask? {
        lock.lock()
        defer { lock.unlock() }

        guard let url = task.originalRequest?.url else {
            return nil
        }
        guard let sessionTask = tasks[url] else {
            return nil
        }
        guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
            return nil
        }
        return sessionTask
    }

    func task(for url: URL) -> SessionDataTask? {
        lock.lock()
        defer { lock.unlock() }
        return tasks[url]