name: Add Name::deepCopy to allow memory optimizations

Change-Id: I5c498d7524c497e8d7c8e2d89561ff51d1c64d35
Refs: #3618
diff --git a/src/name.cpp b/src/name.cpp
index 0e1b11c..ba6c146 100644
--- a/src/name.cpp
+++ b/src/name.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -64,6 +64,15 @@
   construct(uri.c_str());
 }
 
+Name
+Name::deepCopy() const
+{
+  Name copiedName(*this);
+  copiedName.m_nameBlock.resetWire();
+  copiedName.wireEncode(); // "compress" the underlying buffer
+  return copiedName;
+}
+
 template<encoding::Tag TAG>
 size_t
 Name::wireEncode(EncodingImpl<TAG>& encoder) const
diff --git a/src/name.hpp b/src/name.hpp
index 57a1fde..986ef8f 100644
--- a/src/name.hpp
+++ b/src/name.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -108,6 +108,12 @@
   Name(const std::string& uri);
 
   /**
+   * @brief Make a deep copy of the name, reallocating the underlying memory buffer
+   */
+  Name
+  deepCopy() const;
+
+  /**
    * @brief Fast encoding or block size estimation
    */
   template<encoding::Tag TAG>
diff --git a/tests/unit-tests/name.t.cpp b/tests/unit-tests/name.t.cpp
index 3d0d02e..c1b82aa 100644
--- a/tests/unit-tests/name.t.cpp
+++ b/tests/unit-tests/name.t.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2016 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -559,6 +559,26 @@
   BOOST_CHECK_EQUAL("/first/second/last", name.getSubName(-10, 10));
 }
 
+BOOST_AUTO_TEST_CASE(DeepCopy)
+{
+  Name n1("/hello/world");
+  Name n2 = n1.deepCopy();
+
+  BOOST_CHECK_EQUAL(n1, n2);
+  BOOST_CHECK_NE(&n1.wireEncode(), &n2.wireEncode());
+
+  EncodingBuffer buffer(1024, 0);
+  n1.wireEncode(buffer);
+  Name n3(buffer.block());
+
+  BOOST_CHECK_EQUAL(n1, n3);
+  BOOST_CHECK_EQUAL(n3.wireEncode().getBuffer()->size(), 1024);
+  n3 = n3.deepCopy();
+
+  BOOST_CHECK_LT(n3.wireEncode().size(), 1024);
+  BOOST_CHECK_EQUAL(n3.wireEncode().getBuffer()->size(), n3.wireEncode().size());
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
 } // namespace tests