Taskcore
Copy an object
Also called shallow copy an object, deep copy an object, clone an object, copy a class instance, duplicate an object.
Make a shallow copy and a deep copy of a Playlist object with a list field, then change the list through the original and show that the shallow copy sees the change and the deep copy does not.
- Evidence
- Code in 9 languages
Task
Write a type Playlist with two fields: a name, and a list of song titles. Make a copy of a playlist in two ways. A shallow copy is a new Playlist whose list field refers to the same list as the original. A deep copy is a new Playlist with a new list that holds the same titles. Then change one title through the original and show the difference: the shallow copy sees the change, and the deep copy does not.
The function copy_and_change(songs, index, title) makes the original from songs, makes the two copies, sets item index of the original's list to title, and returns the titles of the original, of the shallow copy and of the deep copy, in that order. For example, copy_and_change(["Intro", "Song", "Outro"], 1, "Hit") returns [["Intro", "Hit", "Outro"], ["Intro", "Hit", "Outro"], ["Intro", "Song", "Outro"]]. The list has 1 to 1,000 items, and index is a valid index. The tests also check that each copy is a new object, so that a change of the copy's name does not change the original.
Python's copy module gives the two definitions. "A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original." "A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original."1
Solutions
| Language | Shallow copy | Deep copy |
|---|---|---|
| Python | copy.copy(p) |
copy.deepcopy(p) |
| JavaScript | a method that calls the constructor with the same array | a method that copies the array with structuredClone |
| TypeScript | as JavaScript | as JavaScript |
| Java | clone() that calls super.clone() |
a copy constructor with new ArrayList<>(other.songs) |
| C# | MemberwiseClone() |
a method that makes a new List<string> |
| Go | assignment, shallow := original |
assignment, then slices.Clone of the slice field |
| Rust | the derived clone() of a struct with an Rc<RefCell<Vec<String>>> field |
a method that makes a new Rc with a copy of the vector |
| C | struct assignment | a function that allocates a new array and copies each string |
| C++ | the implicit copy constructor of a struct with a std::shared_ptr<std::vector<std::string>> field |
a method that makes a new vector |
- Python needs no code in the class.
copy.copymakes a newPlaylistand copies the attribute references, andcopy.deepcopycopies the list too. A class can change the behavior with__copy__and__deepcopy__. - Java overrides
clonewith a public method that returnsPlaylistand implementsCloneable.Object.clonecopies each field, so "this method performs a "shallow copy" of this object, not a "deep copy" operation".2 The copy constructorPlaylist(Playlist other)makes the deep copy with a newArrayList. - C# calls the protected
MemberwiseClone. "If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object."3 The documentation's own example has aShallowCopyand aDeepCopymethod, as this solution does. - Go copies a struct with assignment. The slice field is a small header: "A slice value contains the slice length, capacity, and a reference to its underlying array."4 So assignment gives a shallow copy, and
DeepCopyreplaces the field withslices.Clone. That function copies only one level: "The elements are copied using assignment, so this is a shallow clone."5 The strings do not need more, because Go strings cannot change. - Rust shows the difference only with a shared pointer. A derived
Cloneon a struct with aVec<String>field copies the vector, which is a deep copy. With anRcfield,clone"creates another pointer to the same allocation, increasing the strong reference count", so the derivedcloneis the shallow copy.6 TheClonedocumentation warns about this case: "for types that are references to other data (such as smart pointers or references), the new value may still point to the same underlying data, rather than duplicating it".7RefCelllets the original change the shared list. - C copies a struct with
=, which copies the pointer to the array of strings. The deep copy allocates a new array and a new copy of each string. The shallow copy owns nothing, so the program frees the original and the deep copy, and not the shallow copy. - C++ has the same choice as Rust. The implicit copy constructor "performs full member-wise copy of the object's direct base class subobjects and member subobjects", so a
std::vectormember is copied element by element.8 With astd::shared_ptrmember, the copy shares the vector, anddeep_copymakes a new one withstd::make_shared. - JavaScript and TypeScript have no copy operation for class instances, so the class has two methods.
shallowCopypasses the same array to the constructor.deepCopypassesstructuredClone(this.songs); a copy of the whole object withstructuredCloneloses the class, as the Pitfalls show.
Alternatives
- Immutable fields. If the list cannot change, for example a Python tuple, a Java
List.copyOfresult or a RustRc<[String]>, a shallow copy is safe, because no one can change the shared part. - A copy method on the type. A Kotlin data class has
copy(), and a C# record has thewithexpression. Both are shallow. Kotlin says that "The copy() function creates a shallow copy of the instance", and C# says that "The result of a with expression is a shallow copy".910 - Copy through serialization. A program can write the object to bytes and read it back, which gives a deep copy of everything that the format can hold. The .NET documentation lists this way among the ways to make a deep copy.3 It is slow, and it loses the parts that the format cannot hold.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
single: a list of one song.firstandlast: the change at index 0 and at the last index.same-title: the new title is the old one, so all three lists are equal. A test that compares only the lists cannot see the sharing here; the tests of each language also check the identity of the lists.duplicates: three equal titles. Only the item at the index changes, so a solution that replaces the first match of the old title in place of the item at the index fails.
Pitfalls
- Assignment is not a copy. In Python, Java, C#, JavaScript and TypeScript,
b = acopies a reference, sobis the same object. "Assignment statements in Python do not copy objects, they create bindings between a target and an object."1 - A deep copy that loses the type.
structuredClonecopies plain data. "The prototype chain is not walked or duplicated. Class private elements are not duplicated."11 The copy of a class instance is a plain object without the methods:
class Playlist {
constructor(name, songs) {
this.name = name;
this.songs = songs;
}
count() {
return this.songs.length;
}
}
const copy = structuredClone(new Playlist("mix", ["a", "b"]));
console.log(copy instanceof Playlist, copy.songs.length, typeof copy.count);
false 2 undefined
- A
clonethat is too shallow. A Java class with a mutable list field that only callssuper.clone()gives a copy that shares the list, which is often not what the caller expects. Copy each mutable field aftersuper.clone(), or use a copy constructor. - Freeing a shared part twice. In C, a shallow copy and the original point to the same array. If the program frees both, it frees the array twice. Give each piece of memory one owner.
- Too much copying. A deep copy copies everything that the object reaches, including data that the copies should share. The Python documentation names this problem: "Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies."1 It also warns that recursive objects "may cause a recursive loop";
deepcopykeeps a memo dictionary to stop it.
Related tasks
- Implement equality for a type compares two objects by value, which is how a test can check a copy.
- Implement a string form for a type gives the type a string form for test messages.
- Define a record type defines a type whose generated copy operation copies the fields.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-an-object/.
"""A shallow copy and a deep copy of an object with a list field."""
import copy
class Playlist:
def __init__(self, name: str, songs: list[str]) -> None:
self.name = name
self.songs = songs
def copy_and_change(songs: list[str], index: int, title: str) -> list[list[str]]:
if not 0 <= index < len(songs):
raise IndexError(f"no song at index {index}")
original = Playlist("mix", list(songs))
shallow = copy.copy(original) # a new Playlist; its songs field is the same list
deep = copy.deepcopy(original) # a new Playlist with a new list
original.songs[index] = title
return [list(original.songs), list(shallow.songs), list(deep.songs)]
test_playlist.py 39 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-an-object/.
import copy
import pytest
from playlist import Playlist, copy_and_change
CASES = {
"middle": ((["Intro", "Song", "Outro"], 1, "Hit"),
[["Intro", "Hit", "Outro"], ["Intro", "Hit", "Outro"], ["Intro", "Song", "Outro"]]),
"two": ((["A", "B"], 0, "C"), [["C", "B"], ["C", "B"], ["A", "B"]]),
"single": ((["Solo"], 0, "Duet"), [["Duet"], ["Duet"], ["Solo"]]),
"first": ((["a", "b", "c"], 0, "z"), [["z", "b", "c"], ["z", "b", "c"], ["a", "b", "c"]]),
"last": ((["a", "b", "c"], 2, "z"), [["a", "b", "z"], ["a", "b", "z"], ["a", "b", "c"]]),
"same-title": ((["a", "b"], 1, "b"), [["a", "b"], ["a", "b"], ["a", "b"]]),
"duplicates": ((["x", "x", "x"], 1, "y"), [["x", "y", "x"], ["x", "y", "x"], ["x", "x", "x"]]),
}
@pytest.mark.parametrize("name", CASES)
def test_copy_and_change(name):
args, want = CASES[name]
assert copy_and_change(*args) == want
def test_copies_are_new_objects():
original = Playlist("mix", ["a"])
shallow, deep = copy.copy(original), copy.deepcopy(original)
assert shallow is not original and deep is not original
assert shallow.songs is original.songs and deep.songs is not original.songs
shallow.name = "other"
assert original.name == "mix"
def test_bad_index():
with pytest.raises(IndexError):
copy_and_change(["a"], 1, "b")
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#include "playlist.hpp"
#include <stdexcept>
namespace playlist {
Playlist Playlist::deep_copy() const { return Playlist{name, std::make_shared<std::vector<std::string>>(*songs)}; }
std::vector<std::vector<std::string>> copy_and_change(const std::vector<std::string>& songs, std::size_t index,
const std::string& title) {
if (index >= songs.size()) {
throw std::out_of_range("no song at this index");
}
Playlist original{"mix", std::make_shared<std::vector<std::string>>(songs)};
Playlist shallow = original; // the implicit copy constructor: a shallow copy
Playlist deep = original.deep_copy();
(*original.songs)[index] = title;
return {*original.songs, *shallow.songs, *deep.songs};
}
} // namespace playlist
playlist.hpp 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#ifndef PLAYLIST_HPP
#define PLAYLIST_HPP
#include <memory>
#include <string>
#include <vector>
namespace playlist {
// The songs field is a shared pointer, so the implicit copy constructor copies the pointer and
// the copy shares the list. A plain std::vector field would be copied element by element.
struct Playlist {
std::string name;
std::shared_ptr<std::vector<std::string>> songs;
// A deep copy: a new vector with the same songs.
Playlist deep_copy() const;
};
// Returns the songs of the original, of a shallow copy and of a deep copy after the original
// sets the song at index to title; throws std::out_of_range for a bad index.
std::vector<std::vector<std::string>> copy_and_change(const std::vector<std::string>& songs, std::size_t index,
const std::string& title);
} // namespace playlist
#endif
test_playlist.cpp 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#include "playlist.hpp"
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
using playlist::Playlist;
using Lists = std::vector<std::vector<std::string>>;
static int failures = 0;
static void check(std::string_view name, const std::vector<std::string>& songs, std::size_t index,
const std::string& title, const Lists& want) {
if (playlist::copy_and_change(songs, index, title) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
static void expect(std::string_view name, bool ok) {
if (!ok) {
std::cerr << "check " << name << " failed\n";
failures++;
}
}
int main() {
check("middle", {"Intro", "Song", "Outro"}, 1, "Hit",
{{"Intro", "Hit", "Outro"}, {"Intro", "Hit", "Outro"}, {"Intro", "Song", "Outro"}});
check("two", {"A", "B"}, 0, "C", {{"C", "B"}, {"C", "B"}, {"A", "B"}});
check("single", {"Solo"}, 0, "Duet", {{"Duet"}, {"Duet"}, {"Solo"}});
check("first", {"a", "b", "c"}, 0, "z", {{"z", "b", "c"}, {"z", "b", "c"}, {"a", "b", "c"}});
check("last", {"a", "b", "c"}, 2, "z", {{"a", "b", "z"}, {"a", "b", "z"}, {"a", "b", "c"}});
check("same-title", {"a", "b"}, 1, "b", {{"a", "b"}, {"a", "b"}, {"a", "b"}});
check("duplicates", {"x", "x", "x"}, 1, "y", {{"x", "y", "x"}, {"x", "y", "x"}, {"x", "x", "x"}});
Playlist original{"mix", std::make_shared<std::vector<std::string>>(std::vector<std::string>{"a"})};
Playlist shallow = original;
Playlist deep = original.deep_copy();
expect("shared", shallow.songs == original.songs && deep.songs != original.songs);
shallow.name = "other";
expect("own name", original.name == "mix");
bool threw = false;
try {
playlist::copy_and_change({"a"}, 1, "b");
} catch (const std::out_of_range&) {
threw = true;
}
expect("bad index", threw);
if (failures == 0) {
std::cout << "all tests passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
import java.util.ArrayList;
import java.util.List;
/** A playlist with a list field, copied in two ways. */
public final class Playlist implements Cloneable {
private String name;
private final List<String> songs;
public Playlist(String name, List<String> songs) {
this.name = name;
this.songs = songs;
}
/** A deep copy: a copy constructor that makes a new list. */
public Playlist(Playlist other) {
this(other.name, new ArrayList<>(other.songs));
}
/** A shallow copy: Object.clone copies the fields, so the copy shares the list. */
@Override
public Playlist clone() {
try {
return (Playlist) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public String name() {
return name;
}
public void setName(String name) {
this.name = name;
}
/** Returns the list itself, not a copy, so that a caller can see the sharing. */
public List<String> songs() {
return songs;
}
public static List<List<String>> copyAndChange(List<String> songs, int index, String title) {
Playlist original = new Playlist("mix", new ArrayList<>(songs));
Playlist shallow = original.clone();
Playlist deep = new Playlist(original);
original.songs().set(index, title);
return List.of(List.copyOf(original.songs()), List.copyOf(shallow.songs()), List.copyOf(deep.songs()));
}
}
PlaylistTest.java 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class PlaylistTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of(
"middle",
List.of("Intro", "Song", "Outro"),
1,
"Hit",
List.of(List.of("Intro", "Hit", "Outro"), List.of("Intro", "Hit", "Outro"), List.of("Intro", "Song", "Outro"))),
Arguments.of("two", List.of("A", "B"), 0, "C", List.of(List.of("C", "B"), List.of("C", "B"), List.of("A", "B"))),
Arguments.of("single", List.of("Solo"), 0, "Duet", List.of(List.of("Duet"), List.of("Duet"), List.of("Solo"))),
Arguments.of(
"first",
List.of("a", "b", "c"),
0,
"z",
List.of(List.of("z", "b", "c"), List.of("z", "b", "c"), List.of("a", "b", "c"))),
Arguments.of(
"last",
List.of("a", "b", "c"),
2,
"z",
List.of(List.of("a", "b", "z"), List.of("a", "b", "z"), List.of("a", "b", "c"))),
Arguments.of(
"same-title", List.of("a", "b"), 1, "b", List.of(List.of("a", "b"), List.of("a", "b"), List.of("a", "b"))),
Arguments.of(
"duplicates",
List.of("x", "x", "x"),
1,
"y",
List.of(List.of("x", "y", "x"), List.of("x", "y", "x"), List.of("x", "x", "x"))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void copyAndChange(String name, List<String> songs, int index, String title, List<List<String>> want) {
assertEquals(want, Playlist.copyAndChange(songs, index, title), name);
}
@Test
void copiesAreNewObjects() {
Playlist original = new Playlist("mix", new java.util.ArrayList<>(List.of("a")));
Playlist shallow = original.clone();
Playlist deep = new Playlist(original);
assertNotSame(original, shallow);
assertSame(original.songs(), shallow.songs());
assertNotSame(original.songs(), deep.songs());
shallow.setName("other");
assertEquals("mix", original.name());
}
@Test
void badIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> Playlist.copyAndChange(List.of("a"), 1, "b"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#include "playlist.h"
#include <stdlib.h>
#include <string.h>
static char *copy_string(const char *s) {
size_t n = strlen(s) + 1;
char *c = malloc(n);
if (c != NULL) {
memcpy(c, s, n);
}
return c;
}
bool playlist_make(const char *const *songs, size_t count, Playlist *out) {
out->count = count;
out->songs = calloc(count > 0 ? count : 1, sizeof *out->songs);
if (out->songs == NULL) {
return false;
}
for (size_t i = 0; i < count; i++) {
out->songs[i] = copy_string(songs[i]);
if (out->songs[i] == NULL) {
playlist_free(out);
return false;
}
}
return true;
}
Playlist playlist_shallow_copy(const Playlist *p) { return *p; }
bool playlist_deep_copy(const Playlist *p, Playlist *out) {
return playlist_make((const char *const *)p->songs, p->count, out);
}
bool playlist_set(Playlist *p, size_t index, const char *title) {
if (index >= p->count) {
return false;
}
char *c = copy_string(title);
if (c == NULL) {
return false;
}
free(p->songs[index]);
p->songs[index] = c;
return true;
}
void playlist_free(Playlist *p) {
if (p->songs != NULL) {
for (size_t i = 0; i < p->count; i++) {
free(p->songs[i]);
}
free(p->songs);
}
p->songs = NULL;
p->count = 0;
}
bool copy_and_change(const char *const *songs, size_t count, size_t index, const char *title, Playlist results[3]) {
if (index >= count || !playlist_make(songs, count, &results[0])) {
return false;
}
results[1] = playlist_shallow_copy(&results[0]);
if (!playlist_deep_copy(&results[0], &results[2])) {
playlist_free(&results[0]);
return false;
}
if (!playlist_set(&results[0], index, title)) {
playlist_free(&results[0]);
playlist_free(&results[2]);
return false;
}
return true;
}
playlist.h 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#ifndef PLAYLIST_H
#define PLAYLIST_H
#include <stdbool.h>
#include <stddef.h>
// A playlist owns an array of count strings.
typedef struct {
char **songs;
size_t count;
} Playlist;
// playlist_make copies each string into a new playlist; it returns false when memory runs out.
bool playlist_make(const char *const *songs, size_t count, Playlist *out);
// playlist_shallow_copy copies the struct: the copy shares the array and the strings.
// Do not free a shallow copy; free the original once.
Playlist playlist_shallow_copy(const Playlist *p);
// playlist_deep_copy makes a new array and new strings; free it with playlist_free.
bool playlist_deep_copy(const Playlist *p, Playlist *out);
// playlist_set replaces the song at index with a copy of title.
bool playlist_set(Playlist *p, size_t index, const char *title);
void playlist_free(Playlist *p);
// copy_and_change fills results with the original, a shallow copy and a deep copy after the
// original sets the song at index to title. Free results[0] and results[2] with playlist_free.
bool copy_and_change(const char *const *songs, size_t count, size_t index, const char *title, Playlist results[3]);
#endif
test_playlist.c 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
#include "playlist.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
// want holds 3 * count strings: the songs of the original, the shallow copy and the deep copy.
static void check(const char *name, const char *const *songs, size_t count, size_t index, const char *title,
const char *const *want) {
Playlist r[3];
if (!copy_and_change(songs, count, index, title, r)) {
fprintf(stderr, "case %s failed: error\n", name);
failures++;
return;
}
for (size_t k = 0; k < 3; k++) {
for (size_t i = 0; i < count; i++) {
if (r[k].count != count || strcmp(r[k].songs[i], want[k * count + i]) != 0) {
fprintf(stderr, "case %s failed at list %zu item %zu\n", name, k, i);
failures++;
k = 3;
break;
}
}
}
playlist_free(&r[0]);
playlist_free(&r[2]);
}
static void expect(const char *name, bool ok) {
if (!ok) {
fprintf(stderr, "check %s failed\n", name);
failures++;
}
}
int main(void) {
check("middle", (const char *[]){"Intro", "Song", "Outro"}, 3, 1, "Hit",
(const char *[]){"Intro", "Hit", "Outro", "Intro", "Hit", "Outro", "Intro", "Song", "Outro"});
check("two", (const char *[]){"A", "B"}, 2, 0, "C", (const char *[]){"C", "B", "C", "B", "A", "B"});
check("single", (const char *[]){"Solo"}, 1, 0, "Duet", (const char *[]){"Duet", "Duet", "Solo"});
check("first", (const char *[]){"a", "b", "c"}, 3, 0, "z",
(const char *[]){"z", "b", "c", "z", "b", "c", "a", "b", "c"});
check("last", (const char *[]){"a", "b", "c"}, 3, 2, "z",
(const char *[]){"a", "b", "z", "a", "b", "z", "a", "b", "c"});
check("same-title", (const char *[]){"a", "b"}, 2, 1, "b", (const char *[]){"a", "b", "a", "b", "a", "b"});
check("duplicates", (const char *[]){"x", "x", "x"}, 3, 1, "y",
(const char *[]){"x", "y", "x", "x", "y", "x", "x", "x", "x"});
Playlist original;
expect("make", playlist_make((const char *[]){"a"}, 1, &original));
Playlist shallow = playlist_shallow_copy(&original);
Playlist deep;
expect("deep", playlist_deep_copy(&original, &deep));
expect("shared array", shallow.songs == original.songs && deep.songs != original.songs);
expect("own strings", deep.songs[0] != original.songs[0] && strcmp(deep.songs[0], "a") == 0);
playlist_free(&original);
playlist_free(&deep);
Playlist r[3];
expect("bad index", !copy_and_change((const char *[]){"a"}, 1, 1, "b", r));
if (failures == 0) {
printf("all tests passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
using System;
using System.Collections.Generic;
/// <summary>A playlist with a list field, copied in two ways.</summary>
public sealed class Playlist
{
public string Name { get; set; }
public List<string> Songs { get; }
public Playlist(string name, List<string> songs)
{
Name = name;
Songs = songs;
}
// A shallow copy: MemberwiseClone copies the fields, so the copy shares the list.
public Playlist ShallowCopy() => (Playlist)MemberwiseClone();
// A deep copy: a new Playlist with a new list.
public Playlist DeepCopy() => new(Name, new List<string>(Songs));
public static List<List<string>> CopyAndChange(IReadOnlyList<string> songs, int index, string title)
{
if (index < 0 || index >= songs.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
var original = new Playlist("mix", new List<string>(songs));
var shallow = original.ShallowCopy();
var deep = original.DeepCopy();
original.Songs[index] = title;
return new List<List<string>> { new(original.Songs), new(shallow.Songs), new(deep.Songs) };
}
}
PlaylistTests.cs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
using System;
using System.Collections.Generic;
using Xunit;
public sealed class PlaylistTests
{
public static TheoryData<string, string[], int, string, string[][]> Cases => new()
{
{ "middle", new[] { "Intro", "Song", "Outro" }, 1, "Hit",
new[] { new[] { "Intro", "Hit", "Outro" }, new[] { "Intro", "Hit", "Outro" }, new[] { "Intro", "Song", "Outro" } } },
{ "two", new[] { "A", "B" }, 0, "C", new[] { new[] { "C", "B" }, new[] { "C", "B" }, new[] { "A", "B" } } },
{ "single", new[] { "Solo" }, 0, "Duet", new[] { new[] { "Duet" }, new[] { "Duet" }, new[] { "Solo" } } },
{ "first", new[] { "a", "b", "c" }, 0, "z", new[] { new[] { "z", "b", "c" }, new[] { "z", "b", "c" }, new[] { "a", "b", "c" } } },
{ "last", new[] { "a", "b", "c" }, 2, "z", new[] { new[] { "a", "b", "z" }, new[] { "a", "b", "z" }, new[] { "a", "b", "c" } } },
{ "same-title", new[] { "a", "b" }, 1, "b", new[] { new[] { "a", "b" }, new[] { "a", "b" }, new[] { "a", "b" } } },
{ "duplicates", new[] { "x", "x", "x" }, 1, "y", new[] { new[] { "x", "y", "x" }, new[] { "x", "y", "x" }, new[] { "x", "x", "x" } } },
};
[Theory]
[MemberData(nameof(Cases))]
public void CopyAndChange(string name, string[] songs, int index, string title, string[][] want)
{
Assert.NotNull(name);
var got = Playlist.CopyAndChange(songs, index, title);
Assert.Equal(want.Length, got.Count);
for (var i = 0; i < want.Length; i++)
{
Assert.Equal(want[i], got[i]);
}
}
[Fact]
public void CopiesAreNewObjects()
{
var original = new Playlist("mix", new List<string> { "a" });
var shallow = original.ShallowCopy();
var deep = original.DeepCopy();
Assert.NotSame(original, shallow);
Assert.Same(original.Songs, shallow.Songs);
Assert.NotSame(original.Songs, deep.Songs);
shallow.Name = "other";
Assert.Equal("mix", original.Name);
}
[Fact]
public void BadIndex()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Playlist.CopyAndChange(new[] { "a" }, 1, "b"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
export class Playlist {
constructor(name, songs) {
this.name = name;
this.songs = songs;
}
// A shallow copy: a new Playlist whose songs field refers to the same array.
shallowCopy() {
return new Playlist(this.name, this.songs);
}
// A deep copy: a new Playlist with its own copy of the array.
deepCopy() {
return new Playlist(this.name, structuredClone(this.songs));
}
}
export function copyAndChange(songs, index, title) {
if (!Number.isInteger(index) || index < 0 || index >= songs.length) {
throw new RangeError(`no song at index ${index}`);
}
const original = new Playlist("mix", [...songs]);
const shallow = original.shallowCopy();
const deep = original.deepCopy();
original.songs[index] = title;
return [[...original.songs], [...shallow.songs], [...deep.songs]];
}
playlist.test.js 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Playlist, copyAndChange } from "./playlist.js";
const cases = [
["middle", [["Intro", "Song", "Outro"], 1, "Hit"], [["Intro", "Hit", "Outro"], ["Intro", "Hit", "Outro"], ["Intro", "Song", "Outro"]]],
["two", [["A", "B"], 0, "C"], [["C", "B"], ["C", "B"], ["A", "B"]]],
["single", [["Solo"], 0, "Duet"], [["Duet"], ["Duet"], ["Solo"]]],
["first", [["a", "b", "c"], 0, "z"], [["z", "b", "c"], ["z", "b", "c"], ["a", "b", "c"]]],
["last", [["a", "b", "c"], 2, "z"], [["a", "b", "z"], ["a", "b", "z"], ["a", "b", "c"]]],
["same-title", [["a", "b"], 1, "b"], [["a", "b"], ["a", "b"], ["a", "b"]]],
["duplicates", [["x", "x", "x"], 1, "y"], [["x", "y", "x"], ["x", "y", "x"], ["x", "x", "x"]]],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.deepEqual(copyAndChange(...args), want);
});
}
test("copies are new objects", () => {
const original = new Playlist("mix", ["a"]);
const shallow = original.shallowCopy();
const deep = original.deepCopy();
assert.ok(shallow !== original && deep !== original);
assert.ok(shallow.songs === original.songs && deep.songs !== original.songs);
shallow.name = "other";
assert.equal(original.name, "mix");
});
test("structuredClone drops the class", () => {
const copy = structuredClone(new Playlist("mix", ["a"]));
assert.ok(!(copy instanceof Playlist));
assert.deepEqual(copy.songs, ["a"]);
});
test("bad index", () => {
assert.throws(() => copyAndChange(["a"], 1, "b"), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
export class Playlist {
name: string;
songs: string[];
constructor(name: string, songs: string[]) {
this.name = name;
this.songs = songs;
}
// A shallow copy: a new Playlist whose songs field refers to the same array.
shallowCopy(): Playlist {
return new Playlist(this.name, this.songs);
}
// A deep copy: a new Playlist with its own copy of the array.
deepCopy(): Playlist {
return new Playlist(this.name, structuredClone(this.songs));
}
}
export function copyAndChange(songs: string[], index: number, title: string): string[][] {
if (!Number.isInteger(index) || index < 0 || index >= songs.length) {
throw new RangeError(`no song at index ${index}`);
}
const original = new Playlist("mix", [...songs]);
const shallow = original.shallowCopy();
const deep = original.deepCopy();
original.songs[index] = title;
return [[...original.songs], [...shallow.songs], [...deep.songs]];
}
playlist.test.ts 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { Playlist, copyAndChange } from "./playlist.ts";
const cases: [string, [string[], number, string], string[][]][] = [
["middle", [["Intro", "Song", "Outro"], 1, "Hit"], [["Intro", "Hit", "Outro"], ["Intro", "Hit", "Outro"], ["Intro", "Song", "Outro"]]],
["two", [["A", "B"], 0, "C"], [["C", "B"], ["C", "B"], ["A", "B"]]],
["single", [["Solo"], 0, "Duet"], [["Duet"], ["Duet"], ["Solo"]]],
["first", [["a", "b", "c"], 0, "z"], [["z", "b", "c"], ["z", "b", "c"], ["a", "b", "c"]]],
["last", [["a", "b", "c"], 2, "z"], [["a", "b", "z"], ["a", "b", "z"], ["a", "b", "c"]]],
["same-title", [["a", "b"], 1, "b"], [["a", "b"], ["a", "b"], ["a", "b"]]],
["duplicates", [["x", "x", "x"], 1, "y"], [["x", "y", "x"], ["x", "y", "x"], ["x", "x", "x"]]],
];
for (const [name, args, want] of cases) {
test(name, () => {
assert.deepEqual(copyAndChange(args[0], args[1], args[2]), want);
});
}
test("copies are new objects", () => {
const original = new Playlist("mix", ["a"]);
const shallow = original.shallowCopy();
const deep = original.deepCopy();
assert.ok(shallow !== original && deep !== original);
assert.ok(shallow.songs === original.songs && deep.songs !== original.songs);
shallow.name = "other";
assert.equal(original.name, "mix");
});
test("structuredClone drops the class", () => {
const copy = structuredClone(new Playlist("mix", ["a"]));
assert.ok(!(copy instanceof Playlist));
assert.deepEqual(copy.songs, ["a"]);
});
test("bad index", () => {
assert.throws(() => copyAndChange(["a"], 1, "b"), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
// Package playlist copies a struct with a slice field in two ways.
package playlist
import (
"fmt"
"slices"
)
// Playlist is a struct with a slice field.
type Playlist struct {
Name string
Songs []string
}
// DeepCopy returns a copy with its own slice. Assignment alone copies the
// slice header, so the copy would share the array of the original.
func (p Playlist) DeepCopy() Playlist {
c := p
c.Songs = slices.Clone(p.Songs)
return c
}
// CopyAndChange changes one song through the original and returns the songs
// of the original, of a shallow copy and of a deep copy.
func CopyAndChange(songs []string, index int, title string) ([][]string, error) {
if index < 0 || index >= len(songs) {
return nil, fmt.Errorf("no song at index %d", index)
}
original := Playlist{Name: "mix", Songs: slices.Clone(songs)}
shallow := original // a shallow copy: the fields are copied, and Songs shares the array
deep := original.DeepCopy()
original.Songs[index] = title
return [][]string{slices.Clone(original.Songs), slices.Clone(shallow.Songs), slices.Clone(deep.Songs)}, nil
}
playlist_test.go 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
package playlist
import (
"slices"
"testing"
)
var cases = []struct {
name string
songs []string
index int
title string
want [][]string
}{
{"middle", []string{"Intro", "Song", "Outro"}, 1, "Hit",
[][]string{{"Intro", "Hit", "Outro"}, {"Intro", "Hit", "Outro"}, {"Intro", "Song", "Outro"}}},
{"two", []string{"A", "B"}, 0, "C", [][]string{{"C", "B"}, {"C", "B"}, {"A", "B"}}},
{"single", []string{"Solo"}, 0, "Duet", [][]string{{"Duet"}, {"Duet"}, {"Solo"}}},
{"first", []string{"a", "b", "c"}, 0, "z", [][]string{{"z", "b", "c"}, {"z", "b", "c"}, {"a", "b", "c"}}},
{"last", []string{"a", "b", "c"}, 2, "z", [][]string{{"a", "b", "z"}, {"a", "b", "z"}, {"a", "b", "c"}}},
{"same-title", []string{"a", "b"}, 1, "b", [][]string{{"a", "b"}, {"a", "b"}, {"a", "b"}}},
{"duplicates", []string{"x", "x", "x"}, 1, "y", [][]string{{"x", "y", "x"}, {"x", "y", "x"}, {"x", "x", "x"}}},
}
func TestCopyAndChange(t *testing.T) {
for _, c := range cases {
got, err := CopyAndChange(c.songs, c.index, c.title)
if err != nil || !slices.EqualFunc(got, c.want, slices.Equal[[]string]) {
t.Errorf("case %s: got %v, %v; want %v", c.name, got, err, c.want)
}
}
}
func TestCopiesDiffer(t *testing.T) {
original := Playlist{Name: "mix", Songs: []string{"a"}}
shallow := original
deep := original.DeepCopy()
shallow.Name = "other"
if original.Name != "mix" {
t.Error("a change of the copy's name changed the original")
}
if &shallow.Songs[0] != &original.Songs[0] || &deep.Songs[0] == &original.Songs[0] {
t.Error("the shallow copy must share the array and the deep copy must not")
}
}
func TestBadIndex(t *testing.T) {
if _, err := CopyAndChange([]string{"a"}, 1, "b"); err == nil {
t.Error("index 1 of one song gave no error")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
//! A shallow copy and a deep copy of a struct with a list field.
//!
//! A derived `Clone` on a struct with a `Vec` field copies the vector, so it is a deep copy.
//! To share the list, the field is an `Rc<RefCell<Vec<String>>>`; cloning an `Rc` copies the
//! pointer, not the list.
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub struct Playlist {
pub name: String,
pub songs: Rc<RefCell<Vec<String>>>,
}
impl Playlist {
pub fn new(name: &str, songs: Vec<String>) -> Self {
Playlist { name: name.to_string(), songs: Rc::new(RefCell::new(songs)) }
}
/// A shallow copy: the derived `clone` copies the name and the `Rc` pointer.
pub fn shallow_copy(&self) -> Self {
self.clone()
}
/// A deep copy: a new `Rc` that holds a copy of the list.
pub fn deep_copy(&self) -> Self {
Playlist {
name: self.name.clone(),
songs: Rc::new(RefCell::new(self.songs.borrow().clone())),
}
}
}
/// Changes one song through the original and returns the songs of the original, of a shallow
/// copy and of a deep copy, or None when the index is out of range.
pub fn copy_and_change(songs: &[&str], index: usize, title: &str) -> Option<Vec<Vec<String>>> {
if index >= songs.len() {
return None;
}
let original = Playlist::new("mix", songs.iter().map(|s| s.to_string()).collect());
let shallow = original.shallow_copy();
let deep = original.deep_copy();
original.songs.borrow_mut()[index] = title.to_string();
let songs_of = |p: &Playlist| p.songs.borrow().clone();
Some(vec![songs_of(&original), songs_of(&shallow), songs_of(&deep)])
}
tests/playlist_test.rs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-an-object/.
use std::rc::Rc;
use algo_copy_an_object::{copy_and_change, Playlist};
#[test]
fn cases() {
let cases: Vec<(&str, Vec<&str>, usize, &str, Vec<Vec<&str>>)> = vec![
(
"middle",
vec!["Intro", "Song", "Outro"],
1,
"Hit",
vec![vec!["Intro", "Hit", "Outro"], vec!["Intro", "Hit", "Outro"], vec!["Intro", "Song", "Outro"]],
),
("two", vec!["A", "B"], 0, "C", vec![vec!["C", "B"], vec!["C", "B"], vec!["A", "B"]]),
("single", vec!["Solo"], 0, "Duet", vec![vec!["Duet"], vec!["Duet"], vec!["Solo"]]),
("first", vec!["a", "b", "c"], 0, "z", vec![vec!["z", "b", "c"], vec!["z", "b", "c"], vec!["a", "b", "c"]]),
("last", vec!["a", "b", "c"], 2, "z", vec![vec!["a", "b", "z"], vec!["a", "b", "z"], vec!["a", "b", "c"]]),
("same-title", vec!["a", "b"], 1, "b", vec![vec!["a", "b"], vec!["a", "b"], vec!["a", "b"]]),
("duplicates", vec!["x", "x", "x"], 1, "y", vec![vec!["x", "y", "x"], vec!["x", "y", "x"], vec!["x", "x", "x"]]),
];
for (name, songs, index, title, want) in cases {
let want: Vec<Vec<String>> = want.iter().map(|v| v.iter().map(|s| s.to_string()).collect()).collect();
assert_eq!(copy_and_change(&songs, index, title), Some(want), "case {name}");
}
}
#[test]
fn copies_differ() {
let original = Playlist::new("mix", vec!["a".to_string()]);
let mut shallow = original.shallow_copy();
let deep = original.deep_copy();
assert!(Rc::ptr_eq(&original.songs, &shallow.songs));
assert!(!Rc::ptr_eq(&original.songs, &deep.songs));
shallow.name = "other".to_string();
assert_eq!(original.name, "mix");
}
#[test]
fn bad_index() {
assert_eq!(copy_and_change(&["a"], 1, "b"), None);
}
References
- copy, Shallow and deep copy operations, Python standard library, Introduction; Interface summary
- Object (Java SE 21 & JDK 21), API documentation, clone
- Object.MemberwiseClone Method, .NET API reference, Remarks; Examples
- The Go Programming Language Specification, Slice types
- slices package, Go standard library, func Clone
- Rc, Rust standard library, impl Clone for Rc
- Clone trait, Rust standard library, Description
- Copy constructors, cppreference.com, Implicitly-defined copy constructor
- Data classes, Kotlin documentation, Copying
- Records, C# reference, Nondestructive mutation
- The structured clone algorithm, MDN, Things that don't work with structured clone
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag YFXM5G Edit this page History Report an error Markdown