diff --git a/book.toml b/book.toml index 8bda7adad5..664f29f135 100644 --- a/book.toml +++ b/book.toml @@ -1,3 +1,8 @@ [book] title = "A linguagem de programação Rust" author = "Steve Klabnik e Carol Nichols, com a colaboração da comunidade Rust" + +[output.html] +additional-css = ["ferris.css", "theme/2018-edition.css"] +additional-js = ["ferris.js"] +git-repository-url = "https://github.com/rust-br/rust-book-pt-br" \ No newline at end of file diff --git a/ferris.css b/ferris.css new file mode 100644 index 0000000000..b856d477a8 --- /dev/null +++ b/ferris.css @@ -0,0 +1,33 @@ +body.light .does_not_compile, +body.light .panics, +body.light .not_desired_behavior, +body.rust .does_not_compile, +body.rust .panics, +body.rust .not_desired_behavior { + background: #fff1f1; +} + +body.coal .does_not_compile, +body.coal .panics, +body.coal .not_desired_behavior, +body.navy .does_not_compile, +body.navy .panics, +body.navy .not_desired_behavior, +body.ayu .does_not_compile, +body.ayu .panics, +body.ayu .not_desired_behavior { + background: #501f21; +} + +.ferris { + position: absolute; + z-index: 99; + right: 5px; + top: 30px; + width: 10%; + height: auto; +} + +.ferris-explain { + width: 100px; +} \ No newline at end of file diff --git a/ferris.js b/ferris.js new file mode 100644 index 0000000000..27ecec36b8 --- /dev/null +++ b/ferris.js @@ -0,0 +1,51 @@ +var ferrisTypes = [ + { + attr: 'does_not_compile', + title: 'This code does not compile!' + }, + { + attr: 'panics', + title: 'This code panics!' + }, + { + attr: 'unsafe', + title: 'This code block contains unsafe code.' + }, + { + attr: 'not_desired_behavior', + title: 'This code does not produce the desired behavior.' + } +] + +document.addEventListener('DOMContentLoaded', () => { + for (var ferrisType of ferrisTypes) { + attachFerrises(ferrisType) + } +}) + +function attachFerrises (type) { + var elements = document.getElementsByClassName(type.attr) + + for (var codeBlock of elements) { + var lines = codeBlock.textContent.split(/\r|\r\n|\n/).length - 1; + + if (lines >= 4) { + attachFerris(codeBlock, type) + } + } +} + +function attachFerris (element, type) { + var a = document.createElement('a') + a.setAttribute('href', 'ch00-00-introduction.html#ferris') + a.setAttribute('target', '_blank') + + var img = document.createElement('img') + img.setAttribute('src', 'img/ferris/' + type.attr + '.svg') + img.setAttribute('title', type.title) + img.className = 'ferris' + + a.appendChild(img) + + element.parentElement.insertBefore(a, element) +} \ No newline at end of file diff --git a/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs b/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs new file mode 100644 index 0000000000..50f620033a --- /dev/null +++ b/listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs @@ -0,0 +1,10 @@ +// ANCHOR: here +enum Mensagem { + Sair, + Mover { x: i32, y: i32 }, + Escrever(String), + MudarCor(i32, i32, i32), +} +// ANCHOR_END: here + +fn main() {} \ No newline at end of file diff --git a/listings/ch15-smart-pointers/listing-15-01/src/main.rs b/listings/ch15-smart-pointers/listing-15-01/src/main.rs new file mode 100644 index 0000000000..117d0cb8fb --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-01/src/main.rs @@ -0,0 +1,4 @@ +fn main() { + let b = Box::new(5); + println!("b = {}", b); +} \ No newline at end of file diff --git a/listings/ch15-smart-pointers/listing-15-02/src/main.rs b/listings/ch15-smart-pointers/listing-15-02/src/main.rs new file mode 100644 index 0000000000..25ed4a0f3f --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-02/src/main.rs @@ -0,0 +1,8 @@ +// ANCHOR: here +enum List { + Cons(i32, List), + Nil, +} +// ANCHOR_END: here + +fn main() {} \ No newline at end of file diff --git a/listings/ch15-smart-pointers/listing-15-03/output.txt b/listings/ch15-smart-pointers/listing-15-03/output.txt new file mode 100644 index 0000000000..ec13bf68ea --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/output.txt @@ -0,0 +1,28 @@ +$ cargo run + Compiling cons-list v0.1.0 (file:///projects/cons-list) +error[E0072]: recursive type `List` has infinite size + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ recursive type has infinite size +2 | Cons(i32, List), + | ---- recursive without indirection + | + = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable + +error[E0391]: cycle detected when processing `List` + --> src/main.rs:1:1 + | +1 | enum List { + | ^^^^^^^^^ + | + = note: ...which again requires processing `List`, completing the cycle + = note: cycle used when computing dropck types for `Canonical { max_universe: U0, variables: [], value: ParamEnvAnd { param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, def_id: None }, value: List } }` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0072, E0391. +For more information about an error, try `rustc --explain E0072`. +error: could not compile `cons-list`. + +To learn more, run the command again with --verbose. \ No newline at end of file diff --git a/listings/ch15-smart-pointers/listing-15-03/src/main.rs b/listings/ch15-smart-pointers/listing-15-03/src/main.rs new file mode 100644 index 0000000000..b918a30e0a --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-03/src/main.rs @@ -0,0 +1,12 @@ +enum List { + Cons(i32, List), + Nil, +} + +// ANCHOR: here +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Cons(2, Cons(3, Nil))); +} +// ANCHOR_END: here \ No newline at end of file diff --git a/listings/ch15-smart-pointers/listing-15-05/src/main.rs b/listings/ch15-smart-pointers/listing-15-05/src/main.rs new file mode 100644 index 0000000000..1a8c230522 --- /dev/null +++ b/listings/ch15-smart-pointers/listing-15-05/src/main.rs @@ -0,0 +1,10 @@ +enum List { + Cons(i32, Box), + Nil, +} + +use crate::List::{Cons, Nil}; + +fn main() { + let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); +} \ No newline at end of file diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8cac8563c4..96bd6126a2 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -84,7 +84,7 @@ - [Extending Cargo with Custom Commands](ch14-05-extending-cargo.md) - [🇧🇷 Ponteiros Inteligentes (Smart Pointers)](ch15-00-smart-pointers.md) - - [🇧🇷 `Box` Aponta para Dados no Heap e Tem Tamanho Conhecido](ch15-01-box.md) + - [🇧🇷 Usando `Box` para Apontar Dados no Heap](ch15-01-box.md) - [🇧🇷 Tratando Ponteiros Inteligentes como Referências Normais com a Trait `Deref`](ch15-02-deref.md) - [🇧🇷 A Trait `Drop` Roda Código durante a Limpeza](ch15-03-drop.md) - [🇧🇷 `Rc`, o Ponteiro Inteligente com Contagem de Referências](ch15-04-rc.md) diff --git a/src/ch15-01-box.md b/src/ch15-01-box.md index b7f6551813..e17b601805 100644 --- a/src/ch15-01-box.md +++ b/src/ch15-01-box.md @@ -1,15 +1,15 @@ -## `Box` Aponta para Dados no Heap e Tem Tamanho Conhecido +## Usando `Box` para Apontar Dados no Heap O ponteiro inteligente mais simples é um _box_ (literalmente, "caixa"), cujo -tipo é escrito `Box`. _Boxes_ (plural de _box_) lhe permitem armazenar dados +tipo é escrito `Box`. _Boxes_ permitem armazenar dados no heap em vez de na pilha. O que fica na pilha é o ponteiro para o dado no -heap. Confira o Capítulo 4 para rever a diferença entre pilha e heap. +heap. Confira o Capítulo 4 para relembrar a diferença entre pilha e heap. -Boxes não têm custo adicional de desempenho além de armazenar dados no heap em -vez de na pilha. Mas eles também não têm muitas habilidades a mais. Você irá +Boxes não têm custo adicional de desempenho, além de armazenar dados no heap em +vez de na pilha. Mas eles também não tem muitas habilidades a mais. Você irá usá-los mais comumente nestas situações: -- Quando você tem um tipo cujo tamanho não é possível saber em tempo de +- Quando você tem um tipo cujo tamanho não é conhecido em tempo de compilação, e você quer usar um valor desse tipo em um contexto que precisa saber um tamanho exato; - Quando você tem uma quantidade grande de dados e você quer transferir a posse @@ -17,18 +17,18 @@ usá-los mais comumente nestas situações: - Quando você quer possuir um valor e só se importa se é um tipo que implementa uma trait específica, em vez de saber o tipo concreto. -Vamos demonstrar a primeira situação nesta seção. Mas antes disso, vamos falar +Vamos demonstrar a primeira situação na seção ["Boxes Possibilitam Tipos Recursivos"](#boxes-possibilitam-tipos-recursivos). Mas antes disso, vamos falar um pouco mais sobre as outras duas situações: no segundo caso, transferir posse de uma quantidade grande de dados pode levar muito tempo porque os dados são copiados de um lado para o outro na pilha. Para melhorar o desempenho nessa situação, podemos armazenar essa quantidade grande de dados no heap em um box. Assim, apenas uma quantidade pequena de dados referentes ao ponteiro é copiada na pilha, e os dados em si ficam em um lugar só no heap. O terceiro caso é -conhecido como um _objeto de trait_ (_trait object_), e o Capítulo 17 dedica uma +conhecido como um _objeto rait_ (_trait object_), e o Capítulo 17 dedica uma seção inteira somente a esse tópico. Então o que você aprender aqui você irá aplicar de novo no Capítulo 17! -### Usando um `Box` para Armazenar Dados no Heap +### Usando `Box` para Armazenar Dados no Heap Antes de discutirmos esse caso de uso para o `Box`, vamos cobrir a sintaxe e como interagir com valores armazenados dentro de um `Box`. @@ -38,10 +38,7 @@ A Listagem 15-1 mostra como usar um box para armazenar um valor `i32` no heap: Arquivo: src/main.rs ```rust -fn main() { - let b = Box::new(5); - println!("b = {}", b); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-01/src/main.rs}} ``` Listagem 15-1: Armazenando um valor `i32` no heap usando @@ -110,11 +107,9 @@ demonstraremos: Arquivo: src/main.rs -```rust,ignore -enum List { - Cons(i32, List), - Nil, -} + +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-02/src/main.rs:here}} ``` Listagem 15-2: A primeira tentativa de definir um enum @@ -130,12 +125,8 @@ A listagem 15-3 mostra como fica o uso do tipo `List` para armazenar a lista Arquivo: src/main.rs -```rust,ignore -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, Cons(2, Cons(3, Nil))); -} +```rust,ignore,does_not_compile +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-03/src/main.rs:here}} ``` Listagem 15-3: Usando o enum `List` para armazenar a lista @@ -149,17 +140,8 @@ recursiva que sinaliza o final da lista. Se tentarmos compilar o código na listagem 15-3, receberemos o erro mostrado na listagem 15-4: -```text -erro[E0072]: tipo recursivo `List` tem tamanho infinito - --> src/main.rs:1:1 - | -1 | enum List { - | ^^^^^^^^^ tipo recursivo tem tamanho infinito -2 | Cons(i32, List), - | ----- recursivo sem indireção - | - = ajuda: insira indireção (ex.: um `Box`, `Rc` ou `&`) em algum lugar para - tornar `List` representável +```console +{{#include ../listings/ch15-smart-pointers/listing-15-03/output.txt}} ``` Listagem 15-4: O erro que recebemos quando tentamos @@ -178,12 +160,7 @@ Recorde o enum `Mensagem` que definimos na Listagem 6-2 quando discutimos definições de enums no Capítulo 6: ```rust -enum Mensagem { - Sair, - Mover { x: i32, y: i32 }, - Escrever(String), - MudarCor(i32, i32, i32), -} +{{#rustdoc_include ../listings/ch06-enums-and-pattern-matching/listing-06-02/src/main.rs:here}} ``` Para determinar quanto espaço alocar para um valor `Mensagem`, o Rust percorre @@ -206,6 +183,7 @@ Figura 15-1: Uma cons list infinita + Figura 15-1: Uma `List` infinita feita de infinitas variantes `Cons` @@ -239,19 +217,7 @@ Listagem 15-3 para o código na Listagem 15-5, que compila: Arquivo: src/main.rs ```rust -enum List { - Cons(i32, Box), - Nil, -} - -use List::{Cons, Nil}; - -fn main() { - let list = Cons(1, - Box::new(Cons(2, - Box::new(Cons(3, - Box::new(Nil)))))); -} +{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-05/src/main.rs}} ``` Listagem 15-5: Definição de `List` que usa `Box` para @@ -266,10 +232,10 @@ para que o compilador pudesse determinar o espaço que ele precisa para armarzenar um valor `List`. A Figura 15-2 mostra como ficou a variante `Cons` agora: -Uma lista de Cons infinita +Uma lista de Cons infinita -Figura 15-2: Um `List` que não tem tamanho infinito porque -`Cons` contém um `Box` +Figura 15-2: Um `List` que não tem tamanho infinito +porque `Cons` contém um `Box` Boxes apenas proveem a indireção e a alocação no heap; eles não têm nenhuma outra habilidade especial, como as que vamos ver nos outros tipos de ponteiros diff --git a/src/img/trpl15-01.svg b/src/img/trpl15-01.svg new file mode 100644 index 0000000000..bbeef968a2 --- /dev/null +++ b/src/img/trpl15-01.svg @@ -0,0 +1,43 @@ + + + + + + +%3 + + + +table0 + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + +Cons + +i32 + + + + + diff --git a/src/img/trpl15-02.svg b/src/img/trpl15-02.svg new file mode 100644 index 0000000000..4454df8c38 --- /dev/null +++ b/src/img/trpl15-02.svg @@ -0,0 +1,26 @@ + + + + + + +%3 + + + +table0 + +Cons + +i32 + + +Box + +usize + + + diff --git a/src/img/trpl15-03.svg b/src/img/trpl15-03.svg new file mode 100644 index 0000000000..dbc3b5cdb0 --- /dev/null +++ b/src/img/trpl15-03.svg @@ -0,0 +1,109 @@ + + + + + + +%3 + + + +table4 +b + + + +table5 + +3 + +   + + + +table4:c->table5:pte4 + + + + + +table1 + +5 + +   + + + +table5:c->table1:pte0 + + + + + +table0 +a + + + +table0:c->table1:pte0 + + + + + +table2 + +10 + +   + + + +table1:c->table2:pte1 + + + + + +table3 + +Nil + + + +table2:c->table3:pte2 + + + + + +table6 +c + + + +table7 + +4 + +   + + + +table6:c->table7:pte6 + + + + + +table7:c->table1:pte0 + + + + + diff --git a/src/img/trpl15-04.svg b/src/img/trpl15-04.svg new file mode 100644 index 0000000000..96ad98ca13 --- /dev/null +++ b/src/img/trpl15-04.svg @@ -0,0 +1,55 @@ + + + + + + +%3 + + +table0 + +a + + +table1 + +5 + + + + +table2 + +b + + +table3 + +10 + + + + +table0:ref->table1:data + + + + +table1:ref->table2:data + + + + +table2:ref->table3:data + + + + +table3:ref->table0:data + + + + + diff --git a/theme/2018-edition.css b/theme/2018-edition.css new file mode 100644 index 0000000000..e2bccbd776 --- /dev/null +++ b/theme/2018-edition.css @@ -0,0 +1,9 @@ +span.caption { + font-size: .8em; + font-weight: 600; +} + +span.caption code { + font-size: 0.875em; + font-weight: 400; +} \ No newline at end of file