| |   |
| 39 | 39 | \section{Duas sequências de elementos} |
| 40 | 40 | Uma boa metáfora para entender um fluxo é a seguinte: Um fluxo pode ser representada como duas sequências de elementos: a sequência de elementos visitados e a sequência de elementos a visitar. O fluxo é posicionado entre as duas sequências. Entender este modelo é importante uma vez que todos as operações de fluxo em \st dependem dele. |
| 41 | 41 | Por esta razão, a maioria das classes de \clsind{Fluxo} são subclasses de \clsind{PositionableStream}. |
| 42 | | \figref{_abcde} apresenta um fluxo que contém cinco caracteres. Este fluxo está na sua posição original, \ie não há elementos já visitados. Você pode voltar a esta posição usando a mensagem \mthind{PositionableStream}{reset}. |
| 42 | A \figref{_abcde} apresenta um fluxo que contém cinco caracteres. Este fluxo está na sua posição original, portanto a lista de elementos já visitados está vazia. Você pode voltar a esta posição usando a mensagem \mthind{PositionableStream}{reset}. |
| 43 | 43 | |
| 44 | 44 | \begin{figure}[ht] |
| 45 | 45 | \centerline{\includegraphics[scale=0.5]{_abcdeStef}} |
| … | … | |
| 48 | 48 | \vspace{.2in} |
| 49 | 49 | \end{figure} |
| 50 | 50 | |
| 51 | | A leitura de um elemento conceitualmente significa remover o primeiro elemento da sequência de elementos a visitar e colocá-lo na sequência de elementos visitados. Após ter lido um elemento usando a mensagem \ct{next}, o estado do seu fluxo fica semelhante ao mostrado na \figref{a_bcde}. |
| 51 | A leitura de um elemento conceitualmente significa remover o primeiro elemento da sequência de elementos a visitar e colocá-lo na sequência de elementos visitados. Após ter lido um elemento usando a mensagem \ct{next}, o estado do fluxo fica semelhante ao mostrado na \figref{a_bcde}. |
| 52 | 52 | |
| 53 | 53 | \begin{figure}[ht] |
| 54 | 54 | \centerline{\includegraphics[scale=0.5]{a_bcdeStef}} |
| … | … | |
| 100 | 100 | w nextPut: 12. --> resulta numa excecao |
| 101 | 101 | \end{code} |
| 102 | 102 | |
| 103 | | Fluxos não são apenas direcionado a coleções, eles podem ser usados em arquivos ou sockets também. O exemplo a seguir cria um arquivo chamado \ct{test.txt}, escreve duas strings separadas por uma quebra de linha, e fecha o arquivo. |
| 103 | Fluxos não são apenas direcionado a coleções, eles também podem ser usados em arquivos ou sockets. O exemplo a seguir cria um arquivo chamado \ct{test.txt}, escreve duas strings separadas por uma quebra de linha, e fecha o arquivo. |
| 104 | 104 | |
| 105 | 105 | \needlines{3} |
| 106 | 106 | \begin{code}{} |
| … | … | |
| 113 | 113 | \end{code} |
| 114 | 114 | \cmindex{FileStream class}{fileNamed:do:} |
| 115 | 115 | |
| 116 | | As seções a seguir apresentam tais protocolos em mais detalhes. |
| 116 | As seções a seguir apresentam tais protocolos em detalhes. |
| 117 | 117 | |
| 118 | 118 | %============================================================= |
| 119 | 119 | \section{Criando fluxos a partir de coleções} |
| … | … | |
| 123 | 123 | %----------------------------------------------------------------- |
| 124 | 124 | \subsection{Lendo coleções} |
| 125 | 125 | |
| 126 | | Esta seção apresenta os recursos usados para a leitura de coleções. Ao usar um fluxo para ler uma coleção, você recebe um ponteiro para a coleção. Este ponteiro irá se mover para frente conforme a leitura é feita, e você pode posicionar este ponteiro onde desejar. A classe \clsindmain{ReadStream} deve ser usada par ler elementos de coleções. |
| 126 | Esta seção apresenta os recursos usados para a leitura de coleções. Ao usar um fluxo para ler uma coleção, você recebe um ponteiro para a coleção. Este ponteiro irá se mover para frente conforme a leitura é feita, e você pode posicionar este ponteiro onde desejar. A classe \clsindmain{ReadStream} deve ser usada para fazer a leitura dos elementos. |
| 127 | 127 | |
| 128 | 128 | Os métodos \mthind{ReadStream}{next} e \mthind{ReadStream}{next:} são usados para obter um ou mais elementos da coleção. |
| 129 | 129 | |
| … | … | |
| 231 | 231 | %----------------------------------------------------------------- |
| 232 | 232 | \subsection{Escrevendo em coleções} |
| 233 | 233 | |
| 234 | | Nós acabamos de ver como iterar nos elementos de uma coleção usando \ct{ReadStream}. Agora nós iremos aprender como criar coleções usando \clsindmain{WriteStream}{}s. |
| 234 | Nós acabamos de ver como iterar nos elementos de uma coleção usando \ct{ReadStream}. Agora nós iremos aprender como criar coleções usando a classe \clsindmain{WriteStream}{}. |
| 235 | 235 | |
| 236 | | \ct{WriteStream}s are useful for appending a lot of data to a collection at various locations. They are often used to construct strings that are based on static and dynamic parts as in this example: |
| 236 | \ct{WriteStream}s são úteis para incluir dados em vários pontos numa coleção. Esses objetos são frequentemente usados para construir strings baseadas em partes estáticas e dinâmicas, como no exemplo a seguir: |
| 237 | 237 | |
| 238 | | \begin{code}{NB: can't be tested due to the changing number of classes} |
| 238 | \begin{code}{NB: não pode ser testado em razão do número variável de classes.} |
| 239 | 239 | stream := String new writeStream. |
| 240 | 240 | stream |
| 241 | | nextPutAll: 'This Smalltalk image contains: '; |
| 241 | nextPutAll: 'Esta imagem Smalltalk contem: '; |
| 242 | 242 | print: Smalltalk allClasses size; |
| 243 | 243 | nextPutAll: ' classes.'; |
| 244 | 244 | cr; |
| 245 | | nextPutAll: 'This is really a lot.'. |
| 245 | nextPutAll: 'Muita coisa!'. |
| 246 | 246 | |
| 247 | | stream contents. --> 'This Smalltalk image contains: 2322 classes. |
| 248 | | This is really a lot.' |
| 247 | stream contents. --> 'Esta imagem Smalltalk contem: 2322 classes. |
| 248 | Muita coisa!' |
| 249 | 249 | \end{code} |
| 250 | 250 | |
| 251 | | This technique is used in the different implementations of the method |
| 252 | | \ct{printOn:} for example. There is a simpler and more efficient way |
| 253 | | of creating streams if you are only interested in the content of the |
| 254 | | stream: |
| 251 | Esta técnica é usada em diferentes implementações do método \ct{printOn:}, por exemplo. Existe uma forma mais simples e eficiente de criar fluxos se você está interessado apenas no seu conteúdo: |
| 255 | 252 | |
| 256 | 253 | \begin{code}{@TEST |string|} |
| 257 | 254 | string := String streamContents: |
| … | … | |
| 264 | 264 | string. --> '#(1 2 3) size = 3' |
| 265 | 265 | \end{code} |
| 266 | 266 | |
| 267 | | The method \mthind{SequenceableCollection class}{streamContents:} \label{sec:streamContents} creates a collection and a stream on |
| 268 | | that collection for you. It then executes the block you gave passing |
| 269 | | the stream as a parameter. When the block ends, \ct{streamContents:} |
| 270 | | returns the content of the collection. |
| 267 | O método \mthind{SequenceableCollection class}{streamContents:} \label{sec:streamContents} cria uma coleção e um fluxo para essa coleção. Ele então executa o bloco que foi passado como parâmetro. Quando o bloco termina, o método \ct{streamContents:} retorna o conteúdo da coleção. |
| 271 | 268 | |
| 272 | | The following \ct{WriteStream} methods are especially useful in this context: |
| 269 | O método \ct{WriteStream} a seguir é especialmente útil neste contexto: |
| 273 | 270 | |
| 274 | 271 | \begin{description} |
| 275 | | \item[\lct{nextPut:}] adds the parameter to the stream; |
| 276 | | \item[\lct{nextPutAll:}] adds each element of the collection, passed as a |
| 277 | | parameter, to the stream; |
| 278 | | \item[\lct{print:}] adds the textual representation of the parameter to the |
| 279 | | stream. |
| 272 | \item[\lct{nextPut:}] adiciona o parâmetro ao fluxo; |
| 273 | \item[\lct{nextPutAll:}] adiciona ao fluxo cada elemento da coleção passada como parâmetro; |
| 274 | \item[\lct{print:}] adiciona ao fluxo a representação textual do parâmetro; |
| 280 | 275 | \cmindex{Stream}{print:} |
| 281 | 276 | \end{description} |
| 282 | 277 | |
| 283 | | There are also methods useful for printing different kinds of characters to |
| 284 | | the stream like \mthind{WriteStream}{space}, \mthind{WriteStream}{tab} and |
| 285 | | \mthind{WriteStream}{cr} (carriage return). Another useful |
| 286 | | method is \mthind{WriteStream}{ensureASpace} which ensures that the last character |
| 287 | | in the stream is a space; if the last character isn't a space it adds one. |
| 278 | Ainda existem métodos úteis para imprimir diferentes tipos de caracteres ao fluxo como \mthind{WriteStream}{space}, \mthind{WriteStream}{tab} e \mthind{WriteStream}{cr} (\foreign{carriage return}). Outro método útil é \mthind{WriteStream}{ensureASpace}, que garante que o último caractere do fluxo seja um espaço; se não for, um espaço é adicionado. |
| 288 | 279 | |
| 289 | | \paragraph{About Concatenation.} |
| 290 | | Using \mthind{WriteStream}{nextPut:} and \mthind{WriteStream}{nextPutAll:} on a \ct{WriteStream} is often the best way to |
| 291 | | concatenate characters. Using the comma concatenation operator (\ct{,}) is far |
| 292 | | less efficient: |
| 293 | | \index{Collection!comma operator} |
| 280 | \paragraph{Sobre Concatenação.} |
| 281 | Usando os métodos \mthind{WriteStream}{nextPut:} e \mthind{WriteStream}{nextPutAll:} num \ct{WriteStream} é, na maioria das vezes, a melhor forma de se concatenar caracteres. Usar o operador de concatenação (\ct{,}) é muito menos eficiente: |
| 282 | |
| 283 | \index{Coleção!operador vírgula} |
| 294 | 284 | |
| 295 | 285 | \begin{code}{} |
| 296 | 286 | [| temp | |
| … | … | |
| 295 | 295 | temp contents] timeToRun --> 1262 "(milliseconds)" |
| 296 | 296 | \end{code} |
| 297 | 297 | |
| 298 | | The reason that using a stream can be much more efficient is that |
| 299 | | comma creates a new string containing |
| 300 | | the concatenation of the receiver and the argument, so it must copy both of them. |
| 301 | | When you repeatedly concatenate onto the same receiver, it gets longer and longer each time, |
| 302 | | so that the number of characters that must be copied goes up exponentially. |
| 303 | | This also creates a lot of garbage, which must be collected. Using |
| 304 | | a stream instead of string concatenation is a well-known optimization. |
| 298 | A razão de um fluxo ser muito mais eficiente é que a vírgula cria uma nova string contendo a concatenação do objeto receptor e do argumento, copiando então ambos os objetos. Quando você concatena repetidamente ao mesmo receptor, ele fica maior a cada vez, de modo que o número de caracteres que precisam ser copiados aumenta exponencialmente. Isso também cria muito lixo, que deve ser coletado. Usar um fluxo no lugar da concatenação de strings é uma otimização muito conhecida. |
| 305 | 299 | \lr{About Concatenation. This is not true for real world examples (the example benchmark is unrealistic). Most of the time concatenation is simpler, cleaner and much faster, for example when being used on a small number of longer strings. (p. 257)} |
| 306 | | In fact, you can use \mthind{SequenceableCollection class}{streamContents:} (mentioned on page \pageref{sec:streamContents}) to help you do this: |
| 300 | Na verdade, você pode usar \mthind{SequenceableCollection class}{streamContents:} (mencionado na página \pageref{sec:streamContents}) para te ajudar a fazer isso: |
| 307 | 301 | |
| 308 | 302 | \begin{code}{} |
| 309 | 303 | String streamContents: [ :tempStream | |
| … | … | |
| 306 | 306 | \end{code} |
| 307 | 307 | |
| 308 | 308 | %----------------------------------------------------------------- |
| 309 | | \subsection{Reading and writing at the same time} |
| 309 | \subsection{Lendo e escrevendo ao mesmo tempo} |
| 310 | 310 | |
| 311 | | It's possible to use a stream to access a collection for reading and |
| 312 | | writing at the same time. |
| 313 | | Imagine you want to create an \ct{History} class which will manage |
| 314 | | backward and forward buttons in a web browser. |
| 315 | | A history would react as in figures from \ref{fig:emptyStream} to |
| 316 | | \ref{fig:page4}. |
| 311 | É possível usar um fluxo para acessar uma coleção para leitura e escrita ao mesmo tempo. |
| 312 | Imagine que você queira criar uma classe \ct{History} que irá gerenciar os botões ``voltar'' e ``avançar'' em um navegador web. |
| 313 | O histórico reagiria de acordo com as figuras \ref{fig:emptyStream} a \ref{fig:page4}. |
| 317 | 314 | |
| 318 | 315 | \begin{figure}[!ht] |
| 319 | 316 | \centerline{\includegraphics[scale=0.5]{emptyStef}} |
| 320 | | \caption{A new history is empty. Nothing is displayed in the web browser.} |
| 317 | \caption{O novo histórico está vazio. Nada é mostrado no navegador web.} |
| 321 | 318 | \label{fig:emptyStream} |
| 322 | 319 | \vspace{.2in} |
| 323 | 320 | \end{figure} |
| 324 | 321 | |
| 325 | 322 | \begin{figure}[!ht] |
| 326 | 323 | \centerline{\includegraphics[scale=0.5]{page1Stef}} |
| 327 | | \caption{The user opens to page 1.} |
| 324 | \caption{O usuário abre a página 1.} |
| 328 | 325 | \label{fig:page1} |
| 329 | 326 | \vspace{.2in} |
| 330 | 327 | \end{figure} |
| 331 | 328 | |
| 332 | 329 | \begin{figure}[!ht] |
| 333 | 330 | \centerline{\includegraphics[scale=0.5]{page2Stef}} |
| 334 | | \caption{The user clicks on a link to page 2.} |
| 331 | \caption{O usuário clica em um link para a página 2.} |
| 335 | 332 | \label{fig:page2} |
| 336 | 333 | \vspace{.2in} |
| 337 | 334 | \end{figure} |
| 338 | 335 | |
| 339 | 336 | \begin{figure}[!ht] |
| 340 | 337 | \centerline{\includegraphics[scale=0.5]{page3Stef}} |
| 341 | | \caption{The user clicks on a link to page 3.} |
| 338 | \caption{O usuário clica em um link para a página 3.} |
| 342 | 339 | \label{fig:page3} |
| 343 | 340 | \vspace{.2in} |
| 344 | 341 | \end{figure} |
| 345 | 342 | |
| 346 | 343 | \begin{figure}[!ht] |
| 347 | 344 | \centerline{\includegraphics[scale=0.5]{page2_Stef}} |
| 348 | | \caption{The user clicks on the back button. He is now viewing page 2 again.} |
| 345 | \caption{O usuário clica no botão ``voltar''. Ele está agora vendo a página 2 novamente.} |
| 349 | 346 | \label{fig:page2_} |
| 350 | 347 | \vspace{.2in} |
| 351 | 348 | \end{figure} |
| 352 | 349 | |
| 353 | 350 | \begin{figure}[!ht] |
| 354 | 351 | \centerline{\includegraphics[scale=0.5]{page1_Stef}} |
| 355 | | \caption{The user clicks again the back button. Page 1 is now displayed.} |
| 352 | \caption{O usuário clica novamente no botão ``voltar''. A página 1 está agora sendo mostrada.} |
| 356 | 353 | \label{fig:page1_} |
| 357 | 354 | \vspace{.2in} |
| 358 | 355 | \end{figure} |
| 359 | 356 | |
| 360 | 357 | \begin{figure}[!ht] |
| 361 | 358 | \centerline{\includegraphics[scale=0.5]{page4Stef}} |
| 362 | | \caption{From page 1, the user clicks on a link to page 4. The history forgets pages 2 and 3.} |
| 359 | \caption{Da página 1, o usuário clica em um link para a página 4. O histórico esquece das páginas 2 e 3.} |
| 363 | 360 | \label{fig:page4} |
| 364 | 361 | \vspace{.2in} |
| 365 | 362 | \end{figure} |
| 366 | 363 | |
| 367 | | This behaviour can be implemented using a \clsind{ReadWriteStream}. |
| 364 | Este comportamento pode ser implementado sando um \clsind{ReadWriteStream}. |
| 368 | 365 | |
| 369 | 366 | \needlines{6} |
| 370 | 367 | \begin{code}{} |
| … | … | |
| 376 | 376 | stream := ReadWriteStream on: Array new. |
| 377 | 377 | \end{code} |
| 378 | 378 | |
| 379 | | Nothing really difficult here, we define a new class which contains a |
| 380 | | stream. The stream is created during the \ct{initialize} method. |
| 379 | Nada de muito complicado aqui, apenas definimos uma nova classe que contém um fluxo. O fluxo é criado no método \ct{initialize}. |
| 381 | 380 | |
| 382 | | We need methods to go backward and forward: |
| 381 | Nós precisamos de métodos para voltar e avançar: |
| 383 | 382 | |
| 384 | 383 | \begin{code}{} |
| 385 | 384 | History>>goBackward |
| 386 | | self canGoBackward ifFalse: [self error: 'Already on the first element']. |
| 385 | self canGoBackward ifFalse: [self error: 'Ja estamos no primeiro elemento']. |
| 387 | 386 | ^ stream back |
| 388 | 387 | |
| 389 | 388 | History>>goForward |
| 390 | | self canGoForward ifFalse: [self error: 'Already on the last element']. |
| 389 | self canGoForward ifFalse: [self error: 'Ja estamos no ultimo elemento']. |
| 391 | 390 | ^ stream next |
| 392 | 391 | \end{code} |
| 393 | 392 | |
| 394 | | Until then, the code was pretty straightforward. Now, we have to deal |
| 395 | | with the \ct{goTo:} method which should be activated when the user |
| 396 | | clicks on a link. A possible solution is: |
| 393 | Até aqui, o código é bem simples. Agora, nós precisamos lidar com o método \ct{goTo:} que deve ser ativado quando o usuário clica em um link. Uma possível solução é: |
| 397 | 394 | |
| 398 | 395 | \begin{code}{} |
| 399 | 396 | History>>goTo: aPage |
| 400 | 397 | stream nextPut: aPage. |
| 401 | 398 | \end{code} |
| 402 | 399 | |
| 403 | | This version is incomplete however. This is because when the user |
| 404 | | clicks on the link, there should be no more future pages to go to, |
| 405 | | \ie the forward button must be deactivated. To do this, the simplest |
| 406 | | solution is to write \ct{nil} just after to indicate the history end: |
| 400 | Esta versão está incompleta, entretanto. Isso porque quando o usuário clicar em um link, não deve mais haver páginas a se visitar, \ie o botão ``avançar'' deve ser desabilitado. Para fazer isso, a solução mais simples é escrever \ct{nil} em seguida para indicar o fim do histórico: |
| 407 | 401 | |
| 408 | 402 | \begin{code}{} |
| 409 | 403 | History>>goTo: anObject |
| … | … | |
| 406 | 406 | stream back. |
| 407 | 407 | \end{code} |
| 408 | 408 | |
| 409 | | Now, only methods \ct{canGoBackward} and \ct{canGoForward} have to be |
| 410 | | implemented. |
| 409 | Agora, os métodos \ct{canGoBackward} e \ct{canGoForward} precisam ser implementados. |
| 411 | 410 | |
| 412 | | A stream is always positioned between two elements. To go backward, |
| 413 | | there must be two pages before the current position: one page is the |
| 414 | | current page, and the other one is the page we want to go to. |
| 411 | Um fluxo é sempre posicionado entre dois elementos. Para voltar, devem existir duas páginas anteriores à posição atual: uma página é a página atual, e a outra página é a página que queremos mostrar. |
| 415 | 412 | |
| 416 | 413 | \begin{code}{} |
| 417 | 414 | History>>canGoBackward |
| … | … | |
| 418 | 418 | ^ stream atEnd not and: [stream peek notNil] |
| 419 | 419 | \end{code} |
| 420 | 420 | |
| 421 | | Let us add a method to peek at the contents of the stream: |
| 421 | Vamos adicionar um método para olhar o conteúdo do fluxo: |
| 422 | 422 | \begin{code}{} |
| 423 | 423 | History>>contents |
| 424 | 424 | ^ stream contents |
| 425 | 425 | \end{code} |
| 426 | 426 | |
| 427 | | And the history works as advertised: |
| 427 | E o histórico funciona como prometido: |
| 428 | 428 | \begin{code}{} |
| 429 | 429 | History new |
| 430 | 430 | goTo: #page1; |
| … | … | |
| 437 | 437 | \end{code} |
| 438 | 438 | |
| 439 | 439 | %============================================================= |
| 440 | | \section{Using streams for file access} |
| 440 | \section{Usando fluxos para acessar arquivos} |
| 441 | 441 | |
| 442 | 442 | You have already seen how to stream over collections of elements. It's |
| 443 | 443 | also possible to stream over files on your hard disk. |
| toggle raw diff |
--- a/PortugueseBook/Streams/Streams.tex
+++ b/PortugueseBook/Streams/Streams.tex
@@ -39,7 +39,7 @@ Fluxos podem ser facilmente convertidos para coleções e vice-versa.
\section{Duas sequências de elementos}
Uma boa metáfora para entender um fluxo é a seguinte: Um fluxo pode ser representada como duas sequências de elementos: a sequência de elementos visitados e a sequência de elementos a visitar. O fluxo é posicionado entre as duas sequências. Entender este modelo é importante uma vez que todos as operações de fluxo em \st dependem dele.
Por esta razão, a maioria das classes de \clsind{Fluxo} são subclasses de \clsind{PositionableStream}.
-\figref{_abcde} apresenta um fluxo que contém cinco caracteres. Este fluxo está na sua posição original, \ie não há elementos já visitados. Você pode voltar a esta posição usando a mensagem \mthind{PositionableStream}{reset}.
+A \figref{_abcde} apresenta um fluxo que contém cinco caracteres. Este fluxo está na sua posição original, portanto a lista de elementos já visitados está vazia. Você pode voltar a esta posição usando a mensagem \mthind{PositionableStream}{reset}.
\begin{figure}[ht]
\centerline{\includegraphics[scale=0.5]{_abcdeStef}}
@@ -48,7 +48,7 @@ Por esta razão, a maioria das classes de \clsind{Fluxo} são subclasses de \cls
\vspace{.2in}
\end{figure}
-A leitura de um elemento conceitualmente significa remover o primeiro elemento da sequência de elementos a visitar e colocá-lo na sequência de elementos visitados. Após ter lido um elemento usando a mensagem \ct{next}, o estado do seu fluxo fica semelhante ao mostrado na \figref{a_bcde}.
+A leitura de um elemento conceitualmente significa remover o primeiro elemento da sequência de elementos a visitar e colocá-lo na sequência de elementos visitados. Após ter lido um elemento usando a mensagem \ct{next}, o estado do fluxo fica semelhante ao mostrado na \figref{a_bcde}.
\begin{figure}[ht]
\centerline{\includegraphics[scale=0.5]{a_bcdeStef}}
@@ -100,7 +100,7 @@ w := WriteStream on: (OrderedCollection new: 20).
w nextPut: 12. --> resulta numa excecao
\end{code}
-Fluxos não são apenas direcionado a coleções, eles podem ser usados em arquivos ou sockets também. O exemplo a seguir cria um arquivo chamado \ct{test.txt}, escreve duas strings separadas por uma quebra de linha, e fecha o arquivo.
+Fluxos não são apenas direcionado a coleções, eles também podem ser usados em arquivos ou sockets. O exemplo a seguir cria um arquivo chamado \ct{test.txt}, escreve duas strings separadas por uma quebra de linha, e fecha o arquivo.
\needlines{3}
\begin{code}{}
@@ -113,7 +113,7 @@ StandardFileStream
\end{code}
\cmindex{FileStream class}{fileNamed:do:}
-As seções a seguir apresentam tais protocolos em mais detalhes.
+As seções a seguir apresentam tais protocolos em detalhes.
%=============================================================
\section{Criando fluxos a partir de coleções}
@@ -123,7 +123,7 @@ Fluxos são muito úteis quando trabalhamos com coleções de elementos, podendo
%-----------------------------------------------------------------
\subsection{Lendo coleções}
-Esta seção apresenta os recursos usados para a leitura de coleções. Ao usar um fluxo para ler uma coleção, você recebe um ponteiro para a coleção. Este ponteiro irá se mover para frente conforme a leitura é feita, e você pode posicionar este ponteiro onde desejar. A classe \clsindmain{ReadStream} deve ser usada par ler elementos de coleções.
+Esta seção apresenta os recursos usados para a leitura de coleções. Ao usar um fluxo para ler uma coleção, você recebe um ponteiro para a coleção. Este ponteiro irá se mover para frente conforme a leitura é feita, e você pode posicionar este ponteiro onde desejar. A classe \clsindmain{ReadStream} deve ser usada para fazer a leitura dos elementos.
Os métodos \mthind{ReadStream}{next} e \mthind{ReadStream}{next:} são usados para obter um ou mais elementos da coleção.
@@ -231,27 +231,24 @@ result. --> an OrderedCollection(1 1 2 3 4 4 5 9 10 11 12 13 13 14 15)
%-----------------------------------------------------------------
\subsection{Escrevendo em coleções}
-Nós acabamos de ver como iterar nos elementos de uma coleção usando \ct{ReadStream}. Agora nós iremos aprender como criar coleções usando \clsindmain{WriteStream}{}s.
+Nós acabamos de ver como iterar nos elementos de uma coleção usando \ct{ReadStream}. Agora nós iremos aprender como criar coleções usando a classe \clsindmain{WriteStream}{}.
-\ct{WriteStream}s are useful for appending a lot of data to a collection at various locations. They are often used to construct strings that are based on static and dynamic parts as in this example:
+\ct{WriteStream}s são úteis para incluir dados em vários pontos numa coleção. Esses objetos são frequentemente usados para construir strings baseadas em partes estáticas e dinâmicas, como no exemplo a seguir:
-\begin{code}{NB: can't be tested due to the changing number of classes}
+\begin{code}{NB: não pode ser testado em razão do número variável de classes.}
stream := String new writeStream.
stream
- nextPutAll: 'This Smalltalk image contains: ';
+ nextPutAll: 'Esta imagem Smalltalk contem: ';
print: Smalltalk allClasses size;
nextPutAll: ' classes.';
cr;
- nextPutAll: 'This is really a lot.'.
+ nextPutAll: 'Muita coisa!'.
-stream contents. --> 'This Smalltalk image contains: 2322 classes.
-This is really a lot.'
+stream contents. --> 'Esta imagem Smalltalk contem: 2322 classes.
+Muita coisa!'
\end{code}
-This technique is used in the different implementations of the method
-\ct{printOn:} for example. There is a simpler and more efficient way
-of creating streams if you are only interested in the content of the
-stream:
+Esta técnica é usada em diferentes implementações do método \ct{printOn:}, por exemplo. Existe uma forma mais simples e eficiente de criar fluxos se você está interessado apenas no seu conteúdo:
\begin{code}{@TEST |string|}
string := String streamContents:
@@ -267,33 +264,23 @@ string := String streamContents:
string. --> '#(1 2 3) size = 3'
\end{code}
-The method \mthind{SequenceableCollection class}{streamContents:} \label{sec:streamContents} creates a collection and a stream on
-that collection for you. It then executes the block you gave passing
-the stream as a parameter. When the block ends, \ct{streamContents:}
-returns the content of the collection.
+O método \mthind{SequenceableCollection class}{streamContents:} \label{sec:streamContents} cria uma coleção e um fluxo para essa coleção. Ele então executa o bloco que foi passado como parâmetro. Quando o bloco termina, o método \ct{streamContents:} retorna o conteúdo da coleção.
-The following \ct{WriteStream} methods are especially useful in this context:
+O método \ct{WriteStream} a seguir é especialmente útil neste contexto:
\begin{description}
-\item[\lct{nextPut:}] adds the parameter to the stream;
-\item[\lct{nextPutAll:}] adds each element of the collection, passed as a
- parameter, to the stream;
-\item[\lct{print:}] adds the textual representation of the parameter to the
- stream.
+\item[\lct{nextPut:}] adiciona o parâmetro ao fluxo;
+\item[\lct{nextPutAll:}] adiciona ao fluxo cada elemento da coleção passada como parâmetro;
+\item[\lct{print:}] adiciona ao fluxo a representação textual do parâmetro;
\cmindex{Stream}{print:}
\end{description}
-There are also methods useful for printing different kinds of characters to
-the stream like \mthind{WriteStream}{space}, \mthind{WriteStream}{tab} and
-\mthind{WriteStream}{cr} (carriage return). Another useful
-method is \mthind{WriteStream}{ensureASpace} which ensures that the last character
-in the stream is a space; if the last character isn't a space it adds one.
+Ainda existem métodos úteis para imprimir diferentes tipos de caracteres ao fluxo como \mthind{WriteStream}{space}, \mthind{WriteStream}{tab} e \mthind{WriteStream}{cr} (\foreign{carriage return}). Outro método útil é \mthind{WriteStream}{ensureASpace}, que garante que o último caractere do fluxo seja um espaço; se não for, um espaço é adicionado.
-\paragraph{About Concatenation.}
-Using \mthind{WriteStream}{nextPut:} and \mthind{WriteStream}{nextPutAll:} on a \ct{WriteStream} is often the best way to
-concatenate characters. Using the comma concatenation operator (\ct{,}) is far
-less efficient:
-\index{Collection!comma operator}
+\paragraph{Sobre Concatenação.}
+Usando os métodos \mthind{WriteStream}{nextPut:} e \mthind{WriteStream}{nextPutAll:} num \ct{WriteStream} é, na maioria das vezes, a melhor forma de se concatenar caracteres. Usar o operador de concatenação (\ct{,}) é muito menos eficiente:
+
+\index{Coleção!operador vírgula}
\begin{code}{}
[| temp |
@@ -308,15 +295,9 @@ less efficient:
temp contents] timeToRun --> 1262 "(milliseconds)"
\end{code}
-The reason that using a stream can be much more efficient is that
-comma creates a new string containing
-the concatenation of the receiver and the argument, so it must copy both of them.
-When you repeatedly concatenate onto the same receiver, it gets longer and longer each time,
-so that the number of characters that must be copied goes up exponentially.
-This also creates a lot of garbage, which must be collected. Using
-a stream instead of string concatenation is a well-known optimization.
+A razão de um fluxo ser muito mais eficiente é que a vírgula cria uma nova string contendo a concatenação do objeto receptor e do argumento, copiando então ambos os objetos. Quando você concatena repetidamente ao mesmo receptor, ele fica maior a cada vez, de modo que o número de caracteres que precisam ser copiados aumenta exponencialmente. Isso também cria muito lixo, que deve ser coletado. Usar um fluxo no lugar da concatenação de strings é uma otimização muito conhecida.
\lr{About Concatenation. This is not true for real world examples (the example benchmark is unrealistic). Most of the time concatenation is simpler, cleaner and much faster, for example when being used on a small number of longer strings. (p. 257)}
-In fact, you can use \mthind{SequenceableCollection class}{streamContents:} (mentioned on page \pageref{sec:streamContents}) to help you do this:
+Na verdade, você pode usar \mthind{SequenceableCollection class}{streamContents:} (mencionado na página \pageref{sec:streamContents}) para te ajudar a fazer isso:
\begin{code}{}
String streamContents: [ :tempStream |
@@ -325,65 +306,62 @@ String streamContents: [ :tempStream |
\end{code}
%-----------------------------------------------------------------
-\subsection{Reading and writing at the same time}
+\subsection{Lendo e escrevendo ao mesmo tempo}
-It's possible to use a stream to access a collection for reading and
-writing at the same time.
-Imagine you want to create an \ct{History} class which will manage
-backward and forward buttons in a web browser.
-A history would react as in figures from \ref{fig:emptyStream} to
-\ref{fig:page4}.
+É possível usar um fluxo para acessar uma coleção para leitura e escrita ao mesmo tempo.
+Imagine que você queira criar uma classe \ct{History} que irá gerenciar os botões ``voltar'' e ``avançar'' em um navegador web.
+O histórico reagiria de acordo com as figuras \ref{fig:emptyStream} a \ref{fig:page4}.
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{emptyStef}}
-\caption{A new history is empty. Nothing is displayed in the web browser.}
+\caption{O novo histórico está vazio. Nada é mostrado no navegador web.}
\label{fig:emptyStream}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page1Stef}}
-\caption{The user opens to page 1.}
+\caption{O usuário abre a página 1.}
\label{fig:page1}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page2Stef}}
-\caption{The user clicks on a link to page 2.}
+\caption{O usuário clica em um link para a página 2.}
\label{fig:page2}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page3Stef}}
-\caption{The user clicks on a link to page 3.}
+\caption{O usuário clica em um link para a página 3.}
\label{fig:page3}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page2_Stef}}
-\caption{The user clicks on the back button. He is now viewing page 2 again.}
+\caption{O usuário clica no botão ``voltar''. Ele está agora vendo a página 2 novamente.}
\label{fig:page2_}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page1_Stef}}
-\caption{The user clicks again the back button. Page 1 is now displayed.}
+\caption{O usuário clica novamente no botão ``voltar''. A página 1 está agora sendo mostrada.}
\label{fig:page1_}
\vspace{.2in}
\end{figure}
\begin{figure}[!ht]
\centerline{\includegraphics[scale=0.5]{page4Stef}}
-\caption{From page 1, the user clicks on a link to page 4. The history forgets pages 2 and 3.}
+\caption{Da página 1, o usuário clica em um link para a página 4. O histórico esquece das páginas 2 e 3.}
\label{fig:page4}
\vspace{.2in}
\end{figure}
-This behaviour can be implemented using a \clsind{ReadWriteStream}.
+Este comportamento pode ser implementado sando um \clsind{ReadWriteStream}.
\needlines{6}
\begin{code}{}
@@ -398,34 +376,28 @@ History>>initialize
stream := ReadWriteStream on: Array new.
\end{code}
-Nothing really difficult here, we define a new class which contains a
-stream. The stream is created during the \ct{initialize} method.
+Nada de muito complicado aqui, apenas definimos uma nova classe que contém um fluxo. O fluxo é criado no método \ct{initialize}.
-We need methods to go backward and forward:
+Nós precisamos de métodos para voltar e avançar:
\begin{code}{}
History>>goBackward
- self canGoBackward ifFalse: [self error: 'Already on the first element'].
+ self canGoBackward ifFalse: [self error: 'Ja estamos no primeiro elemento'].
^ stream back
History>>goForward
- self canGoForward ifFalse: [self error: 'Already on the last element'].
+ self canGoForward ifFalse: [self error: 'Ja estamos no ultimo elemento'].
^ stream next
\end{code}
-Until then, the code was pretty straightforward. Now, we have to deal
-with the \ct{goTo:} method which should be activated when the user
-clicks on a link. A possible solution is:
+Até aqui, o código é bem simples. Agora, nós precisamos lidar com o método \ct{goTo:} que deve ser ativado quando o usuário clica em um link. Uma possível solução é:
\begin{code}{}
History>>goTo: aPage
stream nextPut: aPage.
\end{code}
-This version is incomplete however. This is because when the user
-clicks on the link, there should be no more future pages to go to,
-\ie the forward button must be deactivated. To do this, the simplest
-solution is to write \ct{nil} just after to indicate the history end:
+Esta versão está incompleta, entretanto. Isso porque quando o usuário clicar em um link, não deve mais haver páginas a se visitar, \ie o botão ``avançar'' deve ser desabilitado. Para fazer isso, a solução mais simples é escrever \ct{nil} em seguida para indicar o fim do histórico:
\begin{code}{}
History>>goTo: anObject
@@ -434,12 +406,9 @@ History>>goTo: anObject
stream back.
\end{code}
-Now, only methods \ct{canGoBackward} and \ct{canGoForward} have to be
-implemented.
+Agora, os métodos \ct{canGoBackward} e \ct{canGoForward} precisam ser implementados.
-A stream is always positioned between two elements. To go backward,
-there must be two pages before the current position: one page is the
-current page, and the other one is the page we want to go to.
+Um fluxo é sempre posicionado entre dois elementos. Para voltar, devem existir duas páginas anteriores à posição atual: uma página é a página atual, e a outra página é a página que queremos mostrar.
\begin{code}{}
History>>canGoBackward
@@ -449,13 +418,13 @@ History>>canGoForward
^ stream atEnd not and: [stream peek notNil]
\end{code}
-Let us add a method to peek at the contents of the stream:
+Vamos adicionar um método para olhar o conteúdo do fluxo:
\begin{code}{}
History>>contents
^ stream contents
\end{code}
-And the history works as advertised:
+E o histórico funciona como prometido:
\begin{code}{}
History new
goTo: #page1;
@@ -468,7 +437,7 @@ History new
\end{code}
%=============================================================
-\section{Using streams for file access}
+\section{Usando fluxos para acessar arquivos}
You have already seen how to stream over collections of elements. It's
also possible to stream over files on your hard disk. |