Commit graph

2975 commits

Author SHA1 Message Date
Timothy Flynn d793262beb AK+Everywhere: Make UTF-16 to UTF-8 converter fallible
This could fail to allocate the underlying storage needed to store the
UTF-8 data. Propagate this error.
2023-01-08 12:13:15 +01:00
Timothy Flynn 1edb96376b AK+Everywhere: Make UTF-8 and UTF-32 to UTF-16 converters fallible
These could fail to allocate the underlying storage needed to store the
UTF-16 data. Propagate these errors.
2023-01-08 12:13:15 +01:00
Timothy Flynn 425c168ded AK+LibJS+LibRegex: Define an alias for UTF-16 string data storage
Instead of writing out "Vector<u16, 1>" everywhere, let's have a name
for it.
2023-01-08 12:13:15 +01:00
Timothy Flynn 39bda0073e AK: Make StringBuilder::try_append_code_point actually fallible
It currently uses the non-fallible `append` method to append each UTF-8
encoded byte of the code point.
2023-01-08 12:13:15 +01:00
Ben Wiederhake 3281050359 Everywhere: Remove "LibC/" includes, add lint-rule against it 2023-01-07 10:01:37 -07:00
Ben Wiederhake d575cfda61 AK: Restrict include of LibC header 2023-01-07 10:01:37 -07:00
Andrew Kaster 64a242261e AK: Reimplement DistinctNumeric comparison operators using operator<=>
Unlike what the class comment says, it's actually valid to return int
from this operator and treat it like a "normal" C-like compare method.
2023-01-07 14:51:04 +01:00
Andrew Kaster a8fcd39b88 AK: Reimplement comparisons on AK::Time using operator<=>
This allows us to make all comparision operators on the class constexpr
without pulling in a bunch of boilerplate. We don't use the `<compare>`
header because it doesn't compile in the main serenity cross-build due
to the include paths to LibC being incompatible with how libc++ expects
them to be for clang builds.
2023-01-07 14:51:04 +01:00
Andrew Kaster 83ad5bfba0 AK: Remove global free function comparison operators for timespec
No code was using these, so let's just delete them. They pollute the
lookup for every single comparison operator in the project.
2023-01-07 14:51:04 +01:00
Andrew Kaster f7025435b2 AK: Add user defined literals for Time for ns, us, ms, and sec
We can use these to simplify Time constants throughout the codebase,
turning Time::from_milliseconds(10) into 10_ms, for example.
2023-01-07 14:51:04 +01:00
Staubfinger 25dd0a4d2d AK: Make Statistics::median return a mean for an even number of values
The previous implementation of Statistics::median() was slightly
incorrect with an even number of elements since in those cases it needs
to be the arithmetic mean of the two elements that share the middle
position.
2023-01-07 12:40:47 +01:00
Thiago Henrique Hupner 401bc13776 AK: Use base URL when the specified URL is empty 2023-01-06 13:59:17 -07:00
Lucas CHOLLET 85bfeba8c6 AK: Support fixed point formatting to print real numbers 2023-01-06 16:05:13 +01:00
Lucas CHOLLET 25e39df7ba AK: Rename StandardFormatter::Mode::Float => FixedPoint 2023-01-06 16:05:13 +01:00
Sam Atkins 6e0ad5536f AK: Export adopt_nonnull_ref_or_enomem to the global namespace 2023-01-06 16:03:50 +01:00
Aliaksandr Kalenik c6d494513e AK: Fix typo in -= operator of DistinctNumeric 2023-01-06 12:01:46 +01:00
Ben Wiederhake 65b420f996 Everywhere: Remove unused includes of AK/Memory.h
These instances were detected by searching for files that include
AK/Memory.h, but don't match the regex:

\\b(fast_u32_copy|fast_u32_fill|secure_zero|timing_safe_compare)\\b

This regex is pessimistic, so there might be more files that don't
actually use any memory function.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake 6b7ce19161 Everywhere: Remove unused includes of LibC/stdlib.h
These instances were detected by searching for files that include
stdlib.h, but don't match the regex:

\\b(_abort|abort|abs|aligned_alloc|arc4random|arc4random_buf|arc4random_
uniform|atexit|atof|atoi|atol|atoll|bsearch|calloc|clearenv|div|div_t|ex
it|_Exit|EXIT_FAILURE|EXIT_SUCCESS|free|getenv|getprogname|grantpt|labs|
ldiv|ldiv_t|llabs|lldiv|lldiv_t|malloc|malloc_good_size|malloc_size|mble
n|mbstowcs|mbtowc|mkdtemp|mkstemp|mkstemps|mktemp|posix_memalign|posix_o
penpt|ptsname|ptsname_r|putenv|qsort|qsort_r|rand|RAND_MAX|random|reallo
c|realpath|secure_getenv|serenity_dump_malloc_stats|serenity_setenv|sete
nv|setprogname|srand|srandom|strtod|strtof|strtol|strtold|strtoll|strtou
l|strtoull|system|unlockpt|unsetenv|wcstombs|wctomb)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use anything from the stdlib.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake f07847e099 Everywhere: Remove unused includes of AK/Concepts.h
These instances were detected by searching for files that include
AK/Concepts.h, but don't match the regex:

\\b(AnyString|Arithmetic|ArrayLike|DerivedFrom|Enum|FallibleFunction|Flo
atingPoint|Fundamental|HashCompatible|Indexable|Integral|IterableContain
er|IteratorFunction|IteratorPairWith|OneOf|OneOfIgnoringCV|SameAs|Signed
|SpecializationOf|Unsigned|VoidFunction)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any concepts.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake c2a900b853 Everywhere: Remove unused includes of AK/StdLibExtras.h
These instances were detected by searching for files that include
AK/StdLibExtras.h, but don't match the regex:

\\b(abs|AK_REPLACED_STD_NAMESPACE|array_size|ceil_div|clamp|exchange|for
ward|is_constant_evaluated|is_power_of_two|max|min|mix|move|_RawPtr|RawP
tr|round_up_to_power_of_two|swap|to_underlying)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any "extra stdlib" functions.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
Ben Wiederhake 6fd478b6ce Everywhere: Remove unused includes of AK/Format.h
These instances were detected by searching for files that include
AK/Format.h, but don't match the regex:

\\b(CheckedFormatString|critical_dmesgln|dbgln|dbgln_if|dmesgln|FormatBu
ilder|__FormatIfSupported|FormatIfSupported|FormatParser|FormatString|Fo
rmattable|Formatter|__format_value|HasFormatter|max_format_arguments|out
|outln|set_debug_enabled|StandardFormatter|TypeErasedFormatParams|TypeEr
asedParameter|VariadicFormatParams|v_critical_dmesgln|vdbgln|vdmesgln|vf
ormat|vout|warn|warnln|warnln_if)\\b

(Without the linebreaks.)

This regex is pessimistic, so there might be more files that don't
actually use any formatting functions.

Observe that this revealed that Userland/Libraries/LibC/signal.cpp is
missing an include.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:27:20 -05:00
kleines Filmröllchen a6a439243f Kernel: Turn lock ranks into template parameters
This step would ideally not have been necessary (increases amount of
refactoring and templates necessary, which in turn increases build
times), but it gives us a couple of nice properties:
- SpinlockProtected inside Singleton (a very common combination) can now
  obtain any lock rank just via the template parameter. It was not
  previously possible to do this with SingletonInstanceCreator magic.
- SpinlockProtected's lock rank is now mandatory; this is the majority
  of cases and allows us to see where we're still missing proper ranks.
- The type already informs us what lock rank a lock has, which aids code
  readability and (possibly, if gdb cooperates) lock mismatch debugging.
- The rank of a lock can no longer be dynamic, which is not something we
  wanted in the first place (or made use of). Locks randomly changing
  their rank sounds like a disaster waiting to happen.
- In some places, we might be able to statically check that locks are
  taken in the right order (with the right lock rank checking
  implementation) as rank information is fully statically known.

This refactoring even more exposes the fact that Mutex has no lock rank
capabilites, which is not fixed here.
2023-01-02 18:15:27 -05:00
Ben Wiederhake 3334cf675a AK+Kernel: Eliminate UB (signed overflow) from days_since_epoch 2023-01-02 16:19:35 -05:00
Ben Wiederhake 7a69219a35 AK+Tests: Replace years_to_days_since_epoch by near-instant function
This solves half the problem of #12729. Note that the inverse function
time_to_tm() in LibC/time.cpp still uses a slow for-loop.

See also #13138
2023-01-02 16:19:35 -05:00
Lenny Maiorani e0ab7763da AK: Combine SinglyLinkedList and SinglyLinkedListWithCount
Using policy based design `SinglyLinkedList` and
`SinglyLinkedListWithCount` can be combined into one class which takes
a policy to determine how to keep track of the size of the list. The
default policy is to use list iteration to count the items in the list
each time. The `WithCount` form is a different policy which tracks the
size, but comes with the overhead of storing the count and
incrementing/decrementing on each modification.

This model is extensible to have other forms of counting by
implementing only a new policy instead of implementing a totally new
type.
2023-01-02 20:13:24 +00:00
Arda Cinar 0dbb1be81c AK: Add an option to format numbers with 1000 based units
Instead of only allowing 1024-based units.
2023-01-02 20:11:18 +00:00
Arda Cinar ccb6b4f943 AK: Make sure no overflow occurs in number_string_with_one_decimal
A possible integer overflow might have occured inside the function in
case (number % unit) * 10 did not fit into a u64. So it is verified that
this does not happen at the beginning of the function.
2023-01-02 20:11:18 +00:00
Arda Cinar c8fadff9b1 AK: Add a human_readable_quantity helper to NumberFormat.h
This can be used for displaying large quantities that are not measured
in bytes in a more human-readable format.
2023-01-02 20:11:18 +00:00
Arda Cinar 3e924e2a37 AK: Move the functions in NumberFormat.h out of line 2023-01-02 20:11:18 +00:00
Ben Wiederhake c1676cdddb Everywhere: Remove unused includes of AK/IterationDecision.h
These instances were detected by searching for files that include
IterationDecision.h, but don't match the regex:
\\bIterationDecision(?!\.h>)\\b
This is the only symbol defined by IterationDecision.h.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:08:35 +00:00
Ben Wiederhake a8391d5a60 Everywhere: Remove unused includes of AK/Array.h
These instances were detected by searching for files that include
Array.h, but don't match the regex:
\\b(Array(?!\.h>)|iota_array|integer_sequence_generate_array)\\b
These are the three symbols defined by Array.h.

In theory, one might use LibCPP to detect things like this
automatically, but let's do this one step after another.
2023-01-02 20:08:35 +00:00
Ben Wiederhake b83cb09db1 Everywhere: Fix badly-formatted includes
In 7c5e30daaa, the focus was "only" on
Userland/Libraries/, whereas this commit cleans up the remaining
headers in the repo, and any new badly-formatted include.
2023-01-02 11:06:15 -05:00
Nico Weber 25171e310b AK: Prefer VERIFY_NOT_REACHED in ByteBuffer 2022-12-31 23:20:37 +01:00
Lucas CHOLLET f12e81b74a AK: Add CircularBuffer
The class is very similar to `CircularDuplexStream` in its behavior.
Main differences are that `CircularBuffer`:
 - does not inherit from `AK::Stream`
 - uses `ErrorOr` for its API
 - is heap allocated (and OOM-Safe)

 This patch also add some tests.
2022-12-31 04:44:17 -07:00
Timon Kruiper b18a7297c5 Kernel: Move ScopedCritical.cpp to Kernel base directory
This file does not contain any architecture specific implementations,
so we can move it to the Kernel base directory. Also update the relevant
include paths.
2022-12-29 19:32:20 -07:00
Sam Atkins feb0eb9309 AK: Fix constructing ErrorOr from ErrorOr of a related type
Mark other ErrorOr types as friends, and fix a typo in the &&
constructor, so that we can create an ErrorOr<Core::Object> from an
ErrorOr<GUI::Widget>. Also, add some requires() clauses to these
constructors so the error messages are clearer.
2022-12-28 22:34:00 -05:00
Arda Cinar bbaf86fb46 AK: Add a forgiving_base64_decode helper
According to the specification at
https://infra.spec.whatwg.org/#forgiving-base64
2022-12-28 21:15:02 +01:00
Nico Weber 57126a0d3c AK: Make BigEndian<> and LittleEndian<> work with enum classes 2022-12-28 20:13:12 +00:00
Andreas Kling c0e3bdd51b AK: Remove ARCH(I386) macro 2022-12-28 11:53:41 +01:00
Liav A feeb25bcee AK: Remove i686 support 2022-12-28 11:53:41 +01:00
Florian Cramer af2ffcaba8 AK: Make StringUtils::matches() handle escaping correctly
Previously any backslash and the character following it were ignored.
This commit adds a fall through to match the character following the
backslash without checking whether it is "special".
2022-12-27 07:28:25 +03:30
Nico Weber 8932b28b8a AK: Mark Error::from_ functions as [[nodiscard]]
Prevents mistakes like the one fixed in #16672.
2022-12-26 13:56:13 -05:00
Timothy Flynn d2a304ae87 AK: Specialize TypeList for Variant types
This allows callers to use the following semantics:

    using MyVariant = Variant<Empty, int>;

    template<typename T>
    size_t size() { return TypeList<T>::size; }

    auto s = size<MyVariant>();

This will be needed for an upcoming IPC change, which will result in us
knowing the Variant type, but not the underlying variadic types that the
Variant holds.
2022-12-26 09:36:16 +01:00
Alec Murphy da4067a75f AK: Remove tilde from URL::PercentEncodeSet::EncodeURI 2022-12-26 04:51:55 +03:30
Timothy Flynn 4b4b15adb1 AK: Rearrange Error's members to reduce its size by 8 bytes
This shrinks sizeof(Error) from 32 bytes to 24 bytes, which in turn will
shrink sizeof(ErrorOr<T>) by the same amount (in cases where sizeof(T)
is less than sizeof(Error)).
2022-12-22 14:13:56 -05:00
Sam Atkins 29733e65f8 AK+Everywhere: Replace all Bitmap::must_create() uses with ::create()
Well, *someone* has to add some more FIXMEs to keep FIXME Roulette
going. :^)
2022-12-22 15:48:53 +01:00
Sam Atkins bed5961fc2 AK: Rename Bitmap::try_create() to ::create()
This is step 1 to removing `must_create()`.
2022-12-22 15:48:53 +01:00
Karol Kosek 25fa485dfb AK: Calculate elapsed days in human_readable_time() 2022-12-21 08:41:34 +00:00
Agustin Gianni 9a2ee5a9dd AK: Add DeprecatedString::find_last(StringView)
This adds the the method DeprecatedString::find_last() as wrapper for
StringUtils::find_last for the StringView type.
2022-12-20 11:24:05 +01:00
Jelle Raaijmakers 25f2e4981c AK: Stop using DeprecatedString in Base64 encoding 2022-12-20 10:34:19 +01:00
Jelle Raaijmakers 99c1b634fc AK: Stop using DeprecatedString in UUID 2022-12-20 10:34:19 +01:00
Andreas Kling f11e6beca8 AK: Use __has_builtin() in Checked.h
Instead of avoiding overflow-checking builtins with AK_COMPILER_CLANG,
we can use the preprocessor's __has_builtin() mechanism to check if
they are available.
2022-12-19 09:29:12 -05:00
Lenny Maiorani f2336d0144 AK+Everywhere: Move custom deleter capability to OwnPtr
`OwnPtrWithCustomDeleter` was a decorator which provided the ability
to add a custom deleter to `OwnPtr` by wrapping and taking the deleter
as a run-time argument to the constructor. This solution means that no
additional space is needed for the `OwnPtr` because it doesn't need to
store a pointer to the deleter, but comes at the cost of having an
extra type that stores a pointer for every instance.

This logic is moved directly into `OwnPtr` by adding a template
argument that is defaulted to the default deleter for the type. This
means that the type itself stores the pointer to the deleter instead
of every instance and adds some type safety by encoding the deleter in
the type itself instead of taking a run-time argument.
2022-12-17 16:00:08 -05:00
Eli Youngs 950b36f95d AK: Add a try_ensure() method to HashMap 2022-12-16 10:41:56 -07:00
Eli Youngs a2024cfb69 AK: Support popping an arbitrary element from a HashTable 2022-12-16 10:41:56 -07:00
Timothy Flynn d28c9ba054 AK: Synchronize explicit instantiations of to_int and to_uint
1. Ensure long and long long are instantiated for to_int.
2. Ensure long and long long are not instantiated for to_uint.
2022-12-16 10:06:26 +01:00
Lucas CHOLLET 34c13eff11 AK: Add OwnPtrWithCustomDeleter
This class is a smart pointer that let you provide a custom deleter to
free the pointer.

It is quite primitive compared to other smart pointers but can still be
useful when interacting with C types that provides a custom `free()`
function.
2022-12-15 13:38:13 +00:00
kleines Filmröllchen 026cc3d4b9 AK: Add Span to Array conversion function 2022-12-15 00:21:00 -07:00
Poseydon42 bdd7531bf5 AK: Create relative path even if prefix is not an ancestor of the path 2022-12-14 15:11:03 +00:00
Ali Mohammad Pur b367da592c AK: Bring back the AK_DONT_REPLACE_STD #define
This was removed in a910961f37 in favour
of the more general USING_AK_GLOBALLY #define, but Ladybird (and
probably other projects) depend on the smaller hammer to include STL
headers and keep the USING_AK_GLOBALLY behaviour, so put it back and
preserve its behaviour.
2022-12-14 12:56:01 +01:00
Ali Mohammad Pur f96a3c002a Everywhere: Stop shoving things into ::std and mentioning them as such
Note that this still keeps the old behaviour of putting things in std by
default on serenity so the tools can be happy, but if USING_AK_GLOBALLY
is unset, AK behaves like a good citizen and doesn't try to put things
in the ::std namespace.

std::nothrow_t and its friends get to stay because I'm being told that
compilers assume things about them and I can't yeet them into a
different namespace...for now.
2022-12-14 11:44:32 +01:00
Ali Mohammad Pur 72514d6915 AK: Make Types.h not export its functions if !USING_AK_GLOBALLY 2022-12-14 11:44:32 +01:00
kleines Filmröllchen 5b4818df22 AK: Make Variant's index type public
This will allow the IPC system to use the exact required index type,
saving transmission space, once it can send variants.
2022-12-13 10:24:59 -05:00
Ali Mohammad Pur ad120606fd AK: Fix build with !USING_AK_GLOBALLY
A couple headers expected names to be in the global namespace, qualify
those names to make sure they're resolved even when the names are not
exported.
One header placed its functions in the global namespace, move those to
the AK namespace to make the concepts resolve.
2022-12-13 08:09:56 +03:30
Ali Mohammad Pur d987ddc0ee AK: Actually don't include <unistd.h> for windows in Platform.h
I got the conditions wrong last time, oops :^)
2022-12-12 17:01:16 +00:00
Arda Cinar 1cdd3bb74f AK: Add a shuffle utility function
This implements a shuffle function in AK/Random.h which works on any
container with size() and curly brace operators. It uses fisher-yates
shuffle.
2022-12-12 16:23:03 +00:00
Lucas CHOLLET 6c83bd8fd4 AK: Introduce the DerivedFrom concept 2022-12-12 16:21:39 +00:00
Ali Mohammad Pur 4aa70a07ca AK: Don't use <random> on windows for ::rand()
This is the same as the libc function, just use the libc function.
2022-12-12 15:05:48 +00:00
Ali Mohammad Pur 06816deb78 AK: Don't try to include <unistd.h> on windows for PAGE_SIZE 2022-12-12 15:05:48 +00:00
kleines Filmröllchen b81a457de5 AK: Change quicksort comments to standard // style 2022-12-12 15:03:57 +00:00
Marc Luqué 22f472249d AK: Introduce cutoff to insertion sort for Quicksort
Implement insertion sort in AK. The cutoff value 7 is a magic number
here, values [5, 15] should work well. Main idea of the cutoff is to
reduce recursion performed by quicksort to speed up sorting
of small partitions.
2022-12-12 15:03:57 +00:00
kleines Filmröllchen bbb256e8b5 AK: Introduce Indexable concept
This was dearly missing and can be used in many existing templates.
2022-12-12 15:03:57 +00:00
Ali Mohammad Pur fc805e8f03 AK: Specialise AK::is() for NNRP<T>
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 18bc88b806 AK: Add an identity implementation of StringView::from_string_literal()
This is required for the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur e591c604de AK: Add Optional-like value()/has_value() getters to WeakPtr 2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c373c2deb0 AK: Allow constructing WeakPtr<T> using OptionalNone
The Jakt runtime requires this.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 96b36203a2 AK: Add Optional::lazy_emplace(Callable)
This makes it possible to emplace using a given function instead of
passing constructor arguments.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 0ed9fe3864 AK: Allow non-ascii characters to be printed
This keeps the FIXME, as well as the assertion.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 08fc42002c AK: Format the contents of NNRP<T> if T is formattable 2022-12-11 20:44:54 +03:30
Ali Mohammad Pur ff038f306a AK: Ignore "alternative" formatting of StringView instead of crashing
Jakt implements this in a different way, but it's a noop for
StringViews anyway.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 1cc8cdcd23 AK: Add a Error::__jakt_from_string_literal(StringView) factory function
Note that Jakt only allows StringView creation from string literals, so
none of the invariants in the class are broken by this (if used only
from within Jakt).
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 537924a8d0 AK: Let ErrorOr<T, E> expose its result/error types
`ErrorOr<T, E>::ResultType` can now refer to `T`.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c3b4b0e88b AK: Add support for modulo to Checked<T>
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur cc0b970d81 AK: Allow Optional<T> to be constructed by OptionalNone()
This is needed by the Jakt runtime too.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 12e4cd3b77 AK: Allow the user to access the variant index
The average user has no need for this, but the Jakt compiler uses this
to avoid going through the expensive ::visit() and ::get<>() APIs.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 543890c5c9 AK: Add a fallible StringBuilder::create() factory function
This is nice, and is also used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 21c2d8bd98 AK: Add a Optional::value_or_lazy_evaluated(constructor_function) API
This allows the user to avoid constructing the default value if the
optional already contains a value.
This is used by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur cc948d06a6 AK: Add a functional-style Optional::map(mapper_function) API
This allows the user to transform the contents of the optional (if any
exists), without manually unwrapping and then rewrapping it.
This is needed by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 5809b4aafa AK: Let HashMap also take a ValueTraits
We were previously using Traits<V>, take that frrom the template
parameters instead.
This is needed by the Jakt runtime.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 58252a7684 AK: Elaborate the Error constructors a bit
The old constraints were making clang mad, so express them in a less
complex way.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 099a6bc45f AK: Give DeprecatedString::replace() a default mode
This is used in Jakt, and providing that value from Jakt's side is more
trouble than doing this.
Considering this class is bound to go away, a little
backwards-compatible API change is just fine.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur 7a17fd6d71 AK: Add a DeprecatedString::byte_at() getter
`operator[]` returns a char, this is used in Jakt.
2022-12-11 20:44:54 +03:30
Ali Mohammad Pur c547b55a00 AK: Add a Checked::unchecked_value() function
This is used in Jakt.
2022-12-11 20:44:54 +03:30
kleines Filmröllchen 16ca41ec10 AK: Add LexicalPath::is_child_of
This API checks whether this path is a child of (or the same as) another
path.
2022-12-11 16:05:23 +00:00
kleines Filmröllchen f502e24bd7 AK: Change the moved-from String state to the empty short string
The previous moved-from state was the null string. This violates both
our invariant that String is never null, and also the C++ contract that
the moved-from state must be valid but unspecified. The empty short
string state is of course valid, so it satisfies both invariants. It
also allows us to remove any extra checks for the null state.

The reason this change is made is primarily because swap() requires
moved-from objects to be reassignable (C++ allows this). Because the
move assignment of String would not check the null state, it crashed
trying to increment the data reference count (nullptr signals a
non-short string). This meant that e.g. quick_sort'ing String would
crash immediately.
2022-12-11 16:05:23 +00:00
kleines Filmröllchen ca80353efe AK: Add comparison operator
s p a c e s h i p  o p e r a t o r

Comparing UTF-8 can be done by simple byte lexicographic comparison per
definition, so we just piggy-back on StringView's high-performance
comparator.
2022-12-11 16:05:23 +00:00
Thomas Queiroz 54c12b76ed AK: Remove HashMap::ensure_capacity
This is not perfect, since the constuctor can still fail.
2022-12-10 14:29:46 +01:00
Tim Schumacher 35bcdefdf7 AK: Add Byte accessors for BigEndian and LittleEndian 2022-12-10 12:05:55 +00:00
Moustafa Raafat b8f1e1bed2 Everywhere: Remove unnecessary AK and Detail namespace scoping 2022-12-09 11:25:30 +00:00
Moustafa Raafat ae2abcebbb Everywhere: Use C++ concepts instead of requires clauses 2022-12-09 11:25:30 +00:00
Andreas Kling d77ce7bae9 AK: Add Vector::shrink_to_fit()
If there's more capacity than size, the vector is reallocated to have
capacity == size.
2022-12-08 23:36:17 +00:00
Timothy Flynn 63e2aa962d AK: Disallow implicit pointer-to-boolean conversion in JsonValue
Similar to how LibJS and LibSQL used to behave, the boolean constructor
of JsonValue is currently allowing pointers to be used to construct a
boolean value. Explicitly disallow such construction.
2022-12-09 00:05:30 +01:00
Maciej 58f5deba70 AK: Unref old m_data in String's move assignment
We were overridding the data pointer without unreffing it,
causing a memory leak when assigning a String.
2022-12-09 00:02:53 +01:00
Timothy Flynn 949f5460fb AK: Add formatters for Span<T> and Span<T const>
This generalizes the formatter currently used for Vector to be usable
for any Span.
2022-12-08 17:14:48 +01:00
Linus Groh f23b55ae86 AK: Add StringView(String const&) constructor
This allows us to pass the new String type to functions that take a
StringView directly, having to call bytes_as_string_view() every time
gets old quickly.
2022-12-07 09:58:38 +00:00
Linus Groh 5103e08b77 AK: Ignore -Wshadow in TRY() and MUST()
This makes the warning in CLion disappear when nesting them.
2022-12-06 21:31:00 +00:00
Linus Groh d2e143eec7 AK: Add a helper macro to temporarily ignore diagnostics with _Pragma() 2022-12-06 21:31:00 +00:00
Andreas Kling a3e82eaad3 AK: Introduce the new String, replacement for DeprecatedString
DeprecatedString (formerly String) has been with us since the start,
and it has served us well. However, it has a number of shortcomings
that I'd like to address.

Some of these issues are hard if not impossible to solve incrementally
inside of DeprecatedString, so instead of doing that, let's build a new
String class and then incrementally move over to it instead.

Problems in DeprecatedString:

- It assumes string allocation never fails. This makes it impossible
  to use in allocation-sensitive contexts, and is the reason we had to
  ban DeprecatedString from the kernel entirely.

- The awkward null state. DeprecatedString can be null. It's different
  from the empty state, although null strings are considered empty.
  All code is immediately nicer when using Optional<DeprecatedString>
  but DeprecatedString came before Optional, which is how we ended up
  like this.

- The encoding of the underlying data is ambiguous. For the most part,
  we use it as if it's always UTF-8, but there have been cases where
  we pass around strings in other encodings (e.g ISO8859-1)

- operator[] and length() are used to iterate over DeprecatedString one
  byte at a time. This is done all over the codebase, and will *not*
  give the right results unless the string is all ASCII.

How we solve these issues in the new String:

- Functions that may allocate now return ErrorOr<String> so that ENOMEM
  errors can be passed to the caller.

- String has no null state. Use Optional<String> when needed.

- String is always UTF-8. This is validated when constructing a String.
  We may need to add a bypass for this in the future, for cases where
  you have a known-good string, but for now: validate all the things!

- There is no operator[] or length(). You can get the underlying data
  with bytes(), but for iterating over code points, you should be using
  an UTF-8 iterator.

Furthermore, it has two nifty new features:

- String implements a small string optimization (SSO) for strings that
  can fit entirely within a pointer. This means up to 3 bytes on 32-bit
  platforms, and 7 bytes on 64-bit platforms. Such small strings will
  not be heap-allocated.

- String can create substrings without making a deep copy of the
  substring. Instead, the superstring gets +1 refcount from the
  substring, and it acts like a view into the superstring. To make
  substrings like this, use the substring_with_shared_superstring() API.

One caveat:

- String does not guarantee that the underlying data is null-terminated
  like DeprecatedString does today. While this was nifty in a handful of
  places where we were calling C functions, it did stand in the way of
  shared-superstring substrings.
2022-12-06 15:21:26 +01:00
Ali Mohammad Pur c500647eee AK: Take the bump-allocated chunk header into account in destroy_all()
Previously we allowed the end_offset to be larger than the chunk itself,
which made it so that certain input sizes would make the logic attempt
to delete a nonexistent object.
Fixes #16308.
2022-12-06 11:19:50 +01:00
Linus Groh 57dc179b1f Everywhere: Rename to_{string => deprecated_string}() where applicable
This will make it easier to support both string types at the same time
while we convert code, and tracking down remaining uses.

One big exception is Value::to_string() in LibJS, where the name is
dictated by the ToString AO.
2022-12-06 08:54:33 +01:00
Linus Groh 6e19ab2bbc AK+Everywhere: Rename String to DeprecatedString
We have a new, improved string type coming up in AK (OOM aware, no null
state), and while it's going to use UTF-8, the name UTF8String is a
mouthful - so let's free up the String name by renaming the existing
class.
Making the old one have an annoying name will hopefully also help with
quick adoption :^)
2022-12-06 08:54:33 +01:00
Linus Groh babfc13c84 Everywhere: Remove 'clang-format off' comments that are no longer needed
https://github.com/SerenityOS/serenity/pull/15654#issuecomment-1322554496
2022-12-03 23:52:23 +00:00
Linus Groh d26aabff04 Everywhere: Run clang-format 2022-12-03 23:52:23 +00:00
Steffen Rusitschka 1aa07d7328 AK: Implement FloatExtractor<f128>
This patch adds support for 128-bit floating points in FloatExtractor.

This is required to build SerenityOS on MacOS/aarch64. It might break
building for Raspberry Pi.
2022-12-02 16:22:51 +01:00
Tim Schumacher a8c73998f1 AK: Fully qualify some usages of AK features outside of the AK namespace 2022-11-27 23:54:40 +01:00
Tim Schumacher 03fd9002da AK: Export Details and Concepts into the AK namespace
AK internals like to use concepts and details without a fully qualified
name, which usually works just fine because we make everything
AK-related available to the unqualified namespace.

However, this breaks as soon as we start not using `USING_AK_GLOBALLY`,
due to those identifiers no longer being made available. Instead, we
just export those into the `AK` namespace instead.
2022-11-27 23:54:40 +01:00
Andreas Kling ae3ffdd521 AK: Make it possible to not using AK classes into the global namespace
This patch adds the `USING_AK_GLOBALLY` macro which is enabled by
default, but can be overridden by build flags.

This is a step towards integrating Jakt and AK types.
2022-11-26 15:51:34 +01:00
cflip 9a0bb8212a AK: Add contains_slow method to Stack 2022-11-26 09:38:13 +01:00
MacDue ce6dacbc46 AK: Fix double promotion error when using AK:ceil on floats 2022-11-26 01:17:04 +01:00
Ali Mohammad Pur 2110e7cf85 Everywhere: Add support for compilation under emscripten
Co-Authored-By: Andrew Kaster <akaster@serenityos.org>
2022-11-26 02:23:15 +03:30
Andreas Kling e7ba03ddd1 AK: Add Utf8View::iterator_at_byte_offset_without_validation()
Unlike iterator_at_byte_offset(), this function assumes the provided
byte offset is a valid offset into the UTF-8 character stream.

This avoids walking the stream from the start.
2022-11-24 16:06:20 +00:00
Timothy Flynn 061bca99a9 AK: Define a convenience alias for a Function's return type
This is nice when the return type is long and needs to be specified as
a lambda's return type many times to resolve ambiguity.
2022-11-21 18:54:22 +00:00
Andreas Kling db91552621 AK: Fix memory corruption due to BumpAllocator mmap reuse
There was a subtle mismatch between the obviously expected behavior
of BumpAllocator::for_each_chunk() and its actual implementation.

You'd think it would invoke the callback with the address of each chunk,
but actually it also took the liberty of adding sizeof(ChunkHeader) to
this address. UniformBumpAllocator::destroy_all() relied on this to
get the right address for objects to delete.

The bug happened in BumpAllocator::deallocate_all(), where we use
for_each_chunk() to walk the list of chunks and munmap() them.

To avoid memory mapping churn, we keep a global cache of 1 chunk around.
Since we were being called with the offset chunk address, it meant that
the cached chunk shifted 16 bytes away from its real address every time
we re-added it to the cache.

Eventually the cached chunk address would leave its memory region
entirely, and at that point, any attempt to allocate from it would yield
an address outside the region, causing memory corruption.
2022-11-21 12:37:49 +03:30
MacDue 3483407ddc AK: Return non-const types from Ptr class operators
Even if the pointer value is const, the value they point to is not
necessarily const, so these functions should not add the qualifier.

This also removes the redundant non-const implementations of these
operators.
2022-11-19 14:37:31 +00:00
Timothy Flynn 5d61053276 AK: Add mutable accessors for JsonValue's as_array and as_object 2022-11-18 12:21:57 +00:00
Timothy Flynn 13b18a182a AK: Add JSON object/array for-each methods for fallible callbacks
This allows the provided callback to return an ErrorOr-like type to
propagate errors back to the caller.
2022-11-18 12:21:57 +00:00
Timothy Flynn 56ab529752 AK: Add a concept for requiring that a function is fallible
This ensures that the function may be wrapped with TRY() and MUST().
2022-11-18 12:21:57 +00:00
Ali Mohammad Pur c2b20b5681 AK: Give DisjointChunks::m_chunks an inline capacity of 1
That's one fewer level of indirection for flattened ones.
2022-11-17 20:13:04 +03:30
Ali Mohammad Pur e9b9527440 AK: Add a fast path for DisjointChunks::spans() 2022-11-17 20:13:04 +03:30
Ali Mohammad Pur 48a4c9c1ad AK: Use TypedTransfer to move vector's inline buffer
This avoids an explicit loop-move when the type is trivial.
2022-11-17 20:13:04 +03:30
Ali Mohammad Pur 6970bf03a9 AK: Mark Span<T> as trivial 2022-11-17 20:13:04 +03:30
Ali Mohammad Pur f59bd33876 AK: Allow DisjointChunks::spans to return a vector with inline capacity 2022-11-17 20:13:04 +03:30
Ali Mohammad Pur bee9412ae4 AK: Align last bump allocated chunk's end offset to the type size too
Otherwise we can end up freeing garbage memory with some type sizes.
2022-11-17 20:13:04 +03:30
Timothy Flynn 09c59ee7c0 AK: Support taking JSON values out of a JSON array 2022-11-13 16:41:07 +00:00
Sam Atkins cf046dbfdb AK: Add optional explicit cast to underlying type to DistinctNumeric 2022-11-11 17:50:53 +03:30
Sam Atkins c33eae24f9 AK+Everywhere: Replace DistinctNumeric bool parameters with named ones
This means that rather than this:

```
AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, true, true, false, false,
    false, true, FunctionAddress);
```

We now have this:
```
AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, FunctionAddress, Arithmetic,
    Comparison, Increment);
```

Which is a lot more readable. :^)

Co-authored-by: Ali Mohammad Pur <mpfard@serenityos.org>
2022-11-11 17:50:53 +03:30
Zaggy1024 a1300d3797 AK: Don't crash in HashTable::clear_with_capacity on an empty table
When calling clear_with_capacity on an empty HashTable/HashMap, a null
deref would occur when trying to memset() m_buckets. Checking that it
has capacity before clearing fixes the issue.
2022-11-11 00:44:04 -07:00
Ali Mohammad Pur 40b07901ac AK: Allow Variant::downcast<OtherVariantType>()
We usually give type aliases to variants, so their variant types are not
always available, so make it possible to downcast to another variant
type.
2022-11-10 16:02:42 +03:30
Nico Weber 6911c5545c Everywhere: Fix a few comment typos 2022-11-09 16:00:32 +00:00
Timothy Flynn 3994a79718 AK+LibIPC: Add a convenience encoder/decoder for JsonValue
This requires that JsonValue is implicitly default-constructible.
2022-11-08 19:58:34 -05:00
Daniel Bertalan 4296425bd8 Everywhere: Remove redundant inequality comparison operators
C++20 can automatically synthesize `operator!=` from `operator==`, so
there is no point in writing such functions by hand if all they do is
call through to `operator==`.

This fixes a compile error with compilers that implement P2468 (Clang
16 currently). This paper restores the C++17 behavior that if both
`T::operator==(U)` and `T::operator!=(U)` exist, `U == T` won't be
rewritten in reverse to call `T::operator==(U)`. Removing `!=` operators
makes the rewriting possible again.
See https://reviews.llvm.org/D134529#3853062
2022-11-06 10:25:08 -07:00
Dan Klishch 73f4cfa930 AK: Introduce fixed-width floating point types (f32, f64, f80 and f128) 2022-11-05 16:04:12 -06:00
Dan Klishch 59e87cc998 AK: Add static_assert to check for effective size of long double 2022-11-03 20:17:09 -06:00
Dan Klishch fdc53a5995 AK: Add framework for a unified floating point to string conversion
Currently, the floating point to string conversion is implemented
several times across the codebase. This commit provides a pretty
low-level function to unify all of such conversions. It converts the
given double to a fixed point decimal satisfying a few correctness
criteria.
2022-11-03 20:17:09 -06:00
Dan Klishch 17c9a3e8d9 AK+LibC+LibCrypto: Move FloatExtractor to AK/FloatingPoint.h 2022-11-03 20:17:09 -06:00
Nico Weber daeaefad17 Everywhere: Clean up "the the" comment typos 2022-11-03 17:38:32 +00:00
Dennis Bonke ccb5151291 AK: Add support for mlibc in URL 2022-11-02 22:19:12 -06:00
Dennis Bonke b4b7264fa5 AK: Add support for mlibc in LexicalPath 2022-11-02 22:19:12 -06:00
Timothy Flynn 6d15cbd411 AK: Use size_t for ByteBuffer offsets
These should be unsigned values.

An east-const conversion was also performed by clang-format 15.
2022-11-01 14:52:59 +00:00
Gunnar Beutner a9888d4ea0 AK+Kernel: Handle some allocation failures in IPv4Socket and TCPSocket
This adds try_* methods to AK::SinglyLinkedList and
AK::SinglyLinkedListWithCount and updates the network stack to use
those to gracefully handle allocation failures.

Refs #6369.
2022-11-01 14:31:48 +00:00
Gunnar Beutner ab8b043684 AK+Kernel: Handle allocation failures in Device::try_make_request
This adds try_* methods to AK::DoublyLinkedList and updates the Device
class to use those to gracefully handle allocation failures.

Refs #6369.
2022-11-01 14:31:34 +00:00
Gunnar Beutner e44ccddba3 AK+Kernel: Don't allow allocations in AK::Function in kernel mode
Refs #6369.
Fixes #15053.

Co-authored-by: Brian Gianforcaro <bgianf@serenityos.org>
2022-11-01 12:07:15 +00:00
Gunnar Beutner d1bc157e9f AK: Allow destruction of JsonObjectSerializer objects after errors
Previously we'd VERIFY() that the user had called finish(). This makes
the following code incorrect though:

auto json = TRY(JsonObjectSerializer<>::try_create(builder));
TRY(json.add("total_time"sv, total_time_scheduled.total));
TRY(json.finish());
return ...;

If the second TRY() returns early we'd fail at the VERIFY() call in the
destructor.

Calling finish() in the destructor - like we had done earlier - is also
not helpful because we have no idea whether the builder is still valid.
Plus we wouldn't be able to handle any errors for that call.

Verifying that either finish() was called or an error occurred doesn't
work either because the caller might have multiple Json*Serializer
objects, e.g. when inserting a JSON array into a JSON object. Forcing
the user to call finish() on their "main" object when a sub-object
caused an error seems unnecessarily tedious.
2022-11-01 11:57:08 +00:00
Zaggy1024 353e1c2b4d LibVideo: Add PlaybackManager to load and decode videos
This file will be the basis for abstracting away the out-of-thread or
later out-of-process decoding from applications displaying videos. For
now, the demuxer is hardcoded to be MatroskaParser, since that is all
we support so far. The demuxer should later be selected based on the
file header.

The playback and decoding are currently all done on one thread using
timers. The design of the code is such that adding threading should
be trivial, at least based on an earlier version of the code. For now,
though, it's better that this runs in one thread, as the multithreaded
approach causes the Video Player to lock up permanently after a few
frames are decoded.
2022-10-31 14:47:13 +01:00
Linus Groh 4db85493e8 AK+Meta: Add WEB_FETCH_DEBUG macro 2022-10-30 20:10:29 +00:00
demostanis 7c33f8f7df AK: Add SplitBehavior::KeepTrailingSeparator with tests 2022-10-24 23:29:18 +01:00
demostanis 3e8b5ac920 AK+Everywhere: Turn bool keep_empty to an enum in split* functions 2022-10-24 23:29:18 +01:00
davidot c9aa664eb0 AK: Make the JsonParser use the new double parser for numbers
Because we still support u64 and i64 (on top of i32 and u32) we do still
have to parse the number ourself first. Then if we determine that the
number is a floating point or is outside of the range of i64 and u64 we
fallback and parse it as a double.

Before JsonParser had ifdefs guarding the double computation, but it
just build when we error on ifdef KERNEL so JsonParser is no longer
usable in the Kernel. This can be remedied fairly easily but since
it is not needed we #error on that for now.
2022-10-23 15:48:45 +02:00
davidot 6fd8e96d53 AK: Add to_{double, float} convenience functions to all string types
These are guarded with #ifndef KERNEL, since doubles (and floats) are
not allowed in KERNEL mode.
In StringUtils there is convert_to_floating_point which does have a
template parameter incase you have a templated type.
2022-10-23 15:48:45 +02:00
davidot 2334cd85a2 AK: Add an exact and fast hex float parsing algorithm
Similar to decimal floating point parsing the current strtod hex float
parsing gives a lot of incorrect results. We can use a similar technique
as with decimal parsing however hex floats are much simpler as we don't
need to scale with a power of 5.

For hex floats we just provide the parse_first_hexfloat API as there is
currently no need for a parse_hexfloat_completely API.

Again the accepted input for parse_first_hexfloat is very lenient and
any validation should be done before calling this method.
2022-10-23 15:48:45 +02:00
davidot 53b7f5e6a1 AK: Add an exact and fast floating point parsing algorithm
This is based on the paper by Daniel Lemire called
"Number parsing at a Gigabyte per second", currently available at
https://arxiv.org/abs/2101.11408
An implementation can be found at
https://github.com/fastfloat/fast_float

To support both strtod like methods and String::to_double we have two
different APIs. The parse_first_floating_point gives back both the
result, next character to read and the error/out of range status.
Out of range here means we rounded to infinity 0.

The other API, parse_floating_point_completely, will return a floating
point only if the given character range contains just the floating point
and nothing else. This can be much faster as we can skip actually
computing the value if we notice we did not parse the whole range.

Both of these APIs support a very lenient format to be usable in as many
places as possible. Also it does not check for "named" values like
"nan", "inf", "NAN" etc. Because this can be different for every usage.

For integers and small values this new method is not faster and often
even a tiny bit slower than the current strtod implementation. However
the strtod implementation is wrong for a lot of values and has a much
less predictable running time.

For correctness this method was tested against known string -> double
datasets from https://github.com/nigeltao/parse-number-fxx-test-data
This method gives 100% accuracy.
The old strtod gave an incorrect value in over 50% of the numbers
tested.
2022-10-23 15:48:45 +02:00
davidot bf6d4a5cbf AK: Make truncating UFixedBigInts constexpr
Also add some tests and shift tests while we're at it.
2022-10-23 15:48:45 +02:00
Timothy Flynn b9dc0b7d1b AK: Do not append string bytes as code points when title-casing a string
By appending individual bytes as code points, we were "breaking apart"
multi-byte UTF-8 code points. This now behaves the same way as the
invert_case() helper in StringUtils.
2022-10-20 18:55:43 +02:00
Timon Kruiper c7aa05cdcc Kernel/aarch64: Initialize TimeManagement in init.cpp
Also remove the check for aarch64 in AK/Format.cpp, so now the format
functions will prepend the time since boot!
2022-10-17 20:11:31 +02:00
Paul Herman d989c50c90 AK: Document the non-standard extensions in TRY
I'm not sure there's a material improvement from this patch. However,
I've been reading the error handling code from multiple projects and
was excited to see Serenity being able to handle assignment
(`auto x = TRY(make_x())`) the same way as actions (`TRY(do_x())`).
I think it's worth documenting that this is only possible due to
non-standard extensions.
2022-10-16 22:05:42 +02:00
Gunnar Beutner 918fdf9e2c Kernel: Add VALIDATE_IS_AARCH64 guard macro 2022-10-16 17:35:37 +02:00
Andrew Kaster 1ca48a2aec AK+Userland: Use a CMake variable for AK_SOURCES instead of GLOB
This lets us remove a glob pattern from LibC, the DynamicLoader, and,
later, Lagom. The Kernel already has its own separate list of AK files
that it wants, which is only a subset of all AK files.
2022-10-16 16:36:39 +02:00
Undefine 9718667bcf AK: Add StringView::find_last_not 2022-10-14 18:36:40 -06:00
Timothy Flynn d007337d97 AK: Explictly disallow lvalue reference types within Variant
This prevents an ICE with GCC trying to declare e.g. Variant<String&>.

Using a concept is a bit overkill here, but clang otherwise trips over
the friendship declaration to other Variant types:

    template<typename... NewTs>
    friend struct Variant;

Without using a concept, clang believes this is re-declaring the Variant
type with differing requirements ("error: requires clause differs in
template redeclaration").
2022-10-15 01:26:14 +02:00
demostanis aa788581f2 AK: Make StringUtils::matches() handle escaping 2022-10-14 13:37:29 +02:00
Gunnar Beutner 7a8206197e AK: Stub out the NAKED macro on AARCH64
This is almost certainly incorrect but we'll see about that once
the kernel actually gets to userspace init.
2022-10-14 13:01:13 +02:00
Gunnar Beutner a650c74b27 AK+Toolchain: Make char and wchar_t behave on AARCH64
By default char and wchar_t are unsigned on AARCH64. This fixes a
bunch of related compiler errors.
2022-10-14 13:01:13 +02:00
Gunnar Beutner 31bd5b1a02 AK+Userland: Stub out code that isn't currently implemented on AARCH64
Even though this almost certainly wouldn't run properly even if we had
a working kernel for AARCH64 this at least lets us build all the
userland binaries.
2022-10-14 13:01:13 +02:00
Hendiadyoin1 a143d666db AK: Fix aarch64 versions of math functions
These were incorrectly assumed to compile, but did indeed still have
a few issues.
2022-10-14 11:06:28 +02:00
Hendiadyoin1 eb5651870e AK: Add support for some trivial math functions on aarch64
These all require just a single instruction each, we only have to
differentiate between register prefixes accordingly.
2022-10-14 00:28:34 +02:00
Al Hoang d7d50d6d9e AK: Fix FreeBSD compilation for clock
FreeBSD introduced CLOCK_MONOTONIC_COARSE and CLOCK_REALTIME_COARSE.
This update fixes ladybird builds from FreeBSD 13.1

see clock_gettime(2) https://www.freebsd.org/cgi/man.cgi?query=clock_gettime&apropos=0&sektion=0&manpath=FreeBSD+13.1-RELEASE&arch=default&format=ascii
2022-10-12 23:12:13 -06:00
Sam Atkins 80603f141a WebDriver: Add new WebDriver service
WebDriver aims to implement the WebDriver specification found at
https://w3c.github.io/webdriver/webdriver-spec.html . It's an HTTP
server that can create Browser sessions and control them.

Co-authored-by: Florent Castelli <florent.castelli@gmail.com>
2022-10-12 23:07:42 +02:00
Sam Atkins a0d44026fc AK+Tests: Correct off-by-one error when right-trimming text
If the entire string you want to right-trim consists of characters you
want to remove, we previously would incorrectly leave the first
character there.

For example: `trim("aaaaa", "a")` would return "a" instead of "".

We can't use `i >= 0` in the loop since that would fail to detect
underflow, so instead we keep `i` in the range `size .. 1` and then
subtract 1 from it when reading the character.

Added some trim() tests while I was at it. (And to confirm that this was
the issue.)
2022-10-11 17:49:32 +02:00
Andrew Kaster 1d533acbc0 AK+Userland: Replace Linux, macOS, and *BSD macros with platform defines
We have such nice platform macros, let's clean up any remnants of manual
__my_platform__ macros in LibCore, LibCompress and AK.
2022-10-10 12:23:12 +02:00
Andrew Kaster 828441852f Everywhere: Replace uses of __serenity__ with AK_OS_SERENITY
Now that we have OS macros for essentially every supported OS, let's try
to use them everywhere.
2022-10-10 12:23:12 +02:00
Ben Wiederhake dc71e1e264 AK: Fix 'constexpr' attribute on non-constexpr function
is_url_code_point invokes StringView::contains, which never was and
cannot become constexpr.
2022-10-09 10:37:20 -06:00
Ben Wiederhake ff8f3814cc AK+Tests: Avoid creating invalid code points from malformed UTF-8
Instead of doing anything reasonable, Utf8CodePointIterator returned
invalid code points, for example U+123456. However, many callers of this
iterator assume that a code point is always at most 0x10FFFF.

In fact, this is one of two reasons for the following OSS Fuzz issue:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49184
This is probably a very old bug.

In the particular case of URLParser, AK::is_url_code_point got confused:
    return /* ... */ || code_point >= 0xA0;
If code_point is a "code point" beyond 0x10FFFF, this violates the
condition given in the preceding comment, but satisfies the given
condition, which eventually causes URLParser to crash.

This commit fixes *only* the erroneous UTF-8 decoding, and does not
fully resolve OSS-Fuzz#49184.
2022-10-09 10:37:20 -06:00
Ben Wiederhake 3aeb57ed09 AK+Everywhere: Fix data corruption due to code-point-to-char conversion
In particular, StringView::contains(char) is often used with a u32
code point. When this is done, the compiler will for some reason allow
data corruption to occur silently.

In fact, this is one of two reasons for the following OSS Fuzz issue:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=49184
This is probably a very old bug.

In the particular case of URLParser, AK::is_url_code_point got confused:
    return /* ... */ || "!$&'()*+,-./:;=?@_~"sv.contains(code_point);
If code_point is a large code point that happens to have the correct
lower bytes, AK::is_url_code_point is then convinced that the given
code point is okay, even if it is actually problematic.

This commit fixes *only* the silent data corruption due to the erroneous
conversion, and does not fully resolve OSS-Fuzz#49184.
2022-10-09 10:37:20 -06:00
Timothy Flynn e897008449 AK: Change ErrorOr to contain a Variant rather than inherit from it
GCC seems to get tripped up over this inheritance when converting from
an ErrorOr<StringView> to the partially specialized ErrorOr<void>. See
the following snippet:

    NEVER_INLINE ErrorOr<StringView> foo()
    {
        auto string = "abc"sv;
        outln("{:p}", string.characters_without_null_termination());
        return string;
    }

    NEVER_INLINE ErrorOr<void> bar()
    {
        auto string = TRY(foo());
        outln("{:p}", string.characters_without_null_termination());

        VERIFY(!string.starts_with('#'));
        return {};
    }

    int main()
    {
        MUST(bar());
    }

On some machines, bar() will contain a StringView whose pointer has had
its upper bits set to 0:

    0x000000010cafd6f8
    0x000000000cafd6f8

I'm not 100% clear on what's happening in the default-generated Variant
destructor that causes this. Probably worth investigating further.

The error would also be alleviated by making the Variant destructor
virtual, but rather than that, let's make ErrorOr simply contain a
Variant rather than inherit from it.

Fixes #15449.
2022-10-07 18:21:40 +01:00
Andreas Kling da781e90c1 AK: Print VERIFY() error messages in release builds
Until now, VERIFY() failures would just cause a __builtin_trap() in
release builds, which made them a bit too harsh. This commit adds an
out-of-line helper function that prints the error before trapping.
2022-10-06 15:29:38 +02:00
Nico Weber 2af028132a AK+Everywhere: Add AK_COMPILER_{GCC,CLANG} and use them most places
Doesn't use them in libc headers so that those don't have to pull in
AK/Platform.h.

AK_COMPILER_GCC is set _only_ for gcc, not for clang too. (__GNUC__ is
defined in clang builds as well.) Using AK_COMPILER_GCC simplifies
things some.

AK_COMPILER_CLANG isn't as much of a win, other than that it's
consistent with AK_COMPILER_GCC.
2022-10-04 23:35:07 +01:00
Andreas Kling 74840c5537 AK: Add more AK_OS_FOO macros, including AK_OS_SERENITY 2022-10-02 21:14:02 +02:00
Daniel Bertalan 01c2cffcca AK: Fix naming conflict with compiler builtin
Clang patch D116203 added various builtin functions for type traits,
`__decay` being one of them. This name conflicts with our
`AK::Detail::__decay`, leading to compiler warnings with Clang 16.
2022-10-01 20:39:48 +02:00
Nico Weber a934fa3d28 AK: Fix a comment typo 2022-09-30 20:09:26 -07:00
Diego Iastrubni 58a44036a9 Lagom: Fix printf implementation on win32
It seems that Filip has already done the hard work, and found out the
implementation different between unix* and windows.

Borrowed from:
https://github.com/SerenityOS/serenity/compare/master...filiphsps:serenity:dev-win32#diff-e3209c9a434a102d0d9459e31e33ddb729dff925b95f41b9d1e56c1e7f88c487R466

Co-authored-by: Filiph Sandström <filiph.sandstrom@filfatstudios.com>
2022-09-29 17:01:22 +01:00
Diego Iastrubni 18257604eb Lagom: Win32 support baby steps
This is the initial port of Lagom to win32. This will enable developers
to use Lagom as an alternative to vanilla STL/StandardC++Library - which
gives a much richer environment (think QtCore - but modern).

My main incentive - is to have a native Windows Ladybird working.

I am starting with AK, which does not yet fully compile (on mingw). When
AK is compiling (currently fails building StringBuffer.cpp) - I will
continue to LibCore and then the rest of the user space libraries
(excluding the GUI, which will be another different effort).

Most of the code is happily stollen from Andrew Kaster's fork - he
deserves the credit.

Co-authored-by: Andrew Kaster <akaster@serenityos.org>
2022-09-29 17:01:22 +01:00
networkException 4230dbbb21 AK+Everywhere: Replace "protocol" with "scheme" url helpers
URL had properly named replacements for protocol(), set_protocol() and
create_with_file_protocol() already. This patch removes these function
and updates all call sites to use the functions named according to the
specification.

See https://url.spec.whatwg.org/#concept-url-scheme
2022-09-29 09:39:04 +01:00
Timothy Flynn 5f9d8f25c6 AK+Meta: Define a debug flag for LibTimeZone 2022-09-28 23:52:51 +01:00
Lucas CHOLLET 42518867d7 AK: Make ErrorOr::error() const and return a const reference 2022-09-27 21:29:44 +01:00
Lucas CHOLLET 0396b6da82 AK: Add StringView operator==(char) 2022-09-27 21:29:44 +01:00
Linus Groh edfef8e2f5 Everywhere: Rename WrapperGenerator to BindingsGenerator
This code generator no longer creates JS wrappers for platform objects
in the old sense, instead they're JS objects internally themselves.
Most of what we generate now are prototypes - which can be seen as
bindings for the internal C++ methods implementing getters, setters, and
methods - as well as object constructors, i.e. bindings for the internal
create_with_global_object() method.

Also tweak the naming of various CMake glue code existing around this.
2022-09-21 23:06:08 +01:00
Daniel Bertalan 2b69af2dfe AK+LibJS: Handle NaN-boxing pointers on AArch64
JS::Value stores 48 bit pointers to separately allocated objects in its
payload. On x86-64, canonical addresses have their top 16 bits set to
the same value as bit 47, effectively meaning that the value has to be
sign-extended to get the pointer. AArch64, however, expects the topmost
bits to be all zeros.

This commit gates sign extension behind `#if ARCH(X86_64)`, and adds an
`#error` for unsupported architectures, so that we do not forget to
think about pointer handling when porting to a new architecture.

Fixes #15290
Fixes SerenityOS/ladybird#56
2022-09-21 11:55:57 +02:00
Andreas Kling 287a9b552a AK: Fix bad parsing of some file:/// URLs with base URL
We were dropping the base URL path components in the resulting URL due
to mistakenly determining the input URL to start with a Windows drive
letter. Fix this, add a spec link, and a test.
2022-09-20 15:38:53 +02:00
Timothy Flynn 11bd6c3d68 AK: Do not require an allocated String for fuzzy matching
A StringView is sufficient here. This also removes the declaration of
fuzzy_match_recursive from the header, as it's only needed from within
the implementation file.
2022-09-20 11:08:54 +01:00
Ben Wiederhake 9c75d9e2cb AK: Move heavyweight fuzzy matching to own compilation unit 2022-09-18 13:27:24 -04:00
Tim Schumacher 643d2a683b AK: Define both ::nullptr_t and std::nullptr_t
LLVM 15 switched around what it's basing its `nullptr_t` definitions on,
it's now defining `std::nullptr_t` using `::nullptr_t` instead of the
other way around.

Work around any errors that result from that by just defining it both in
the global namespace as well as in `std` ourselves.
2022-09-16 05:39:28 +00:00
Lucas CHOLLET 62b8ccaffc StringBuilder: Add try_append_repeated() and append_repeated()
This two methods add the character as many times as specified by the
second parameter.
2022-09-15 14:08:21 +01:00
Sam Atkins 32c99313a6 AK: Warn when trying to set @foo@ as a SourceGenerator key
I was very confused why I was getting "no key named `foo`" errors, so
hopefully this will save someone that confusion in the future. :^)

(It'll probably be me again...)
2022-09-09 15:18:07 +02:00
Sam Atkins edc3ed2a0e AK: Allow creating NonnullPtrVectors from an initializer list
This was present in Vector already. Clang-format fixed some const
positions automatically too.

Also removed a now-ambiguous and unnecessary constructor from Shell.
2022-09-08 18:53:08 +02:00
Andreas Kling 53c0038d2c AK: Make Weakable non-atomic
Let's not punish single-threaded workloads with the performance cost of
atomic weakables. The kernel keeps using LockWeakable.
2022-09-03 00:36:25 +02:00
davidot 75ebcf6b4a AK: Allow exponents in JSON double values
This is required for ECMA-404 compliance, but probably not for serenity
itself.
2022-09-02 02:07:37 +01:00
Liav A 13c8695523 AK: Add find_first_split_view() helper for StringView container
Similar to the find_last_split_view() helper, but in this helper we
search for the first split view instead of the last one.
2022-08-30 00:50:15 +01:00
Jelle Raaijmakers 8483064b59 AK: Add FloatingPoint.h
This is a set of functions that allow you to convert between arbitrary
IEEE 754 floating point types, as long as they can be represented
within 64 bits. Conversion methods between floats and doubles are
provided, as well as a generic `float_to_float()`.

Example usage:

  #include <AK/FloatingPoint.h>

  double val = 1.234;
  auto weird_f16 =
      convert_from_native_double<FloatingPointBits<0, 6, 10>>(val);

Signed and unsigned floats are supported, and both NaN and +/-Inf are
handled correctly. Values that do not fit in the target floating point
type are clamped.
2022-08-27 12:28:05 +02:00
Andreas Kling f03f70a84a AK: Make empty FixedArray smaller
Move the FixedArray's size field into the heap-allocated storage. This
makes zero-sized FixedArrays take up 8 bytes instead of 16.
2022-08-27 12:19:37 +02:00
Andreas Kling 11eee67b85 Kernel: Make self-contained locking smart pointers their own classes
Until now, our kernel has reimplemented a number of AK classes to
provide automatic internal locking:

- RefPtr
- NonnullRefPtr
- WeakPtr
- Weakable

This patch renames the Kernel classes so that they can coexist with
the original AK classes:

- RefPtr => LockRefPtr
- NonnullRefPtr => NonnullLockRefPtr
- WeakPtr => LockWeakPtr
- Weakable => LockWeakable

The goal here is to eventually get rid of the Lock* classes in favor of
using external locking.
2022-08-20 17:20:43 +02:00
Andreas Kling e475263113 AK+Kernel: Add AK::AtomicRefCounted and use everywhere in the kernel
Instead of having two separate implementations of AK::RefCounted, one
for userspace and one for kernelspace, there is now RefCounted and
AtomicRefCounted.
2022-08-20 17:15:52 +02:00
kleines Filmröllchen 4809dc8ec2 AK: Add Singleton special-case constructor for SpinlockProtected
This will allow Singletons of that class to still be created when
SpinlockProtected can't be constructed without a lock rank argument
anymore.
2022-08-19 20:26:47 -07:00
davidot 8be96cd7ff AK: Allow bit_cast to be used in constant evaluated context 2022-08-15 17:11:25 +02:00
thankyouverycool 75b6097c55 AK: Add human_readable_digital_time() helper
Converts seconds into a readable digital format. For example:
30 seconds	= "00:30"
90 seconds	= "01:30"
86401 seconds	= "24:00:01"
And so on.
2022-08-05 13:55:13 +02:00
Andreas Kling b6307f73a2 AK: Suppress -Wunqualified-std-cast-call in the CLion IDE 2022-08-05 12:42:46 +02:00
Brian Gianforcaro ea9ef33a7f AK: Prefix CACHE_ALIGNED & SYSTEM_CACHE_ALIGNMENT_SIZE 2022-08-01 00:19:16 +02:00
Filiph Sandström 5a281336c5 AK: Fix usage of undefined variables
The commit that introduced BuiltinWrappers (548529a) accidentally used
`val` instead of `value` in the non `__GNUC__` and `__clang__` versions
of the functions.
2022-07-31 11:08:33 +02:00
MacDue 13406b83b1 AK: VERIFY() the index is in bounds in StringView::operator[]
That this did not already happen took me by surprise, as for
most other similar containers/types in AK (e.g. Span) the index
will be checked. This check not happening could easily let
off-by-one indexing errors slip through the cracks.
2022-07-26 12:41:46 +02:00
Linus Groh 8150d71821 Everywhere: Prefix 'TYPEDEF_DISTINCT_ORDERED_ID' with 'AK_' 2022-07-22 23:09:43 +01:00
Linus Groh 5a106b6401 Everywhere: Prefix 'TYPEDEF_DISTINCT_NUMERIC_GENERAL' with 'AK_' 2022-07-22 23:09:43 +01:00
kleines Filmröllchen 500dc83f32 AK: Add FixedArray::fill_with
This is a memset-like utility method.
2022-07-22 19:35:41 +01:00
kleines Filmröllchen 5b1345a4ff AK: Remove FixedArray::must_create_but_fixme_should_propagate_errors
Nobody was using this anymore.
2022-07-22 19:35:41 +01:00
Samuel Bowman 25de9de7dc Kernel+LibPartition: Move GUIDPartitionTable into LibPartition 2022-07-21 20:13:44 +01:00
Samuel Bowman 1a6ef03e4a Kernel+LibPartition: Move MBRPartitionTable into LibPartition 2022-07-21 20:13:44 +01:00
Daniel Bertalan 42e22f89a4 AK+LibGfx+LibJS: Pass -1 as the file descriptor to anonymous mmap
Serenity/Linux/macOS ignore the file descriptor when an anonymous
mapping is requested. However, BSDs require the fd to be -1.
2022-07-19 12:39:24 +02:00
Daniel Bertalan ae4d871183 AK: Port StackInfo to FreeBSD
This can almost be identical to the Linux version, except that the
`pthread_attr_t` object is populated using a call to
`pthread_attr_get_np` instead of `pthread_getattr_np`.

FreeBSD also needs `pthread_atttr_t` to be initialized using
`pthread_attr_init` instead of zero-initialization, but it's the
technically correct thing to do on Linux as well.
2022-07-19 12:39:24 +02:00
Daniel Bertalan cd0fb6dcc8 AK: Do not negate Pthread error codes for strerror()
On all systems I've checked, pthread functions return the positive error
code directly.
2022-07-19 12:39:24 +02:00
Andrew Kaster 3b15addbc8 AK: Add support for building on Android with API version >= 30 2022-07-19 10:44:02 +01:00
Hendiadyoin1 154871834b AK: Add a helper to get the last split-group 2022-07-15 12:42:43 +02:00
Ali Mohammad Pur 0d6dc74951 AK: Use the correct data types in bitap_bitwise()
Otherwise the bit twiddling goes all wrong and breaks some boundary
cases.
Fixes `StringView::contains(31-chars)`.
2022-07-14 13:10:23 +02:00
Linus Groh 3953004e60 AK: Add Traits<ByteBuffer>::hash() 2022-07-14 00:42:26 +01:00
sin-ack 5744211001 AK: Remove StringView(char const*) :^)
This constructor relied on running strlen implicitly on its argument,
thereby potentially causing out-of-bound reads (some of which were
caught a few days ago). The removal of this constructor ensures that the
caller must explicitly pass the size of the string by either:

1) Using operator""sv on literal strings; or
2) Calling strlen explicitly, making it clear that the size of the view
   is being calculated at runtime.
2022-07-12 23:11:35 +02:00
sin-ack 604aac531c AK+Userland+Tests: Remove URL(char const*) constructor
The StringView(char const*) constructor is being removed, and there was
only a few users of this left, which are also cleaned up in this commit.
2022-07-12 23:11:35 +02:00
sin-ack 3f8060d859 AK: Remove String <-> char const* comparison operators
During the removal of StringView(char const*), all users of these
functions were removed, and they are of dubious value (relying on
implicit StringView conversion).
2022-07-12 23:11:35 +02:00
sin-ack c8585b77d2 Everywhere: Replace single-char StringView op. arguments with chars
This prevents us from needing a sv suffix, and potentially reduces the
need to run generic code for a single character (as contains,
starts_with, ends_with etc. for a char will be just a length and
equality check).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack 3f3f45580a Everywhere: Add sv suffix to strings relying on StringView(char const*)
Each of these strings would previously rely on StringView's char const*
constructor overload, which would call __builtin_strlen on the string.
Since we now have operator ""sv, we can replace these with much simpler
versions. This opens the door to being able to remove
StringView(char const*).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack e5f09ea170 Everywhere: Split Error::from_string_literal and Error::from_string_view
Error::from_string_literal now takes direct char const*s, while
Error::from_string_view does what Error::from_string_literal used to do:
taking StringViews. This change will remove the need to insert `sv`
after error strings when returning string literal errors once
StringView(char const*) is removed.

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack c70f45ff44 Everywhere: Explicitly specify the size in StringView constructors
This commit moves the length calculations out to be directly on the
StringView users. This is an important step towards the goal of removing
StringView(char const*), as it moves the responsibility of calculating
the size of the string to the user of the StringView (which will prevent
naive uses causing OOB access).
2022-07-12 23:11:35 +02:00
sin-ack 7da00bfa8d AK: Add string literal helpers to AK::SourceGenerator
Since all uses of SourceGenerator are with literal strings, there is no
need to burden generators with the sv suffix.
2022-07-12 23:11:35 +02:00
sin-ack 6eecc65787 AK: Explicitly calculate length of char* when printing
This moves out the calculation of the char* out to the formatter.
Additionally, we now print (null) when a null pointer is passed.
2022-07-12 23:11:35 +02:00
sin-ack 52d017c611 AK: Make CheckedFormatString pass the char array size to StringView
This makes the assumption that we never pass a stack-allocated char
array to CheckedFormatString arguments (dbgln, outln, warnln). This
assumption seems to hold true for the current state of Serenity code, at
least. :^)
2022-07-12 23:11:35 +02:00
Luke Wilde da25ac0d48 AK: Treat empty string as invalid JSON
Previously we would treat the empty string as `null`. This caused
JavaScript like this to fail:
```js
var object = {};
try {
    object = JSON.parse("");
} catch {}
var array = object.array || [];
```
Since `JSON.parse("")` returned null instead of throwing, it would set
`object` to null and then try and use it instead of using the default
backup value.
2022-07-10 23:31:48 +02:00
Karol Kosek b5420b8a9a LibGfx: Implement PNG filtering on write
Is it another great upgrade to our PNG encoder like in 9aafaec259?
Well, not really - it's not a 2x or 55x improvement like you saw there,
but still it saves something:

- a screenshot of a blank Serenity desktop dropped from about 45 KiB
  to 40 KiB.
- re-encoding NASA photo of the Earth to PNG again saves about 25%
  (16.5 MiB -> 12.3 MiB), compared to not using filters.

[1]: https://commons.wikimedia.org/wiki/File:The_Blue_Marble_(remastered).jpg
2022-07-10 15:01:07 +02:00
kleines Filmröllchen 41b2d37e8a AK: Always check shift amount in LEB128 read functions
Even shifting 0 by more than the value size is UB.
2022-07-09 22:04:31 +00:00
Andreas Kling 2217d91b8d AK: Make VERIFY() work in MinSizeRel builds 2022-07-09 22:15:43 +02:00
Allan Regush 63d06458ca AK: Add equality operators to compare RefPtr to NonNullRefPtr 2022-07-09 09:32:51 +01:00
Allan Regush ce7d868d6b AK: Add comparison operators to NonnullRefPtr 2022-07-09 09:32:51 +01:00
Maciej 36676a1604 AK: Add IPv4Address::netmask_from_cidr 2022-07-09 09:22:25 +01:00
DexesTTP 7ceeb74535 AK: Use an enum instead of a bool for String::replace(all_occurences)
This commit has no behavior changes.

In particular, this does not fix any of the wrong uses of the previous
default parameter (which used to be 'false', meaning "only replace the
first occurence in the string"). It simply replaces the default uses by
String::replace(..., ReplaceMode::FirstOnly), leaving them incorrect.
2022-07-06 11:12:45 +02:00
Idan Horowitz 33214c29d3 AK: Add an align_down_to power of two helper
Matching the similar align_up_to helper
2022-07-05 11:26:10 +02:00