Commit graph

2671 commits

Author SHA1 Message Date
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
FrHun dba6f0bc4b AK: Add header for generic shorthands
These are functions that can be expressed with just normal operators,
but would be very repetetive.
2022-07-04 11:15:40 +02:00
Lenny Maiorani c860d8f5be AK: Add nodiscard attribute to Find functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani ef4b98be52 AK: Add nodiscard attribute to BitStream functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani 97d966d25c AK: Add nodiscard attribute to BitCast functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani 84d9e537cd AK: Add nodiscard attribute to BinarySearch functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani ccbf240962 AK: Add nodiscard attribute to BinaryHeap functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani 56cabf80de AK: Add nodiscard attribute to Base64 functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani 49042bffe9 AK: Add nodiscard attribute to AnyOf functions 2022-07-04 05:53:56 +00:00
Lenny Maiorani 318bee03d8 AK: Add nodiscard attribute to AllOf functions 2022-07-04 05:53:56 +00:00
MacDue 072a78b958 AK: Add AK::ceil(float) and AK::ceil_log2(integer)
Co-authored-by: Leon Albrecht <leon2002.la@gmail.com>
2022-06-30 11:16:22 +02:00
Lucas CHOLLET 3843b8c0a1 AK: Perform a resize in ByteBuffer::get_bytes_for_writing()
ByteBuffer::get_bytes_for_writing() was only ensuring capacity before
this patch. The method needs to call resize to register the appended
data, otherwise it will be overwritten with next data addition.
2022-06-27 20:22:15 +01:00
Ali Mohammad Pur 2104e9a6e4 AK: Recognize __CLION_IDE__ as well as __CLION_IDE_
This used to be `__CLION_IDE_` before, but it seems to have been fixed
in the latest EAP.
2022-06-26 22:21:17 +01:00
kleines Filmröllchen 07d712ea00 AK: Add saturating addition and subtraction to Checked 2022-06-23 23:26:33 +01:00
Hendiadyoin1 5bf84a5b0e AK: Zero previous pointer *after* fixing the insertion list in HashTable 2022-06-23 20:25:12 +03:00
Idan Horowitz eb02425ef9 AK: Clear the previous and next pointers of deleted HashTable buckets
Usually the values of the previous and next pointers of deleted buckets
are never used, as they're not part of the main ordered bucket chain,
but if an in-place rehashing is done, which results in the bucket being
turned into a free bucket, the stale pointers will remain, at which
point any item that is inserted into said free-bucket will have either
a stale previous pointer if the HashTable was empty on insertion, or a
stale next pointer, resulting in undefined behaviour.

This commit also includes a new HashMap test that reproduces this issue
2022-06-22 21:53:13 +02:00
Linus Groh 9e79856b43 Revert "AK: Add comparison operators to NonnullOwnPtr"
This reverts commit 50c88e5e3a.

The intention was to add them to NonnullRefPtr, not NonnullOwnPtr. That
is also what was advertised in the PR, but not actually done in the
reverted commit.
2022-06-18 13:17:49 +01:00
Allan Regush 50c88e5e3a AK: Add comparison operators to NonnullOwnPtr 2022-06-18 02:11:08 +01:00
Andreas Kling 75dca629df AK+Kernel: Remove RefPtrTraits template param in userspace code
Only the kernel actually uses RefPtrTraits, so let's not burden
userspace builds with the complexity.
2022-06-15 17:15:04 +02:00
Andreas Kling 9e994da2ac Kernel+AK: Split Weakable.h into userspace and kernel variants
Only the kernel expects AK::Weakable to lock its refcount manipulation,
so let's not force userspace to pay for that as well.
2022-06-15 17:15:04 +02:00
Hediadyoin1 e6a3cac5ce AK: Add sqrt(2) and sqrt(1/2) constants 2022-06-14 23:00:52 +02:00
Luke Wilde 076c9772a4 LibWeb: Add ability to present LibGL framebuffer and add clearing 2022-06-13 21:45:27 +01:00
Matthias Zimmerman c10d48b72c AK/ByteBuffer+Everywhere: Handle errors in ByteBuffer::slice() 2022-06-13 15:38:51 +01:00
Karol Kosek 65afa113e5 AK: Make URL ApplicationXWWWFormUrlencoded encoding closer to spec
It was mostly implemented based on a spec note, that described only
allowed characters, but instead of allowing some special characters not
to be escaped, we escaped every special character except those 'new in
this encode set' disallowed characters from the spec definition.
2022-06-10 22:32:29 +01:00
Karol Kosek 9e69a89f8e AK: Append correct number of port characters when serializing a URL
Instead of formatting a port string, it put bytes from stack, using the
port number as a length (so for port 8000 it appended 8000 bytes).
2022-06-10 22:32:29 +01:00
Tim Schumacher b3e0aed91f AK: Add SinglyLinkedList::prepend() 2022-06-10 19:06:46 +01:00
Lucas CHOLLET dad4716cc2 AK: Add Error::operator==(Error const&) 2022-06-09 22:08:04 +02:00
huttongrabiel 8ffa860bc3 AK: Add invert_case() and invert_case(StringView)
In the given String, invert_case() swaps lowercase characters with
uppercase ones and vice versa.
2022-05-26 21:51:23 +01:00
Ali Mohammad Pur 06c6c046f3 AK: Use static_cast to cast to base type
This is an issue on systems that don't have the empty base class
optimisation (such as windows), and we normally don't need to care -
however static_cast is technically the right thing to use, so let's use
that instead.

Co-Authored-By: Daniel Bertalan <dani@danielbertalan.dev>
2022-05-21 02:18:40 +02:00
Daniel Bertalan 014b9fd709 AK+DHCPClient: Fix false positive gcc 12 warnings
The compiler would complain about `__builtin_memcpy` in ByteBuffer::copy
writing out of bounds, as it isn't able to deduce the invariant that the
inline buffer is only used when the requested size is smaller than the
inline capacity.

The other change is more bizarre. If the destructor's declaration
exists, gcc complains about a `delete` operation causing an
out-of-bounds array access.

error: array subscript 'DHCPv4Client::__as_base [0]' is partly outside
array bounds of 'unsigned char [8]' [-Werror=array-bounds]
   14 |   ~DHCPv4Client() = default;
      |   ^

This looks like a compiler bug, and I'll report it if I find a suitable
reduced reproducer.
2022-05-12 13:12:37 +02:00
Jelle Raaijmakers 2c381ea45c AK: Add clamp(f32x4, float, float)
We are allowed to directly compare `f32x4` with a `float`, so make use
of it.
2022-05-09 21:49:48 +02:00
Vitaly Dyachkov a0a4d169f4 AK+LibGUI: Pass predicate to *_matching() methods by const reference 2022-05-08 17:02:00 +02:00
EWouters 0317882b61 AK: Use AK:: sin and cos on aarch64 build
This fixes the lagom build on aarch64, as `__builtin_sincosf` doesn't
take double arguments.
2022-05-08 16:51:23 +02:00
EWouters 6ea89c35fe AK: Use builtin versions of llrint{,l,f}
This fixes the build on M1 Macs.
2022-05-07 23:36:49 +02:00
Hendiadyoin1 d4fe02152a AK: Add an SSE2 specific implementation of sqrt(double) 2022-05-07 20:27:05 +02:00
Hendiadyoin1 6d9bc87903 AK: Add a cpp-y, more fine grained version of fenv.h: FPControl.h
This allows direct inlining and hides away some assembly and
bit-fiddling when manipulating the floating point environment.

This only implements the x87/SSE versions, as of now.
2022-05-07 20:27:05 +02:00
Hendiadyoin1 37ff2b9bd2 AK: Add an helper for quick hardware based rounding
This uses the `fistp` and `cvts[sd]2si` respectively, to potentially
round floating point values with just one instruction.

This falls back to `llrint[fl]?` on aarch64 for now.
2022-05-07 20:25:39 +02:00
kleines Filmröllchen df57536c40 AK: Put invalid UTF8 debug spam behind a flag
This is very annoying if we're (intentionally) passing invalid UTF8 into
Utf8View.
2022-04-27 00:02:24 +02:00
Andrew Kaster 83603d68d2 AK: Make sure we don't include Math.h or math.h from KERNEL 2022-04-23 10:43:32 -07:00
kleines Filmröllchen 6b13436ef6 LibCore: Introduce SharedSingleProducerCircularQueue
This new class with an admittedly long OOP-y name provides a circular
queue in shared memory. The queue is a lock-free synchronous queue
implemented with atomics, and its implementation is significantly
simplified by only accounting for one producer (and multiple consumers).
It is intended to be used as a producer-consumer communication
datastructure across processes. The original motivation behind this
class is efficient short-period transfer of audio data in userspace.

This class includes formal proofs of several correctness properties of
the main queue operations `enqueue` and `dequeue`. These proofs are not
100% complete in their existing form as the invariants they depend on
are "handwaved". This seems fine to me right now, as any proof is better
than no proof :^). Anyways, the proofs should build confidence that the
implemented algorithms, which are only roughly based on existing work,
operate correctly in even the worst-case concurrency scenarios.
2022-04-21 13:55:00 +02:00
kleines Filmröllchen 65b338ad04 AK: Allow alignment to cache line size with CACHE_ALIGNED
This is particularly important to avoid false sharing, which thrashes
performance when two process-shared atomics are on the same cache line.
2022-04-21 13:55:00 +02:00
Tim Schumacher 908d5a2853 AK: Expose RedBlackTree::find_smallest_not_below() 2022-04-21 13:16:56 +02:00
ForLoveOfCats 79a2088a13 AK: Make Vector::contains_slow templated
This allows for calling this function with any argument type for which
the appropriate traits and operators have been implemented so it can be
compared to the Vector's item type
2022-04-21 09:12:37 +04:30
ForLoveOfCats a7fe3183f5 AK: Add URL::create_with_help_scheme helper function 2022-04-21 09:12:37 +04:30
faxe1008 b8bd667782 AK: Add FuzzyMatch header
This patch adds a header containing the fuzzy match algorithm
previously used in Assistant. The algorithm was moved to AK
since there are many places where a search may benefit from fuzzyness.
2022-04-20 18:34:09 +02:00
Ali Mohammad Pur dd370fcdd1 AK: Explicitly instantiate String::to_uint<unsigned long{, long}>()
Instead of just to_uint<u64>().
2022-04-20 00:15:23 +04:30
Ali Mohammad Pur 2b79f36148 AK: Add a OneOfIgnoringCV concept
Some functions want to ignore cv-qualifiers, and it's much easier to
constrain the type through a concept than a separate requires clause on
the function.
2022-04-20 00:15:23 +04:30
Thitat Auareesuksakul f4b8bae65f AK: Add Kernel namespace to KStrings in AK::IPv6Address
Currently there is no AK::IPv6Address in the kernel. But when there is,
KStrings won't resolve properly because they are in Kernel namespace.
2022-04-17 16:57:52 -07:00
Tim Schumacher d6ccee4089 AK: Differ between long and long long formats 2022-04-14 03:12:56 +04:30
Tim Schumacher fbfa378e74 AK: Deduplicate formatting hexadecimal values
Both calls essentially only differ in one boolean, which dictates
whether to print the value in uppercase or lowercase.

Move the long function call into a new function and pass in the
"uppercase" boolean seperately to avoid having to write everything
twice.
2022-04-14 03:12:56 +04:30
Tim Schumacher 0d5098fdc0 AK: Merge print_i64 into print_signed_number
Those functions only differ by the input type of `number`. No other
wrapper does this, as they rely on adjusting the type of the argument on
the caller side instead.

Avoid specializing too much by just doing the same for signed numbers.
2022-04-14 03:12:56 +04:30
Andreas Kling 83082b12b7 LibWeb: Make reverse iterators work for const NonnullPtrVectors 2022-04-13 19:52:25 +02:00
Andreas Kling 40f584a2bb AK: Add missing include to Traits.h 2022-04-10 19:18:16 +02:00
Andreas Kling ae6b09f4dc AK: Add hash traits for floating-point primitives
This allows us to use float and double as hash keys.
2022-04-10 12:39:44 +02:00
Jelle Raaijmakers 1577a8ba42 AK: Remove KERNEL check from String
Since we no longer use `String` inside of the kernel code, we can drop
this `#ifndef`.
2022-04-10 12:08:31 +02:00
Andreas Kling 79c77debb0 AK: Don't destructively re-encode query strings in the URL parser
We were decoding and then re-encoding the query string in URLs.
This round-trip caused us to lose information about plus ('+')
ASCII characters encoded as "%2B".
2022-04-10 01:37:45 +02:00
Andreas Kling 3724ce765e AK+LibWeb: Encode ' ' as '+' in application/x-www-form-urlencoded
This matches what the URL and HTML specifications ask us to do.
2022-04-10 01:37:45 +02:00
GeekFiftyFive 832920c003 AK+LibHTTP: Revert prior change to percent encode plus signs
A change was made prior to percent encode plus signs in order to fix an
issue with the Google cookie consent page.

Unforunately, this was treating a symptom of a problem and not the root
cause and is incorrect behavior.
2022-04-08 20:44:49 +02:00
Sam Atkins c0ca6e470f AK+Userland: Rename Array::front/back to first/last
This is the name that is used for every other collection type so let's
be consistent.
2022-04-06 14:31:52 +02:00
kleines Filmröllchen 7b145d810a AK: Add const version of Vector::first_matching 2022-04-06 12:47:50 +02:00
kleines Filmröllchen ff8ca811c7 AK: Add find_first_index to NonnullPtrVector that strips smart pointer
When we want to use the find_first_index that base Vector provides, we
need to provide an element of the real contained type. That's impossible
for OwnPtr, however, and even with RefPtr there might be instances where
we have a raw reference to the object we want to find, but no smart
pointer. Therefore, overloading this function (with an identical body,
the magic is done by the find_index templatization) with `T const&` as a
parameter allows there use cases.
2022-04-06 12:47:50 +02:00
Timothy Flynn 9e5abec6f1 AK: Invalidate UTF-8 encoded code points larger than U+10ffff
On oss-fuzz, the LibJS REPL is provided a file encoded with Windows-1252
with the following contents:

    /ô¡°½/

The REPL assumes the input file is UTF-8. So in Windows-1252, the above
is represented as [0x2f 0xf4 0xa1 0xb0 0xbd 0x2f]. The inner 4 bytes are
actually a valid UTF-8 encoding if we only look at the most significant
bits to parse leading/continuation bytes. However, it decodes to the
code point U+121c3d, which is not a valid code point.

This commit adds additional validation to ensure the decoded code point
itself is also valid.
2022-04-05 00:14:29 +01:00
Ali Mohammad Pur 188207ed79 AK: Make Vector<T>::{first,last}_matching() return Optional<T&>
These functions are _very_ misleading, as `first()` and `last()` return
references, but `{first,last}_matching()` return copies of the values.
This commit makes it so that they now return Optional<T&>, eliminating
the copy and the confusion.
2022-04-04 12:48:31 +02:00
Ali Mohammad Pur 33e27c545e AK: Return Optional<T&> from HashMap<..., T>::get()
This avoids a useless copy of the value, as most of the users (except
one) actually just need a reference to the value.
2022-04-04 12:48:31 +02:00
Ali Mohammad Pur 1a74895680 AK: Return Optional<ConstPeekType> for HashMap::get() const
While the previous implementation always copied the object, returning a
non-const reference to a const object is not valid.
2022-04-04 12:48:31 +02:00
Ali Mohammad Pur 221ecf17d3 AK: Allow Optional<T&> to exist
This implements Optional<T&> as a T*, whose presence has been missing
since the early days of Optional.
As a lot of find_foo() APIs return an Optional<T> which imposes a
pointless copy on the underlying value, and can sometimes be very
misleading, with this change, those APIs can return Optional<T&>.
2022-04-04 12:48:31 +02:00
Idan Horowitz 1787d94907 AK: Add begin_from(V&) APIs to IntrusiveRedBlackTree
This method exploits the fact that the values themselves hold the tree
pointers, and as a result this let's us skip the O(logn) traversal down
to the matching Node for a Key-Value pair.
2022-04-04 00:16:11 +02:00
Tim Schumacher 8209c2b570 AK: Add StringView::copy_characters_to_buffer() 2022-04-03 19:15:14 +02:00
kleines Filmröllchen 7a0cd6793e AK: Add non-const iterator for CircularQueue 2022-04-03 09:49:08 -07:00
serenityosrocks 4a6a7cf3c8 AK: Add generic sincos solution for non-x86 platforms 2022-04-03 00:31:41 +01:00
Ben Maxwell 0f2c1f804e AK: Add last() utility function to Span 2022-04-02 21:50:41 +02:00
GeekFiftyFive 737f5b26b7 AK+LibHTTP: Ensure plus signs are percent encoded in query string
Adds a new optional parameter 'reserved_chars' to
AK::URL::percent_encode. This new optional parameter allows the caller
to specify custom characters to be percent encoded. This is then used
to percent encode plus signs by HttpRequest::to_raw_request.
2022-04-02 18:43:15 +02:00
Hendiadyoin1 5ba5a6615d AK: Add vector variants of sqrt and rsqrt 2022-04-02 18:37:38 +02:00
Hendiadyoin1 b1db1e4e4f AK: Add rsqrt and a SSE specific implementation for sqrt 2022-04-02 18:37:38 +02:00
Idan Horowitz 086969277e Everywhere: Run clang-format 2022-04-01 21:24:45 +01:00
kleines Filmröllchen 09a12247fb AK: Use bucket states with special bit patterns in HashTable
This simplifies some of the bucket state handling code, as there's now
an easy way of checking the basic category of bucket state.
2022-03-31 12:06:13 +02:00
kleines Filmröllchen 49d29c8298 AK: Rehash HashTable in-place instead of shrinking
As seen on TV, HashTable can get "thrashed", i.e. it has a bunch of
deleted buckets that count towards the load factor. This means that hash
tables which are large enough for their contents need to be resized.
This was fixed in 9d8da16 with a workaround that shrinks the HashTable
back down in these cases, as after the resize and re-hash the load
factor is very low again. However, that's not a good solution. If you
insert and remove repeatedly around a size boundary, you might get
frequent resizes, which involve frequent re-allocations.

The new solution is an in-place rehashing algorithm that I came up with.
(Do complain to me, I'm at fault.) Basically, it iterates the buckets
and re-hashes the used buckets while marking the deleted slots empty.
The issue arises with collisions in the re-hash. For this reason, there
are two kinds of used buckets during the re-hashing: the normal "used"
buckets, which are old and are treated as free space, and the
"re-hashed" buckets, which are new and treated as used space, i.e. they
trigger probing. Therefore, the procedure for relocating a bucket's
contents is as follows:
- Locate the "real" bucket of the contents with the hash. That bucket is
  the starting point for the target bucket, and the current (old) bucket
  is the bucket we want to move.
- While we still need to move the bucket:
  - If we're the target, something strange happened last iteration or we
    just re-hashed to the same location. We're done.
  - If the target is empty or deleted, just move the bucket. We're done.
  - If the target is a re-hashed full bucket, we probe by double-hashing
    our hash as usual. Henceforth, we move our target for the next
    iteration.
  - If the target is an old full bucket, we swap the target and to-move
buckets. Therefore, the bucket to move is a the correct location and the
former target, which still needs to find a new place, is now in the
bucket to move. So we can just continue with the loop; the target is
re-obtained from the bucket to move. This happens for each and every
bucket, though some buckets are "coincidentally" moved before their
point of iteration is reached. Either way, this guarantees full in-place
movement (even without stack storage) and therefore space complexity of
O(1). Time complexity is amortized O(2n) asssuming a good hashing
function.

This leads to a performance improvement of ~30% on the benchmark
introduced with the last commit.

Co-authored-by: Hendiadyoin1 <leon.a@serenityos.org>
2022-03-31 12:06:13 +02:00
kleines Filmröllchen bcb8937898 AK: Merge HashTable bucket state into one enum
The hash table buckets had three different state booleans that are in
fact exclusive. In preparation for further states, this commit
consolidates them into one enum. This has the added benefit on not
relying on the compiler's boolean packing anymore; we definitely now
only need one byte for the bucket state.
2022-03-31 12:06:13 +02:00
safarp 704e1d13f4 AK: Allow printing wide characters using %ls modifier 2022-03-30 11:30:43 +04:30
Ali Mohammad Pur 67357fe984 LibXML: Add a fairly basic XML parser
Currently this can parse XML and resolve external resources/references,
and read a DTD (but not apply or verify its rules).
That's good enough for _most_ XHTML documents as the HTML 5 spec
enforces its own rules about document well-formedness, and does not make
use of XML DTDs (aside from a list of predefined entities).

An accompanying `xml` utility is provided that can read and dump XML
documents, and can also run the XML conformance test suite.
2022-03-28 23:11:48 +02:00
Ali Mohammad Pur 06cedf5bae AK: Add a 'OneOf' concept
Similar to 'SameAs', but for multiple types.
2022-03-28 23:11:48 +02:00
Ali Mohammad Pur 2a1a619eed AK: Display SourceLocation function name in color
It's much easier to spot the function name (which is what you often
expect) like this.
2022-03-28 23:11:48 +02:00
Ali Mohammad Pur b3c18db463 AK: Add a 'is_not_any_of' similar to 'is_any_of' to GenericLexer
It's often useful to have the negated version, so instead of making a
local lambda for it, let's just add the negated form too.
2022-03-28 23:11:48 +02:00
Ali Mohammad Pur e21fa158dd AK: Make Vector capable of holding forward-declared types
This is pretty useful for making trees.
2022-03-28 23:11:48 +02:00
Hendiadyoin1 6b20496758 AK: Add appendln helper to SourceGenerator 2022-03-28 23:08:08 +02:00
Hendiadyoin1 f6f7280fe3 AK: Explicitly move value String in SourceGenerator::set 2022-03-28 23:08:08 +02:00
Hendiadyoin1 14caecefb1 AK: Make SourceGenerator move constructible
This makes us able to return one from a function
2022-03-28 23:08:08 +02:00
Linus Groh 22308e52cf AK: Add an ArbitrarySizedEnum template
This is an enum-like type that works with arbitrary sized storage > u64,
which is the limit for a regular enum class - which limits it to 64
members when needing bit field behavior.

Co-authored-by: Ali Mohammad Pur <mpfard@serenityos.org>
2022-03-27 18:54:56 +02:00
Linus Groh 8b2361e362 AK: Add non-const DistinctNumeric::value() getter 2022-03-27 18:54:56 +02:00
Linus Groh 76e85ebbfc AK: Remove unused String.h include from UFixedBigInt.h
This makes it usable in the Kernel. :^)
2022-03-27 18:54:56 +02:00
Idan Horowitz 5626e1b324 LibWeb: Rename PARSER_DEBUG => HTML_PARSER_DEBUG
Since this macro was created we gained a couple more parsers in the
system :^)
2022-03-24 21:37:49 +01:00
Hendiadyoin1 820e03e8d4 AK: Add a case insensitive of is_one_of to String[View] 2022-03-21 10:48:17 +01:00
Sam Atkins dfc02f9761 AK: Fix typo in warnln_if() 2022-03-19 11:01:49 -07:00
Sam Atkins 7e98c8eaf6 AK+Tests: Fix StringUtils::contains() being confused by repeating text
Previously, case-insensitively searching the haystack "Go Go Back" for
the needle "Go Back" would return false:

1. Match the first three characters. "Go ".
2. Notice that 'G' and 'B' don't match.
3. Skip ahead 3 characters, plus 1 for the outer for-loop.
4. Now, the haystack is effectively "o Back", so the match fails.

Reducing the skip by 1 fixes this issue. I'm not 100% convinced this
fixes all cases, but I haven't been able to find any cases where it
doesn't work now. :^)
2022-03-18 23:51:56 +00:00
Lenny Maiorani 4c5e9f5633 Everywhere: Deduplicate day/month name constants
Day and month name constants are defined in numerous places. This
pulls them together into a single place and eliminates the
duplication. It also ensures they are `constexpr`.
2022-03-18 23:48:50 +00:00
Timothy Flynn 31515a9147 AK: Mark the StringView user-defined literal as consteval
Even though the StringView(char*, size_t) constructor only runs its
overflow check when evaluated in a runtime context, the code generated
here could prevent the compiler from optimizing invocations from the
StringView user-defined literal (verified on Compiler Explorer).

This changes the user-defined literal declaration to be consteval to
ensure it is evaluated at compile time.
2022-03-18 19:56:50 +01:00
Andreas Kling fc6b7fcd97 AK: Add const variant of Vector::in_reverse() 2022-03-18 15:18:48 +01:00
Lenny Maiorani 2844f7c333 Everywhere: Switch from EnableIf to requires
C++20 provides the `requires` clause which simplifies the ability to
limit overload resolution. Prefer it over `EnableIf`

With all uses of `EnableIf` being removed, also remove the
implementation so future devs are not tempted.
2022-03-17 22:15:42 -07:00
Michiel Visser 3d561abe15 AK: Add constant time equality and zero check to UFixedBigInt 2022-03-18 07:56:47 +03:30
Michiel Visser 590dcb0581 AK: UFixedBigInt add efficient multiplication with full result 2022-03-18 07:56:47 +03:30
Lenny Maiorani 5b59375a56 AK: Fix implicit and narrowing conversions in Base64 2022-03-16 16:19:53 +00:00
Lenny Maiorani 8d1d4d4f09 AK: Make static constexpr variables to avoid stack copy in Base64
Alphabet and lookup table are created and copied to the stack on each
call. Create them and store them in static memory.
2022-03-16 16:19:53 +00:00
Daniel Bertalan e3eb68dd58 AK+Kernel: Avoid double memory clearing of HashTable buckets
Since the allocated memory is going to be zeroed immediately anyway,
let's avoid redundantly scrubbing it with MALLOC_SCRUB_BYTE just before
that.

The latest versions of gcc and Clang can automatically do this malloc +
memset -> calloc optimization, but I've seen a couple of places where it
failed to be done.

This commit also adds a naive kcalloc function to the kernel that
doesn't (yet) eliminate the redundancy like the userland does.
2022-03-15 11:56:46 +01:00
Hendiadyoin1 cd21e03225 AK+Everywhere: Add sincos and use it in some places
Calculating sin and cos at once is quite a bit cheaper than calculating
them individually.
x87 has even a dedicated instruction for it: `fsincos`.
2022-03-15 11:39:42 +01:00
Timothy Flynn c12cfe83b7 AK: Allow creating a Vector from any Span of the same underlying type
This allows, for example, to create a Vector from a subset of another
Vector.
2022-03-14 16:33:15 +01:00