Rust provides memory safety without garbage collection through its ownership and borrowing model that is checked at compile time. Ownership rules ensure that references to resources like vectors remain valid by moving the vector when it is passed to a function. Borrowing allows immutable or mutable references to a resource, but not both at the same time, avoiding data races. Rust achieves performance comparable to C++ through its zero-cost abstractions and moves semantics that avoid unnecessary data copying.
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
Rust is a young programming language developed by Mozilla with the open source community support. According to a survey of StackOverflow, in 2016 was the most loved among developers language! The goal of Rust is to combine control and performances, that is, operate at low level with high-level constructs. The actual applications vary from operating system to web development. Rust natively includes tools for Agile development, such as dependency management, testing and much more. The gap with other popular languages is filling up quickly thanks to the community, very active and fantastic :)
In this introductory presentation we will discuss the characteristics that make Rust unique, including the concepts of Ownership, Borrowing, and Lifetimes.
These slide has be presented for a talk in BIC Lazio Casilina, that has been also the first meetup of Rust Rome!
Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.
Rust is a systems programming language focused on three goals: safety, speed, and concurrency. It is open source and provides top-tier performance like C/C++ while ensuring memory safety and preventing issues like memory leaks through its ownership and borrowing model that is checked at compile time. Rust also supports features like enums, pattern matching, generics, traits, and has a built-in test system to help ensure correctness.
This document discusses why Rust is a useful programming language. It provides an introduction to Rust, highlighting its memory safety features, ownership and borrowing system, and functional programming aspects like iterators and closures. Examples are given to demonstrate how Rust prevents common bugs like dangling pointers and iterator invalidation. The talk also covers Rust's type system, enums, patterns matching, and its Cargo package manager.
This document provides an introduction to the Rust programming language. It describes that Rust was developed by Mozilla Research beginning in 2009 to combine the type safety of Haskell, concurrency of Erlang, and speed of C++. Rust reached version 1.0 in 2015 and is a generic, multiparadigm systems programming language that runs on platforms including ARM, Apple, Linux, Windows and embedded devices. It emphasizes security, performance and fine-grained memory safety without garbage collection.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/
The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
Rust is a young programming language developed by Mozilla with the open source community support. According to a survey of StackOverflow, in 2016 was the most loved among developers language! The goal of Rust is to combine control and performances, that is, operate at low level with high-level constructs. The actual applications vary from operating system to web development. Rust natively includes tools for Agile development, such as dependency management, testing and much more. The gap with other popular languages is filling up quickly thanks to the community, very active and fantastic :)
In this introductory presentation we will discuss the characteristics that make Rust unique, including the concepts of Ownership, Borrowing, and Lifetimes.
These slide has be presented for a talk in BIC Lazio Casilina, that has been also the first meetup of Rust Rome!
Brief overview of the Rust system programming language. Provides a concise introduction of its basic features, with an emphasis on its memory safety features (ownership, moves, borrowing) and programming style with generic functions, structures, and traits.
Rust is a systems programming language focused on three goals: safety, speed, and concurrency. It is open source and provides top-tier performance like C/C++ while ensuring memory safety and preventing issues like memory leaks through its ownership and borrowing model that is checked at compile time. Rust also supports features like enums, pattern matching, generics, traits, and has a built-in test system to help ensure correctness.
This document discusses why Rust is a useful programming language. It provides an introduction to Rust, highlighting its memory safety features, ownership and borrowing system, and functional programming aspects like iterators and closures. Examples are given to demonstrate how Rust prevents common bugs like dangling pointers and iterator invalidation. The talk also covers Rust's type system, enums, patterns matching, and its Cargo package manager.
This document provides an introduction to the Rust programming language. It describes that Rust was developed by Mozilla Research beginning in 2009 to combine the type safety of Haskell, concurrency of Erlang, and speed of C++. Rust reached version 1.0 in 2015 and is a generic, multiparadigm systems programming language that runs on platforms including ARM, Apple, Linux, Windows and embedded devices. It emphasizes security, performance and fine-grained memory safety without garbage collection.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/
The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
The document discusses code generation on the JVM using various tools and frameworks. It provides an overview of Lombok for generating Java boilerplate code, Groovy AST transformations, CodeNarc for static analysis, and Spock, GContracts, and Groovy++ for framework-oriented code generation. It also discusses generating code at compile time using abstract syntax trees.
The document discusses abstract syntax tree (AST) transformations in Groovy and Java. It covers several tools and techniques for AST transformations including Lombok, Groovy, CodeNarc, IntelliJ IDEA, Mirah macros, and how they allow generating code, performing static analysis, and rewriting code at compile time through analyzing and modifying the AST. The key topics are how these tools work by compiling code to an AST, analyzing and modifying the AST nodes, and sometimes generating source code from the transformed AST.
The document discusses the major changes and improvements in Swift 3.0, which is expected to be released in late 2016. It outlines proposals like removing var from function parameters, distinguishing single-tuple from multiple-argument function types, and applying API design guidelines to the standard library. It also covers changes to the Foundation framework like dropping the NS prefix and making value types non-mutable by default. The goal is to enhance the Swift language, development experience, and source compatibility between versions.
This document summarizes Hamlet D'Arcy's presentation on AST transformations using tools like Lombok, Groovy, CodeNarc, and Mirah. It discusses how these tools allow manipulating abstract syntax trees to add functionality like automatic property generation, static analysis, and embedded domain-specific languages. Local AST transformations are performed without changing bytecode or requiring new semantics. Type checking can also be added through transformations. Mirah compiles to pure Java classes without additional syntax.
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
Blocks allow passing code as a parameter or return value from functions. They capture the context in which they are defined. Grand Central Dispatch (GCD) simplifies concurrent programming using dispatch queues, which can execute blocks asynchronously or synchronously, and dispatch sources which attach blocks to system events. Dispatch groups and semaphores help coordinate work across dispatch queues.
Building native Android applications with Mirah and PindahNick Plante
Mirah is a Ruby-like language that compiles to Java bytecode, allowing Ruby developers to write Android apps without using Java. The document introduces Mirah and Pindah, a framework that makes it easier to develop Android apps in Mirah. It provides an example "Up or Down?" app that checks the status of websites and displays results. While Mirah offers a more Ruby-like syntax, it is still immature and tooling support needs improvement, making large Android app development challenging.
Groovy is a dynamic language for the Java Virtual Machine that aims to bring dynamic capabilities like Python and Ruby to Java developers. It has many features inspired by dynamic languages like closures, duck typing and metaprogramming, but also maintains compatibility with Java by having a Java-like syntax and the ability to interoperate with Java code. Groovy code can either be run directly from scripts or compiled into Java bytecode to be used within Java applications.
The document discusses code generation and abstract syntax tree (AST) transformations. It provides an overview of Project Lombok, a Java library that generates boilerplate code through annotation processing and AST transformations. It also discusses how to analyze and transform code by visiting and rewriting AST nodes, giving examples of checking for null checks and instanceof expressions.
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
Slides of Eclipse Modeling Day in New York and Toronto http://wiki.eclipse.org/Eclipse_Modeling_Day
Motivation of specific tools with apple corer analogy, Example of domain-specific language (chess notation), introduction to Xtext with demo plus outlook
This document provides an introduction and overview of the Kotlin programming language. It begins with an agenda and quote about Kotlin being a good choice for Spring applications. The remainder of the document covers what Kotlin is, its main features like type inference, functional programming support, interoperability with Java, and language concepts like properties, classes, inheritance, interfaces, functions, collections and more. Code examples are provided to illustrate many of the language features. Resources for learning more about Kotlin are listed at the end.
Sven and I are going to classify Xtext compared to other concepts and frameworks and demonstrate its capabilities with a refined version of an example I presented in London the week before. After that we discuss the versatile possibilities for extending and customizing the framework and finish with an exciting outlook.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
The document discusses hacking the Go compiler by modifying various phases. The lexer phase scans source code and tokenizes it. The parser phase builds an abstract syntax tree from the tokens by making parser calls. Examples are given of modifying the lexer to accept emoji identifiers and adding a new operator by extending the parser phase. Helpful debugging functions are also outlined.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
The document summarizes Carlo Sciolla's blog post about using Clojure to interact with the Alfresco content repository. It shows how to write a function in Clojure to loop through all nodes in a repository and print their names, and compares the Clojure code to the equivalent Java code. It also discusses some Clojure concepts like immutable data structures, macros, and sequence processing that make the Clojure implementation more concise and functional than the object-oriented Java code.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Rust is a systems programming language developed by Mozilla that provides memory safety without garbage collection. It uses concepts of ownership and borrowing to ensure memory safety issues like use-after-free do not occur. Rust offers zero-cost abstractions meaning abstraction mechanisms like generics have little to no performance overhead. It allows high levels of concurrency but requires memory references be valid during their entire lifetime.
This talk exposes the reasons what Servo is and why it is necessary, its current status, future plans and details on the Rust programming language, which has a symbiotic relationship with Servo.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
The document discusses code generation on the JVM using various tools and frameworks. It provides an overview of Lombok for generating Java boilerplate code, Groovy AST transformations, CodeNarc for static analysis, and Spock, GContracts, and Groovy++ for framework-oriented code generation. It also discusses generating code at compile time using abstract syntax trees.
The document discusses abstract syntax tree (AST) transformations in Groovy and Java. It covers several tools and techniques for AST transformations including Lombok, Groovy, CodeNarc, IntelliJ IDEA, Mirah macros, and how they allow generating code, performing static analysis, and rewriting code at compile time through analyzing and modifying the AST. The key topics are how these tools work by compiling code to an AST, analyzing and modifying the AST nodes, and sometimes generating source code from the transformed AST.
The document discusses the major changes and improvements in Swift 3.0, which is expected to be released in late 2016. It outlines proposals like removing var from function parameters, distinguishing single-tuple from multiple-argument function types, and applying API design guidelines to the standard library. It also covers changes to the Foundation framework like dropping the NS prefix and making value types non-mutable by default. The goal is to enhance the Swift language, development experience, and source compatibility between versions.
This document summarizes Hamlet D'Arcy's presentation on AST transformations using tools like Lombok, Groovy, CodeNarc, and Mirah. It discusses how these tools allow manipulating abstract syntax trees to add functionality like automatic property generation, static analysis, and embedded domain-specific languages. Local AST transformations are performed without changing bytecode or requiring new semantics. Type checking can also be added through transformations. Mirah compiles to pure Java classes without additional syntax.
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
Blocks allow passing code as a parameter or return value from functions. They capture the context in which they are defined. Grand Central Dispatch (GCD) simplifies concurrent programming using dispatch queues, which can execute blocks asynchronously or synchronously, and dispatch sources which attach blocks to system events. Dispatch groups and semaphores help coordinate work across dispatch queues.
Building native Android applications with Mirah and PindahNick Plante
Mirah is a Ruby-like language that compiles to Java bytecode, allowing Ruby developers to write Android apps without using Java. The document introduces Mirah and Pindah, a framework that makes it easier to develop Android apps in Mirah. It provides an example "Up or Down?" app that checks the status of websites and displays results. While Mirah offers a more Ruby-like syntax, it is still immature and tooling support needs improvement, making large Android app development challenging.
Groovy is a dynamic language for the Java Virtual Machine that aims to bring dynamic capabilities like Python and Ruby to Java developers. It has many features inspired by dynamic languages like closures, duck typing and metaprogramming, but also maintains compatibility with Java by having a Java-like syntax and the ability to interoperate with Java code. Groovy code can either be run directly from scripts or compiled into Java bytecode to be used within Java applications.
The document discusses code generation and abstract syntax tree (AST) transformations. It provides an overview of Project Lombok, a Java library that generates boilerplate code through annotation processing and AST transformations. It also discusses how to analyze and transform code by visiting and rewriting AST nodes, giving examples of checking for null checks and instanceof expressions.
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
Slides of Eclipse Modeling Day in New York and Toronto http://wiki.eclipse.org/Eclipse_Modeling_Day
Motivation of specific tools with apple corer analogy, Example of domain-specific language (chess notation), introduction to Xtext with demo plus outlook
This document provides an introduction and overview of the Kotlin programming language. It begins with an agenda and quote about Kotlin being a good choice for Spring applications. The remainder of the document covers what Kotlin is, its main features like type inference, functional programming support, interoperability with Java, and language concepts like properties, classes, inheritance, interfaces, functions, collections and more. Code examples are provided to illustrate many of the language features. Resources for learning more about Kotlin are listed at the end.
Sven and I are going to classify Xtext compared to other concepts and frameworks and demonstrate its capabilities with a refined version of an example I presented in London the week before. After that we discuss the versatile possibilities for extending and customizing the framework and finish with an exciting outlook.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
The document discusses hacking the Go compiler by modifying various phases. The lexer phase scans source code and tokenizes it. The parser phase builds an abstract syntax tree from the tokens by making parser calls. Examples are given of modifying the lexer to accept emoji identifiers and adding a new operator by extending the parser phase. Helpful debugging functions are also outlined.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
The document summarizes Carlo Sciolla's blog post about using Clojure to interact with the Alfresco content repository. It shows how to write a function in Clojure to loop through all nodes in a repository and print their names, and compares the Clojure code to the equivalent Java code. It also discusses some Clojure concepts like immutable data structures, macros, and sequence processing that make the Clojure implementation more concise and functional than the object-oriented Java code.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Rust is a systems programming language developed by Mozilla that provides memory safety without garbage collection. It uses concepts of ownership and borrowing to ensure memory safety issues like use-after-free do not occur. Rust offers zero-cost abstractions meaning abstraction mechanisms like generics have little to no performance overhead. It allows high levels of concurrency but requires memory references be valid during their entire lifetime.
This talk exposes the reasons what Servo is and why it is necessary, its current status, future plans and details on the Rust programming language, which has a symbiotic relationship with Servo.
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOMEJulien Fitzpatrick
Learning to program in Ruby was super fun, but I kept hearing people talk about typed languages that are so-called "closer to the metal," like Rust. It seemed intimidating, but I was curious! I built a small, text-based adventure game in both Ruby and Rust, side-by-side, so I could see what the differences and similarities were. I learned a lot, and now I'm here to share it all with you!
This document discusses how to program FPGAs using free and open source software tools. It explains what an FPGA is and how it works, and walks through examples of using Verilog to program simple logic gates and circuits on an FPGA board. These include turning on an LED, implementing a NAND gate in hardware, and using the FPGA as an interactive input/output device. The document promotes the IceStorm toolchain for programming Lattice FPGA boards and outlines several other hardware description languages and frameworks. It concludes by discussing future developments that could expand the use of open source FPGA programming.
Rust is a new systems programming language designed for safety, concurrency, and speed. It uses a borrow checker to ensure memory safety and avoid use-after-free bugs, and enables safe concurrency through message passing and ownership rules. The Rust team has been redesigning and implementing the language over the past year based on lessons learned from writing the compiler in Rust. Their goals are to have a memory-safe, concurrent language that achieves performance comparable to C++. They plan to use Rust for the parallel engine of the Servo browser project.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
Performance Comparison of Mutex, RWLock and Atomic types in RustMitsunori Komatsu
This document compares the performance of Mutex, RWLock, and atomic types for concurrent access in Rust. It presents benchmark results from a Rust program that tests updating a shared variable with these different synchronization methods under varying read/write loads on Linux and macOS. The results show that RWLock performance degrades significantly with more writes, Mutex performance is consistent even with writes, and atomic types are always the fastest for a counter.
Type-Directed TDD in Rust: a case study using FizzBuzzFranklin Chen
An expressive static type system is one of the most joyful and powerful tools for prototyping, designing, and maintaining programs. In this performance-theatrical presentation, I will provide a taste of how to use types, in conjunction with tests, to drive iterative development of a particular program, the famous FizzBuzz problem. We will solve generalizations of this problem, changing and adding requirements, to illustrate the pleasures and benefits of "type thinking".
The Rust language will be used as the vehicle for this demonstration, but the techniques apply immediately to any industrial-strength statically typed language, such as Scala, Haskell, OCaml, F#, and most recently, Swift.
RUSTing is not a tutorial on the Rust programming language.
I decided to create the RUSTing series as a way to document and share programming idioms and techniques.
From time to time I’ll draw parallels with Haskell and Scala, having some familiarity with one of them is useful but not indispensable.
- InfoQ is a news and community site for software developers with 750,000 unique visitors per month publishing content in 4 languages.
- It posts content from QCon conferences including news, articles, presentations, interviews and books to empower software development through spreading knowledge and innovation.
- QCon conferences are practitioner-driven and designed for influencers of change and innovation, connecting them and catalyzing innovation, and have been attended by over 12,000 delegates since 2007 across 9 cities worldwide.
Lecture on shells in operating systems class, but mostly about teaching philosophy.
Notes: http://www.cs.virginia.edu/~evans/cs4414-fall2013/class5.html
What the &~#@<!? (Memory Management in Rust)David Evans
Operating Systems course lecture on memory management in Rust.
Browser design from 1990s (one process) to 2000s (one process per tag) to 2010s and beyond (enough processes to efficiently use machine resources to provide good user experience).
malloc, free, double-free vulnerabilities
Introduction to rust: a low-level language with high-level abstractionsyann_s
The document discusses the Rust programming language. It notes that Rust is a low-level language that provides high-level abstractions. It allows for high performance due to being compiled without a garbage collector or virtual machine, but also provides high-level features like types, type inference, pattern matching and functional programming. Rust aims to combine the performance of low-level languages with the safety and abstraction of high-level languages.
Видео доклада: https://www.youtube.com/watch?v=slnQBoxsHPU
Rust - системный язык программирования, который быстро исполняется, предотвращает почти все падения, и устраняет гонки по данным.
Как он этого достигает? Про это доклад.
Slides for my Embedded Rust talk at #Devoxx 2016.
Rust is a systems programming language that runs blazingly fast, prevents segfaults and runs on embedded IoT devices.
Rust — это современный, практический, быстрый и безопасный язык программирования. Некоторые говорят, что Rust — это как C++, если бы его писал человек, знающий Haskell.
Система типов Rust решает главную проблему C++ — небезопасность. C++ очень легко сделать ошибки, которые приведут к поломкам (например, use after free). Rust позволяет писать безопасный код, сохраняя при этом выразительность и околонулевые накладные расходы C++. В докладе будут подробно описаны механизмы языка, которые контролируют безопасность программы.
Хотя в данный момент Rust ещё не подходит для использования в продакшне, его всё равно стоит изучать. Во-первых, потому что это очень интересный подход к программированию, а во-вторых, потому что через несколько лет для разработки требовательных к ресурсам программ будет необходим именно Rust или другой похожий инструмент.
Rust is a systems programming language that offers performance comparable to C and C++ with memory safety and thread safety. It uses a borrow checker to enforce rules around ownership, borrowing, and lifetimes that prevent common bugs like use of dangling pointers and data races. Rust also supports features like generics, pattern matching, and idioms that improve productivity without sacrificing performance.
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовYandex
Последние 15 лет между разработчиками на Java и на C++ ведётся спор о том, какой язык программирования хуже — Java или C++. Программы на C++ глючат, падают, и в них утекает память. Программы на Java тормозят и требуют слишком много памяти.
Rust — новый язык программирования, разрабатываемый компанией Mozilla — решает проблемы Java и C++: программы, написанные на Rust, одновременно быстрые и безопасные. Rust является таким же низкоуровневым, close-to-metal языком программирования, как и C++, однако в язык встроены конструкции, позволяющие на этапе компиляции доказывать, что в программе не случится обращения к неинициализированной памяти (механизм borrowed pointers). Большая часть моего рассказа будет посвящена описанию этого механизма.
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This reference will take you through simple and practical approach while learning C++ Programming language.
This document provides an introduction to the Rust programming language. It discusses Rust's memory safety features, variable bindings, functions, control flow statements like if/else and loops, data types like tuples and vectors, and borrowing rules. It also covers Rust concepts like ownership, slices, pattern matching, and destructuring. Examples are provided to demonstrate various Rust language features.
Game Design and Development Workshop Day 1Troy Miles
This course teaches you how to build awesome video games using Cocos2Dx. Cocos2Dx is a feature packed, free game development engine. It is cross platform, high performance, and supports three languages: C++, Lua and JavaScript. With it, you can write games for iOS, Android, Windows, Mac, and the Web. It is nothing short of amazing and this course teaches you how to use it. We will program Cocos2Dx in JavaScript, but this is not a programming class. If you don't know how to write code in JavaScript or some other curly brace language, this is not the course for you. For those whose JavaScript is rusty, we will do quick language overview. Don't let the JavaScript part fool you. Cocos2Dx is built from highly optimized C++ and OpenGL, JavaScript is used for game logic, not graphics. Our games will run at a super fast, 60 frames a second.
The document provides information about Flutter Forward, an annual event hosted by Google's Flutter team that brings together developers, designers, and enthusiasts to learn about Flutter. It includes details about the 2023 Flutter Forward event such as the website and livestream link. Information about Flutter, its architecture, and Dart programming language is also presented.
The document provides an overview of several C++ concepts including basic syntax, compiling programs, argument passing, dynamic memory allocation, and object-oriented programming. It demonstrates simple C++ programs and functions. It discusses best practices like separating interface and implementation using header files. It also introduces C++ standard library features like vectors and the importance of avoiding unnecessary copying.
ES6 is Nigh is a presentation on the future of JavaScript. It discusses the history of JavaScript and why ES6 is important for advancing the language. The presentation outlines many new features being added in ES6, such as arrow functions, classes, modules, template strings, symbols, generators, and proxies. It emphasizes that ES6 is purely additive and introduces these features without breaking backwards compatibility.
A talk about how Javascript developers can make better and less error prone code by adopting two practices: using type-checkers to validate types during the development process, using Flowtype as an example; and by applying some common clean code practices to make their code more readable.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
The document discusses arrays, strings, and functions in C programming. It begins by explaining how to initialize and access 2D arrays, including examples of declaring and initializing a 2D integer array and adding elements of two 2D arrays. It also covers initializing and accessing multidimensional arrays. The document then discusses string basics like declaration and initialization of character arrays that represent strings. It explains various string functions like strlen(), strcat(), strcmp(). Finally, it covers functions in C including declaration, definition, call by value vs reference, and passing arrays to functions.
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
Charlie Miller and Vincenzo Iozzo presented techniques for post-exploitation on the iPhone 2 including:
1. Running arbitrary shellcode by overwriting memory protections and calling vm_protect to mark pages as read/write/executable.
2. Loading an unsigned dynamic library called Meterpreter by mapping it over an existing signed library, patching dyld to ignore code signing, and forcing unloaded of linked libraries.
3. Adding new functionality to Meterpreter, such as a module to vibrate and play a sound on the iPhone, demonstrating how payloads can be extended once loaded into memory.
Rust is a systems programming language that was first initiated in 2006 and reached 1.0 in 2015. It is used by Mozilla in Firefox and focuses on memory safety without garbage collection through features like ownership and borrowing. The document provides an introduction to Rust and covers topics like variables, functions, primitive types, if/loop control structures, ownership, references, and encourages readers to explore further topics in the Rust Book and Rust by Example.
This document provides an overview of programming basics including 2D and 3D arrays, nested loops, and classes. It discusses how to create and access multi-dimensional arrays, use nested loops to repeat operations, and define classes with methods and member variables. Examples are given for 2D and 3D arrays, nested loops that count iterations, and a class for flashing an LED with methods to define on and off times. Challenges are presented at the end involving nested loops, serial printing patterns, counting string occurrences, and creating a class to add integers that is then turned into a library.
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
In this session, we will present real life applications of compiler techniques helping kaChing achieve ultra confidence and power its incredible 5 minutes commit-to-production cycle [1]. We'll talk about idempotency analysis [2], dependency detection, on the fly optimisations, automatic memoization [3], type unification [4] and more! This talk is not suitable for the faint-hearted... If you want to dive deep, learn about advanced JVM topics, devoure bytecode and see first hand applications of theoretical computer science, join us.
[1] http://eng.kaching.com/2010/05/deployment-infrastructure-for.html
[2] http://en.wikipedia.org/wiki/Idempotence
[3] http://en.wikipedia.org/wiki/Memoization
[4] http://eng.kaching.com/2009/10/unifying-type-parameters-in-java.html
Rust is a systems programming language that provides memory safety without using a garbage collector. It achieves memory safety through rules of ownership, borrowing, and lifetimes that are checked at compile time. These rules prevent common memory bugs like memory leaks, dangling pointers, and use-after-free errors that are common in C and C++.
Groovy is a dynamic language for the Java Virtual Machine that simplifies programming through features like closures, properties, and built-in support for lists, maps, ranges, and regular expressions. The latest version 1.5 adds support for Java 5 features like annotations and generics to leverage frameworks that use them. Groovy can be integrated into applications through mechanisms like JSR-223, Spring, and Groovy's own GroovyClassLoader to externalize business rules, provide extension points, and customize applications.
OSX/Flashback
El sistema operativo Apple OS X, al igual que todos los sistemas operativos, puede convertirse en una víctima de software malicioso. Antes de la aparición de OSX/Flashback, hubo varios casos documentados de malware dirigido a OS X; pero hasta ahora, OSX/Flashback fue el que cobró la mayor cantidad de víctimas. En este artículo se describen las características técnicas más interesantes de la amenaza, en especial el método utilizado para espiar las comunicaciones de red y los algoritmos para la generación dinámica de nombres de dominio. También se incluye una línea de tiempo con los puntos más importantes del malware, cuyo ciclo de vida persistió durante tantos meses.
Similar to Rust Workshop - NITC FOSSMEET 2017 (20)
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
What is Augmented Reality Image Trackingpavan998932
Augmented Reality (AR) Image Tracking is a technology that enables AR applications to recognize and track images in the real world, overlaying digital content onto them. This enhances the user's interaction with their environment by providing additional information and interactive elements directly tied to physical images.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...kalichargn70th171
A dynamic process unfolds in the intricate realm of software development, dedicated to crafting and sustaining products that effortlessly address user needs. Amidst vital stages like market analysis and requirement assessments, the heart of software development lies in the meticulous creation and upkeep of source code. Code alterations are inherent, challenging code quality, particularly under stringent deadlines.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
4. Why is Rust so exciting?
Safe low-level systems programming
Memory safety without garbage collection
High-level abstractions (influenced by statically typed functional
programming languages like ML) without run-time overhead
Concurrency without data races
5. Why not just use C/C++?
The second big thing each student should learn is: How
can I avoid being burned by C’s numerous and severe
shortcomings? This is a development environment where
only the paranoid can survive.
http://blog.regehr.org/archives/1393
7. A bit of Rust history
Started by Graydon Hoare as a personal project in 2006
Mozilla foundation started sponsoring Rust in 2010
Rust 1.0 released in May, 2015
Regular six week release cycles
8. Core language features
Memory safety without garbage collection
Ownership
Move Semantics
Borrowing and lifetimes
Static Typing with Type Inference
Algebraic Data Types (Sum and Product types)
Exhaustive Pattern Matching
Trait-based generics
Iterators
Zero Cost Abstractions
Concurrency without data races
Efficient C bindings, minimal runtime
9. Structure of this workshop
Understanding the problems with C/C++
Understanding Ownership, Borrow, Move semantics and
Lifetimes
Other features (depending on availability of time)
19. Dangling Pointers
// a4.c
void fun2() { int m = 1; int n = 2; }
int* fun1() {
int *p; int q = 0;
p = &q; return p; // bug
}
int main() {
int *a, b; a = fun1();
*a = 10; fun2();
b = *a;
}
22. Heap allocation - malloc and free
// a7.c
#include <stdlib.h>
void fun()
{
char *c;
c = malloc(10*sizeof(char));
/* do some stuff here */
free(c);
}
int main()
{
fun();
}
23. Heap allocation - malloc and free
Figure 9: A stack location pointing to a heap location
24. Memory leaks
// a8.c
#include <stdlib.h>
void fun()
{
char *c;
c = malloc(10*sizeof(char));
/* do some stuff here */
}
int main()
{
fun(); // bug! memory leak.
}
25. Use-after-free
// a9.c
#include <stdlib.h>
void fun(char *t) {
/* do some stuff here */
free(t);
}
int main() {
char *c;
c = malloc(10 * sizeof(char));
fun(c);
c[0] = ’A’; //bug! user-after-free
}
26. Double free
// a10.c
#include <stdlib.h>
void fun(char *t) {
/* do some stuff here */
free(t);
}
int main() {
char *c;
c = malloc(10 * sizeof(char));
fun(c);
free(c); //bug! double free
}
27. Undefined behaviours and optimization
// a11.c
#include <limits.h>
#include <stdio.h>
// compile the code with optimization (-O3) and without
int main() {
int c = INT_MAX;
if (c+1 < c)
printf("hellon");
printf("%dn", c+1);
}
29. Undefined behaviours
When tools like the bounds checking GCC, Purify,
Valgrind, etc. first showed up, it was interesting to run a
random UNIX utility under them. The output of the
checker showed that these utility programs, despite
working perfectly well, executed a ton of memory safety
errors such as use of uninitialized data, accesses beyond
the ends of arrays, etc. Just running grep or whatever
would cause tens or hundreds of these errors to happen.
From: http://blog.regehr.org/archives/226
30. Undefined behaviours
More and more, I’m starting to wonder how safety-critical
code can continue being written in C.
A comment on: http://blog.regehr.org/archives/232
32. Static Typing and Type inference
// a12-1.rs
fn sqr(x: i32) -> i32 {
let y = x * x; // type inferred
y
}
fn main() {
let t1 = sqr(10); // type inferred
let t2:i32 = sqr(20);
println!("sqr 10 = {}, sqr 20 ={}", t1, t2);
}
33. Static Typing and Type Inference
The Rust type system is considerably more advanced than that of
“mainstream” languages like Java,C.
https://github.com/jaheba/stuff/blob/master/communicating_intent.
http://ferrisellis.com/posts/rust-implementing-units-for-
types/
https://fsharpforfunandprofit.com/series/designing-with-
types.html (you can do most of these in
Rust)
41. Ownership
// a15-1.rs
fn fun(v2: Vec<i32>) {
println!("{:?}", v2);
}
fn main() {
let v1 = vec![10, 20, 30];
fun(v1);
}
// do we have a double free here?
42. Ownership
// a16.rs
fn main() {
let v1 = vec![10, 20, 30];
let mut v2 = v1;
v2.truncate(2);
println!("{:?}", v2);
}
// what happens if we try to acces the
// vector through v1?
47. Memory safety without garbage collection
Languages like Python, Java etc achieve memory safety at run
time through garbage collection.
Rust achieves memory safety at compile time by static type
analysis.
Ownership + move semantics has some interesting properties
which makes them suitable for general resource management
(not just memory).
52. Garbage Collection
# a22.py
a = [10, 20, 30]
b = a # refcount is 2
a = "hello" # refcount is 1
b = "world" # refcount drops to zero, deallocate
53. Resource management
# a23.py
def read_a_line():
f = open("/etc/passwd")
s = f.readline()
f.close() # close the file, release OS resources
return s
while True:
print read_a_line()
54. Resource Leaks in managed languages
# a24.py
def read_a_line():
f = open("/etc/passwd")
s = f.readline()
# No explicit "close"
return s
while True:
print read_a_line()
55. Rust means never having to close a file!
// a25.rs
use std::fs::File;
use std::io::Read;
fn read_whole_file() -> String {
let mut s = String::new();
let mut f = File::open("/etc/passwd").unwrap();
f.read_to_string(&mut s).unwrap();
s // return the string
}
fn main() {
println!("{}", read_whole_file());
}
Read:
http://blog.skylight.io/rust-means-never-having-to-close-a-socket/
56. Ownership / Move: Limitations
// a26.rs
fn vector_sum(v: Vec<i32>) -> i32 {
//assume v is always a 3 elemnt vector
v[0] + v[1] + v[2]
}
fn main() {
let v = vec![1,2,3];
let s = vector_sum(v);
println!("{}",s);
}
57. Ownership / Move: Limitations
// a27.rs
fn vector_sum(v: Vec<i32>) -> i32 {
v[0] + v[1] + v[2]
}
fn vector_product(v: Vec<i32>) -> i32 {
v[0] * v[1] * v[2]
}
fn main() {
let v = vec![1,2,3];
let s = vector_sum(v);
let p = vector_product(v);
println!("{}",p);
}
// does this code compile?
58. Immutable Borrow
// a28.rs
fn vector_sum(v: &Vec<i32>) -> i32 {
v[0] + v[1] + v[2]
}
fn vector_product(v: &Vec<i32>) -> i32 {
v[0] * v[1] * v[2]
}
fn main() {
let v = vec![1,2,3];
let s = vector_sum(&v);
let p = vector_product(&v);
println!("v={:?}, s={}, p={}", v, s, p);
}
59. Immutable Borrow
// a29.rs
fn main() {
let v = vec![1,2,3];
let t1 = &v;
let t2 = &v;
println!("{}, {}, {}", t1[0], t2[0], v[0]);
}
// any number of immutable borrows are ok!
60. Immutable Borrow
// a30.rs
fn change(t1: &Vec<i32>) {
t1[0] = 10;
}
fn main() {
let mut v = vec![1,2,3];
change(&v);
}
// Does the program compile?
65. A use-after-free bug in C++
// a33-1.cpp
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v;
int *p;
v.push_back(1);
p = &v[0];
v.push_back(2);
*p = 100; // bug!
cout << v[0] << endl;
}
66. A use-after-free bug in Rust?
// a34.rs
fn main() {
let mut v = vec![10, 20, 30, 40];
let p1 = &v[1];
v.push(50);
// bug if we try to use p1
// does this code compile?
}
67. Borrowing Rules
Any number of immutable borrows can co-exist.
A mutable borrow can not co-exist with other mutable or
immutable borrows.
The “borrow checker” checks violations of these rules at
compile time.
68. Borrow checker limitations
The borrow checker gives you safety by rejecting ALL unsafe
programs.
But it is not perfect in the sense it rejects safe programs also;
“fighting the borrow checker” is a common sporting activity
among Rust programmers :)
There are plans to improve the situation:
http://smallcultfollowing.com/babysteps/blog/2017/03/01/nested-
method-calls-via-two-phase-borrowing/
69. Borrow checker limitations - an example
// a35.rs
fn main() {
let mut v = vec![10,20,30];
v.push(v.len());
}
// this will not compile
70. Borrow checker limitations - an example
// a36.rs
// Same as a35.rs
fn main() {
let mut v = vec![10,20,30];
let tmp0 = &v;
let tmp1 = &mut v;
let tmp2 = Vec::len(tmp0); //v.len()
Vec::push(tmp1, tmp2);// v.push(tmp2)
}
71. Lifetimes
// a37.rs
fn main() {
let ref1: &Vec<i32>;
{
let v = vec![1, 2, 3];
ref1 = &v;
}
// v gets deallocated as it goes out of
// the scope. What about ref1? Do we have
// a "dangling pointer" here?
}
72. Lifetimes
// a38.rs
fn foo() -> Vec<i32> {
let v = vec![1, 2, 3];
v // transfer ownership to caller
}
fn main() {
let p = foo();
println!("{:?}", p);
}
73. Lifetimes
// a39.rs
fn foo() -> &Vec<i32> {
let v = vec![1, 2, 3];
&v // Will this compile?
}
fn main() {
let p = foo();
}
74. Explicit Lifetime Annotations
// a40.rs
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> &i32 {
&v1[0]
}
fn main() {
let v1 = vec![1, 2, 3];
let p:&i32;
{
let v2 = vec![4, 5, 6];
p = foo(&v1, &v2);
// How does the compiler know, just by looking at
// the signature of "foo", that the reference
// returned by "foo" will live as long as "p"?
}
}
82. A complete web app in Rust (using rocket.rs)
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
#[get("/<name>")]
fn index(name: &str) -> String {
format!("nHello, {}!, hope you are enjoying
the Rust workshop!n", name)
}
fn main() {
rocket::ignite()
.mount("/", routes![index])
.launch();
}
83. Test run the web app!
wget -q -O - http://128.199.100.27:8000/Mohan
curl -s http://128.199.100.27:8000/Mohan
84. End of Part 1
What we have seen so far is the “core” of Rust, these are the
ideas which make Rust unique!
Most of the other “interesting” ideas are borrowed from
statically typed functional programming languages (like ML).
(The first Rust compiler was written in Ocaml).
88. Zero cost abstractions
Here is part of the assembly language code produced by the
compiler for a45.rs:
.Ltmp0:
.cfi_def_cfa_offset 80
movabsq $500000000500000000, %rax
movq %rax, (%rsp)
leaq (%rsp), %rax
movq %rax, 8(%rsp)
Looks like the expression has been evaluated fully at compile time
itself!
Here is the commandline used to produce the above output:
rustc -O a45.rs --emit=asm
89. Zero cost abstractions
You can write confidently using all the high-level abstractions
the language has to offer.
Your code will almost always be as fast as hand-coded low level
C!
90. Sum Types and Pattern Matching
// a46.rs
enum Color {
Red,
Green,
Blue,
}
use Color::*;
fn main() {
let c = Red;
match c {
Red => println!("color is Red!"),
Green => println!("color is Green!"),
Blue => println!("color is Blue!")
}
}
91. Sum Types and Pattern Matching
// a47.rs
#[derive(Debug)]
enum Shape {
Circle(u32),
Square (u32),
Rectangle {ht: u32, wid: u32},
}
use Shape::*;
fn main() {
let s1 = Circle(10);
let s2 = Square(5);
let s3 = Rectangle {ht: 10, wid: 2};
println!("{:?}", s3);
}
92. Pattern matching is exhaustive
// a48.rs
#[derive(Debug)]
enum Shape {
Circle(f64),
Square (f64),
Rectangle {ht: f64, wid: f64},
}
use Shape::*;
fn area(s: Shape) -> f64 {
match s {
Circle(x) => 3.14 * x * x,
Rectangle {ht: x, wid: y} => x * y,
} // bug!
}
fn main() {
let s1 = Circle(10.0);
println!("{}", area(s1));
}
93. The Option type
// a49.rs
fn main() {
let mut a = vec![10];
let b = a.pop();
let c = a.pop();
let d = b + 1; // does it compile?
}
94. The Option type
// a50.rs
fn main() {
let mut a = vec![10];
let b = a.pop();
let c = a.pop();
println!("b = {:?}, c = {:?}", b, c);
}
95. The Option type
// a51.rs
fn main() {
let mut a = vec![10];
let b = a.pop();
match b {
Some(x) => println!("pop: {}", x),
None => println!("empty stack"),
}
}
96. The Option type
// a52.rs
fn main() {
let mut a = vec![10];
let b = a.pop();
println!("{}", b.unwrap());
let c = a.pop();
println!("{}", c.unwrap());
}
97. Generic Enums - an implementation of Option
// a53.rs
// A "generic" enum similar to Option
enum Maybe <T> {
Just(T),
Nothing,
}
use Maybe::*;
fn main() {
let c:Maybe<i32> = Just(10);
let d:Maybe<&str> = Just("hello");
let e = Just(20);
let f = Just("world");
}
98. Generic functions
// a54.rs
fn identity <T> (x: T) -> T {
x
}
fn main() {
let a = identity(10);
let b = identity(’A’);
let c = identity("hello");
println!("{}, {}, {}", a, b, c);
}
Rust creates specialized versions of the “identity” function for each
argument type. This is called “monomorphization”.
102. Tools
Cargo, the package manager (crates.io holds packages)
rustfmt, formatting Rust code according to style guidelines
clippy, a “lint” tool for Rust
rustup (https://www.rustup.rs/), the Rust toolchain
installer/manager
103. Interesting projects using Rust
Servo, from Mozilla. The next-gen browser engine.
Redox OS (https://www.redox-os.org/), an Operating System
being written from scratch in Rust.
ripgrep (https://github.com/BurntSushi/ripgrep), a fast text
search tool.
rocket.rs - a powerful web framework.
More: https://github.com/kud1ing/awesome-rust
105. Documentation
Official Rust book (http://rust-lang.github.io/book/). The
second edition is far better, even though it is incomplete.
Upcoming O’Reilly book:
http://shop.oreilly.com/product/0636920040385.do
http://intorust.com/ (screencasts for learning Rust)