From c3b9ee314b95e2f2601361d6fc38eb4e9fba5043 Mon Sep 17 00:00:00 2001 From: Konrad Borowski Date: Fri, 1 Jun 2018 09:08:16 +0200 Subject: [PATCH] Use try_borrow for serializing RefCell --- serde/src/ser/impls.rs | 5 ++++- test_suite/tests/test_ser.rs | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/serde/src/ser/impls.rs b/serde/src/ser/impls.rs index 3d088d87..3eb4a88d 100644 --- a/serde/src/ser/impls.rs +++ b/serde/src/ser/impls.rs @@ -459,7 +459,10 @@ where where S: Serializer, { - self.borrow().serialize(serializer) + match self.try_borrow() { + Ok(value) => value.serialize(serializer), + Err(_) => Err(S::Error::custom("already mutably borrowed")), + } } } diff --git a/test_suite/tests/test_ser.rs b/test_suite/tests/test_ser.rs index 795d65f6..21c641a7 100644 --- a/test_suite/tests/test_ser.rs +++ b/test_suite/tests/test_ser.rs @@ -9,6 +9,7 @@ #[macro_use] extern crate serde_derive; +use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::ffi::CString; use std::mem; @@ -563,6 +564,13 @@ fn test_cannot_serialize_paths() { assert_ser_tokens_error(&path_buf, &[], "path contains invalid UTF-8 characters"); } +#[test] +fn test_cannot_serialize_mutably_borrowed_ref_cell() { + let ref_cell = RefCell::new(42); + let _reference = ref_cell.borrow_mut(); + assert_ser_tokens_error(&ref_cell, &[], "already mutably borrowed"); +} + #[test] fn test_enum_skipped() { assert_ser_tokens_error(